code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """cvt""" def __init__(self : int , UpperCamelCase : List[Any]=3 , UpperCamelCase : int=[7, 3, 3] , UpperCamelCase : str=[4, 2, 2] , UpperCamelCase : Dict=[2, 1, 1] , UpperCamelCase : Dict=[64, 192, 384] , UpperCamelCase : Dict=[1, 3, 6] , UpperCamelCase : Dict=[1, 2, 10] , UpperCamelCase : Any=[4.0, 4.0, 4.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : int=[0.0, 0.0, 0.1] , UpperCamelCase : Any=[True, True, True] , UpperCamelCase : int=[False, False, True] , UpperCamelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase : Optional[int]=[3, 3, 3] , UpperCamelCase : Tuple=[1, 1, 1] , UpperCamelCase : Any=[2, 2, 2] , UpperCamelCase : Dict=[1, 1, 1] , UpperCamelCase : List[str]=[1, 1, 1] , UpperCamelCase : str=0.02 , UpperCamelCase : int=1E-12 , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
2
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = ShapEImgaImgPipeline lowerCAmelCase__ : List[str] = ["""image"""] lowerCAmelCase__ : Any = ["""image"""] lowerCAmelCase__ : Any = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] lowerCAmelCase__ : Tuple = False @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : str ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase__ (self : int ): '''simple docstring''' return 8 @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(UpperCamelCase ) return model @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase , do_normalize=UpperCamelCase , do_resize=UpperCamelCase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def UpperCamelCase__ (self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase__ = PriorTransformer(**UpperCamelCase ) return model @property def UpperCamelCase__ (self : int ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**UpperCamelCase ) return model def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase , clip_sample=UpperCamelCase , clip_sample_range=1.0 , ) lowercase__ = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : str=0 ): '''simple docstring''' lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) if str(UpperCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(UpperCamelCase ) else: lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowercase__ = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = '''cpu''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = pipe(**self.get_dummy_inputs(UpperCamelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = torch_device == '''cpu''' lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase , relax_max_difference=UpperCamelCase , ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(UpperCamelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**UpperCamelCase , num_images_per_prompt=UpperCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase__ = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(0 ) lowercase__ = pipe( UpperCamelCase , generator=UpperCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available lowerCamelCase : str = logging.getLogger(__name__) @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : str lowerCAmelCase__ : List[str] lowerCAmelCase__ : Optional[List[str]] @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : List[int] lowerCAmelCase__ : List[int] lowerCAmelCase__ : Optional[List[int]] = None lowerCAmelCase__ : Optional[List[int]] = None class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Dict = """train""" lowerCAmelCase__ : Any = """dev""" lowerCAmelCase__ : List[str] = """test""" class __lowerCAmelCase : '''simple docstring''' @staticmethod def UpperCamelCase__ (UpperCamelCase : Dict , UpperCamelCase : Union[Split, str] ): '''simple docstring''' raise NotImplementedError @staticmethod def UpperCamelCase__ (UpperCamelCase : str ): '''simple docstring''' raise NotImplementedError @staticmethod def UpperCamelCase__ (UpperCamelCase : List[InputExample] , UpperCamelCase : List[str] , UpperCamelCase : int , UpperCamelCase : PreTrainedTokenizer , UpperCamelCase : str=False , UpperCamelCase : Dict="[CLS]" , UpperCamelCase : Optional[int]=1 , UpperCamelCase : int="[SEP]" , UpperCamelCase : Optional[Any]=False , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : Tuple=0 , UpperCamelCase : Dict=0 , UpperCamelCase : List[Any]=-100 , UpperCamelCase : int=0 , UpperCamelCase : str=True , ): '''simple docstring''' lowercase__ = {label: i for i, label in enumerate(UpperCamelCase )} lowercase__ = [] for ex_index, example in enumerate(UpperCamelCase ): if ex_index % 10000 == 0: logger.info('''Writing example %d of %d''' , UpperCamelCase , len(UpperCamelCase ) ) lowercase__ = [] lowercase__ = [] for word, label in zip(example.words , example.labels ): lowercase__ = tokenizer.tokenize(UpperCamelCase ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(UpperCamelCase ) > 0: tokens.extend(UpperCamelCase ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(UpperCamelCase ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. lowercase__ = tokenizer.num_special_tokens_to_add() if len(UpperCamelCase ) > max_seq_length - special_tokens_count: lowercase__ = tokens[: (max_seq_length - special_tokens_count)] lowercase__ = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] lowercase__ = [sequence_a_segment_id] * len(UpperCamelCase ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: lowercase__ = [cls_token] + tokens lowercase__ = [pad_token_label_id] + label_ids lowercase__ = [cls_token_segment_id] + segment_ids lowercase__ = tokenizer.convert_tokens_to_ids(UpperCamelCase ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. lowercase__ = [1 if mask_padding_with_zero else 0] * len(UpperCamelCase ) # Zero-pad up to the sequence length. lowercase__ = max_seq_length - len(UpperCamelCase ) if pad_on_left: lowercase__ = ([pad_token] * padding_length) + input_ids lowercase__ = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask lowercase__ = ([pad_token_segment_id] * padding_length) + segment_ids lowercase__ = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(UpperCamelCase ) == max_seq_length assert len(UpperCamelCase ) == max_seq_length assert len(UpperCamelCase ) == max_seq_length assert len(UpperCamelCase ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(UpperCamelCase ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(UpperCamelCase ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(UpperCamelCase ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(UpperCamelCase ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(UpperCamelCase ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ = None features.append( InputFeatures( input_ids=UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , label_ids=UpperCamelCase ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[InputFeatures] lowerCAmelCase__ : int = nn.CrossEntropyLoss().ignore_index def __init__(self : str , UpperCamelCase : TokenClassificationTask , UpperCamelCase : str , UpperCamelCase : PreTrainedTokenizer , UpperCamelCase : List[str] , UpperCamelCase : str , UpperCamelCase : Optional[int] = None , UpperCamelCase : int=False , UpperCamelCase : Split = Split.train , ): '''simple docstring''' lowercase__ = os.path.join( UpperCamelCase , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(UpperCamelCase ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. lowercase__ = cached_features_file + '''.lock''' with FileLock(UpperCamelCase ): if os.path.exists(UpperCamelCase ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) lowercase__ = torch.load(UpperCamelCase ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) lowercase__ = token_classification_task.read_examples_from_file(UpperCamelCase , UpperCamelCase ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ = token_classification_task.convert_examples_to_features( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=UpperCamelCase , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f"Saving features into cached file {cached_features_file}" ) torch.save(self.features , UpperCamelCase ) def __len__(self : Tuple ): '''simple docstring''' return len(self.features ) def __getitem__(self : Tuple , UpperCamelCase : Optional[int] ): '''simple docstring''' return self.features[i] if is_tf_available(): import tensorflow as tf class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : List[InputFeatures] lowerCAmelCase__ : int = -100 def __init__(self : Any , UpperCamelCase : TokenClassificationTask , UpperCamelCase : str , UpperCamelCase : PreTrainedTokenizer , UpperCamelCase : List[str] , UpperCamelCase : str , UpperCamelCase : Optional[int] = None , UpperCamelCase : Optional[Any]=False , UpperCamelCase : Split = Split.train , ): '''simple docstring''' lowercase__ = token_classification_task.read_examples_from_file(UpperCamelCase , UpperCamelCase ) # TODO clean up all this to leverage built-in features of tokenizers lowercase__ = token_classification_task.convert_examples_to_features( UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=UpperCamelCase , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: lowercase__ = tf.data.Dataset.from_generator( UpperCamelCase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: lowercase__ = tf.data.Dataset.from_generator( UpperCamelCase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__(self : List[Any] ): '''simple docstring''' return len(self.features ) def __getitem__(self : int , UpperCamelCase : Dict ): '''simple docstring''' return self.features[i]
2
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" return int((input_a, input_a).count(0 ) == 0 ) def _SCREAMING_SNAKE_CASE () -> None: """simple docstring""" assert and_gate(0 , 0 ) == 0 assert and_gate(0 , 1 ) == 0 assert and_gate(1 , 0 ) == 0 assert and_gate(1 , 1 ) == 1 if __name__ == "__main__": test_and_gate() print(and_gate(1, 0)) print(and_gate(0, 0)) print(and_gate(0, 1)) print(and_gate(1, 1))
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
1
'''simple docstring''' import operator as op def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [] lowercase__ = lambda A , A : int(x / y ) # noqa: E731 integer division operation lowercase__ = { '''^''': op.pow, '''*''': op.mul, '''/''': div, '''+''': op.add, '''-''': op.sub, } # operators & their respective operation # print table header print('''Symbol'''.center(8 ) , '''Action'''.center(12 ) , '''Stack''' , sep=''' | ''' ) print('''-''' * (30 + len(A )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(A ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('''push(''' + x + ''')''').ljust(12 ) , ''','''.join(A ) , sep=''' | ''' ) else: lowercase__ = stack.pop() # pop stack # output in tabular format print(''''''.rjust(8 ) , ('''pop(''' + b + ''')''').ljust(12 ) , ''','''.join(A ) , sep=''' | ''' ) lowercase__ = stack.pop() # pop stack # output in tabular format print(''''''.rjust(8 ) , ('''pop(''' + a + ''')''').ljust(12 ) , ''','''.join(A ) , sep=''' | ''' ) stack.append( str(opr[x](int(A ) , int(A ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('''push(''' + a + x + b + ''')''').ljust(12 ) , ''','''.join(A ) , sep=''' | ''' , ) return int(stack[0] ) if __name__ == "__main__": lowerCamelCase : Tuple = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ') print('\n\tResult = ', solve(Postfix))
2
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
1
'''simple docstring''' import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import faiss import torch from datasets import Features, Sequence, Value, load_dataset from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser lowerCamelCase : Dict = logging.getLogger(__name__) torch.set_grad_enabled(False) lowerCamelCase : List[Any] = 'cuda' if torch.cuda.is_available() else 'cpu' def _SCREAMING_SNAKE_CASE (A , A=100 , A=" " ) -> List[str]: """simple docstring""" lowercase__ = text.split(A ) return [character.join(text[i : i + n] ).strip() for i in range(0 , len(A ) , A )] def _SCREAMING_SNAKE_CASE (A ) -> dict: """simple docstring""" lowercase__ ,lowercase__ = [], [] for title, text in zip(documents['''title'''] , documents['''text'''] ): if text is not None: for passage in split_text(A ): titles.append(title if title is not None else '''''' ) texts.append(A ) return {"title": titles, "text": texts} def _SCREAMING_SNAKE_CASE (A , A , A ) -> dict: """simple docstring""" lowercase__ = ctx_tokenizer( documents['''title'''] , documents['''text'''] , truncation=A , padding='''longest''' , return_tensors='''pt''' )['''input_ids'''] lowercase__ = ctx_encoder(input_ids.to(device=A ) , return_dict=A ).pooler_output return {"embeddings": embeddings.detach().cpu().numpy()} def _SCREAMING_SNAKE_CASE (A , A , A , ) -> List[str]: """simple docstring""" logger.info('''Step 1 - Create the dataset''' ) ###################################### # The dataset needed for RAG must have three columns: # - title (string): title of the document # - text (string): text of a passage of the document # - embeddings (array of dimension d): DPR representation of the passage # Let's say you have documents in tab-separated csv files with columns "title" and "text" assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file" # You can load a Dataset object this way lowercase__ = load_dataset( '''csv''' , data_files=[rag_example_args.csv_path] , split='''train''' , delimiter='''\t''' , column_names=['''title''', '''text'''] ) # More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files # Then split the documents into passages of 100 words lowercase__ = dataset.map(A , batched=A , num_proc=processing_args.num_proc ) # And compute the embeddings lowercase__ = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=A ) lowercase__ = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ) lowercase__ = Features( {'''text''': Value('''string''' ), '''title''': Value('''string''' ), '''embeddings''': Sequence(Value('''float32''' ) )} ) # optional, save as float32 instead of float64 to save space lowercase__ = dataset.map( partial(A , ctx_encoder=A , ctx_tokenizer=A ) , batched=A , batch_size=processing_args.batch_size , features=A , ) # And finally save your dataset lowercase__ = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset''' ) dataset.save_to_disk(A ) # from datasets import load_from_disk # dataset = load_from_disk(passages_path) # to reload the dataset ###################################### logger.info('''Step 2 - Index the dataset''' ) ###################################### # Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search lowercase__ = faiss.IndexHNSWFlat(index_hnsw_args.d , index_hnsw_args.m , faiss.METRIC_INNER_PRODUCT ) dataset.add_faiss_index('''embeddings''' , custom_index=A ) # And save the index lowercase__ = os.path.join(rag_example_args.output_dir , '''my_knowledge_dataset_hnsw_index.faiss''' ) dataset.get_index('''embeddings''' ).save(A ) # dataset.load_faiss_index("embeddings", index_path) # to reload the index @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : str = field( default=str(Path(lowercase_ ).parent / """test_run""" / """dummy-kb""" / """my_knowledge_dataset.csv""" ) , metadata={"""help""": """Path to a tab-separated csv file with columns 'title' and 'text'"""} , ) lowerCAmelCase__ : Optional[str] = field( default=lowercase_ , metadata={"""help""": """Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."""} , ) lowerCAmelCase__ : str = field( default="""facebook/rag-sequence-nq""" , metadata={"""help""": """The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"""} , ) lowerCAmelCase__ : str = field( default="""facebook/dpr-ctx_encoder-multiset-base""" , metadata={ """help""": ( """The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or""" """ 'facebook/dpr-ctx_encoder-multiset-base'""" ) } , ) lowerCAmelCase__ : Optional[str] = field( default=str(Path(lowercase_ ).parent / """test_run""" / """dummy-kb""" ) , metadata={"""help""": """Path to a directory where the dataset passages and the index will be saved"""} , ) @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : Optional[int] = field( default=lowercase_ , metadata={ """help""": """The number of processes to use to split the documents into passages. Default is single process.""" } , ) lowerCAmelCase__ : int = field( default=16 , metadata={ """help""": """The batch size to use when computing the passages embeddings using the DPR context encoder.""" } , ) @dataclass class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : int = field( default=768 , metadata={"""help""": """The dimension of the embeddings to pass to the HNSW Faiss index."""} , ) lowerCAmelCase__ : int = field( default=128 , metadata={ """help""": ( """The number of bi-directional links created for every new element during the HNSW index construction.""" ) } , ) if __name__ == "__main__": logging.basicConfig(level=logging.WARNING) logger.setLevel(logging.INFO) lowerCamelCase : Optional[Any] = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments)) lowerCamelCase , lowerCamelCase , lowerCamelCase : Union[str, Any] = parser.parse_args_into_dataclasses() with TemporaryDirectory() as tmp_dir: lowerCamelCase : Optional[int] = rag_example_args.output_dir or tmp_dir main(rag_example_args, processing_args, index_hnsw_args)
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''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" lowercase__ = (boundary[1] - boundary[0]) / steps lowercase__ = boundary[0] lowercase__ = boundary[1] lowercase__ = make_points(A , A , A ) lowercase__ = 0.0 y += (h / 2.0) * f(A ) for i in x_i: # print(i) y += h * f(A ) y += (h / 2.0) * f(A ) return y def _SCREAMING_SNAKE_CASE (A , A , A ) -> int: """simple docstring""" lowercase__ = a + h while x < (b - h): yield x lowercase__ = x + h def _SCREAMING_SNAKE_CASE (A ) -> Any: # enter your function here """simple docstring""" lowercase__ = (x - 0) * (x - 0) return y def _SCREAMING_SNAKE_CASE () -> List[str]: """simple docstring""" lowercase__ = 0.0 # Lower bound of integration lowercase__ = 1.0 # Upper bound of integration lowercase__ = 10.0 # define number of steps or resolution lowercase__ = [a, b] # define boundary of integration lowercase__ = method_a(A , A ) print(f"y = {y}" ) if __name__ == "__main__": main()
2
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[str] = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """unispeech-sat""" def __init__(self : Any , UpperCamelCase : Tuple=32 , UpperCamelCase : Tuple=768 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[str]=12 , UpperCamelCase : str=3072 , UpperCamelCase : Dict="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Union[str, Any]=0.1 , UpperCamelCase : Union[str, Any]=0.1 , UpperCamelCase : Optional[Any]=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : int=0.1 , UpperCamelCase : Union[str, Any]=0.1 , UpperCamelCase : str=0.02 , UpperCamelCase : List[Any]=1E-5 , UpperCamelCase : Tuple="group" , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : str=(512, 512, 512, 512, 512, 512, 512) , UpperCamelCase : Optional[int]=(5, 2, 2, 2, 2, 2, 2) , UpperCamelCase : Dict=(10, 3, 3, 3, 3, 2, 2) , UpperCamelCase : Optional[int]=False , UpperCamelCase : Dict=128 , UpperCamelCase : List[str]=16 , UpperCamelCase : List[str]=False , UpperCamelCase : List[Any]=True , UpperCamelCase : List[Any]=0.05 , UpperCamelCase : int=10 , UpperCamelCase : Dict=2 , UpperCamelCase : int=0.0 , UpperCamelCase : List[str]=10 , UpperCamelCase : int=0 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : int=2 , UpperCamelCase : str=0.1 , UpperCamelCase : Optional[Any]=100 , UpperCamelCase : List[str]=256 , UpperCamelCase : Union[str, Any]=256 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any="mean" , UpperCamelCase : Optional[Any]=False , UpperCamelCase : Tuple=False , UpperCamelCase : Optional[int]=256 , UpperCamelCase : Any=(512, 512, 512, 512, 1500) , UpperCamelCase : str=(5, 3, 3, 1, 1) , UpperCamelCase : List[Any]=(1, 2, 3, 1, 1) , UpperCamelCase : str=512 , UpperCamelCase : Tuple=0 , UpperCamelCase : int=1 , UpperCamelCase : Optional[int]=2 , UpperCamelCase : Optional[Any]=504 , **UpperCamelCase : List[Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase , pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase ) lowercase__ = hidden_size lowercase__ = feat_extract_norm lowercase__ = feat_extract_activation lowercase__ = list(UpperCamelCase ) lowercase__ = list(UpperCamelCase ) lowercase__ = list(UpperCamelCase ) lowercase__ = conv_bias lowercase__ = num_conv_pos_embeddings lowercase__ = num_conv_pos_embedding_groups lowercase__ = len(self.conv_dim ) lowercase__ = num_hidden_layers lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = num_attention_heads lowercase__ = hidden_dropout lowercase__ = attention_dropout lowercase__ = activation_dropout lowercase__ = feat_proj_dropout lowercase__ = final_dropout lowercase__ = layerdrop lowercase__ = layer_norm_eps lowercase__ = initializer_range lowercase__ = vocab_size lowercase__ = num_clusters lowercase__ = do_stable_layer_norm lowercase__ = use_weighted_layer_sum 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 lowercase__ = apply_spec_augment lowercase__ = mask_time_prob lowercase__ = mask_time_length lowercase__ = mask_time_min_masks lowercase__ = mask_feature_prob lowercase__ = mask_feature_length lowercase__ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations lowercase__ = num_codevectors_per_group lowercase__ = num_codevector_groups lowercase__ = contrastive_logits_temperature lowercase__ = feat_quantizer_dropout lowercase__ = num_negatives lowercase__ = codevector_dim lowercase__ = proj_codevector_dim lowercase__ = diversity_loss_weight # ctc loss lowercase__ = ctc_loss_reduction lowercase__ = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowercase__ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowercase__ = list(UpperCamelCase ) lowercase__ = list(UpperCamelCase ) lowercase__ = list(UpperCamelCase ) lowercase__ = xvector_output_dim @property def UpperCamelCase__ (self : Any ): '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """megatron-bert""" def __init__(self : Tuple , UpperCamelCase : Optional[int]=29056 , UpperCamelCase : Optional[Any]=1024 , UpperCamelCase : Any=24 , UpperCamelCase : int=16 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : int="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any=512 , UpperCamelCase : int=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Optional[int]="absolute" , UpperCamelCase : List[Any]=True , **UpperCamelCase : str , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache
2
1
'''simple docstring''' import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def __init__(self : Tuple , UpperCamelCase : int , UpperCamelCase : str=13 , UpperCamelCase : Optional[int]=7 , UpperCamelCase : Any=True , UpperCamelCase : int=True , UpperCamelCase : Optional[int]=True , UpperCamelCase : Optional[Any]=True , UpperCamelCase : Optional[Any]=99 , UpperCamelCase : Any=32 , UpperCamelCase : Tuple=5 , UpperCamelCase : str=4 , UpperCamelCase : Optional[int]=37 , UpperCamelCase : Any="gelu" , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Dict=0.1 , UpperCamelCase : List[Any]=512 , UpperCamelCase : List[Any]=16 , UpperCamelCase : List[Any]=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=4 , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_token_type_ids lowercase__ = use_labels 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__ = type_vocab_size lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = num_choices def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=UpperCamelCase , ) return config, input_ids, attention_mask def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = FlaxDistilBertModelTester(self ) @slow def UpperCamelCase__ (self : List[str] ): '''simple docstring''' for model_class_name in self.all_model_classes: lowercase__ = model_class_name.from_pretrained('''distilbert-base-uncased''' ) lowercase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(UpperCamelCase ) @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = FlaxDistilBertModel.from_pretrained('''distilbert-base-uncased''' ) lowercase__ = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) lowercase__ = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase )[0] lowercase__ = (1, 11, 768) self.assertEqual(output.shape , UpperCamelCase ) lowercase__ = np.array([[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , UpperCamelCase , atol=1E-4 ) )
2
'''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
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCamelCase : int = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[Any] = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys lowerCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
1
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCamelCase : Optional[Any] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) lowerCamelCase : Tuple = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) lowerCamelCase : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) lowerCamelCase : Any = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) lowerCamelCase : Tuple = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) lowerCamelCase : Optional[int] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) lowerCamelCase : Dict = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ = randrange(len(A ) ), randrange(len(A ) ) lowercase__ = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] lowercase__ ,lowercase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE (A = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(A )) @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" assert PokerHand(A )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = PokerHand(A ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" assert PokerHand(A )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = [PokerHand(A ) for hand in SORTED_HANDS] lowercase__ = poker_hands.copy() shuffle(A ) lowercase__ = chain(sorted(A ) ) for index, hand in enumerate(A ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=A ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE () -> int: """simple docstring""" lowercase__ = PokerHand('''2C 4S AS 3D 5C''' ) lowercase__ = True lowercase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = 0 lowercase__ = os.path.abspath(os.path.dirname(A ) ) lowercase__ = os.path.join(A , '''poker_hands.txt''' ) with open(A ) as file_hand: for line in file_hand: lowercase__ = line[:14].strip() lowercase__ = line[15:].strip() lowercase__ ,lowercase__ = PokerHand(A ), PokerHand(A ) lowercase__ = player.compare_with(A ) if output == "Win": answer += 1 assert answer == 376
2
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A , A ) -> float: """simple docstring""" if days_between_payments <= 0: raise ValueError('''days_between_payments must be > 0''' ) if daily_interest_rate < 0: raise ValueError('''daily_interest_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * daily_interest_rate * days_between_payments def _SCREAMING_SNAKE_CASE (A , A , A , ) -> float: """simple docstring""" if number_of_compounding_periods <= 0: raise ValueError('''number_of_compounding_periods must be > 0''' ) if nominal_annual_interest_rate_percentage < 0: raise ValueError('''nominal_annual_interest_rate_percentage must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return principal * ( (1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods - 1 ) def _SCREAMING_SNAKE_CASE (A , A , A , ) -> float: """simple docstring""" if number_of_years <= 0: raise ValueError('''number_of_years must be > 0''' ) if nominal_annual_percentage_rate < 0: raise ValueError('''nominal_annual_percentage_rate must be >= 0''' ) if principal <= 0: raise ValueError('''principal must be > 0''' ) return compound_interest( A , nominal_annual_percentage_rate / 365 , number_of_years * 365 ) if __name__ == "__main__": import doctest doctest.testmod()
2
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : str = Mapping[str, np.ndarray] lowerCamelCase : List[Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Any = 0.0_1 @dataclasses.dataclass(frozen=lowercase_ ) class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ : Optional[str] = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ : Optional[Sequence[str]] = None # Chain corresponding to each parent lowerCAmelCase__ : Optional[Sequence[int]] = None def _SCREAMING_SNAKE_CASE (A ) -> Protein: """simple docstring""" lowercase__ = R'''(\[[A-Z]+\]\n)''' lowercase__ = [tag.strip() for tag in re.split(A , A ) if len(A ) > 0] lowercase__ = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) lowercase__ = ["N", "CA", "C"] lowercase__ = None lowercase__ = None lowercase__ = None for g in groups: if "[PRIMARY]" == g[0]: lowercase__ = g[1][0].strip() for i in range(len(A ) ): if seq[i] not in residue_constants.restypes: lowercase__ = '''X''' # FIXME: strings are immutable lowercase__ = np.array( [residue_constants.restype_order.get(A , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowercase__ = [] for axis in range(3 ): tertiary.append(list(map(A , g[1][axis].split() ) ) ) lowercase__ = np.array(A ) lowercase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowercase__ = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) lowercase__ = np.zeros( ( len(A ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=A , atom_mask=A , aatype=A , residue_index=np.arange(len(A ) ) , b_factors=A , ) def _SCREAMING_SNAKE_CASE (A , A = 0 ) -> List[str]: """simple docstring""" lowercase__ = [] lowercase__ = prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) lowercase__ = prot.parents lowercase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowercase__ = [p for i, p in zip(A , A ) if i == chain_id] if parents is None or len(A ) == 0: lowercase__ = ['''N/A'''] pdb_headers.append(f"PARENT {' '.join(A )}" ) return pdb_headers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = [] lowercase__ = pdb_str.split('''\n''' ) lowercase__ = prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) lowercase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: lowercase__ = [] if prot.parents_chain_index is not None: lowercase__ = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(A ) , [] ) parent_dict[str(A )].append(A ) lowercase__ = max([int(A ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowercase__ = parent_dict.get(str(A ) , ['''N/A'''] ) parents_per_chain.append(A ) else: parents_per_chain.append(list(prot.parents ) ) else: lowercase__ = [['''N/A''']] def make_parent_line(A ) -> str: return f"PARENT {' '.join(A )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowercase__ = 0 for i, l in enumerate(A ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(A ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(A ): lowercase__ = parents_per_chain[chain_counter] else: lowercase__ = ['''N/A'''] out_pdb_lines.append(make_parent_line(A ) ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = residue_constants.restypes + ['''X'''] def res_atoa(A ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) lowercase__ = residue_constants.atom_types lowercase__ = [] lowercase__ = prot.atom_mask lowercase__ = prot.aatype lowercase__ = prot.atom_positions lowercase__ = prot.residue_index.astype(np.intaa ) lowercase__ = prot.b_factors lowercase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) lowercase__ = get_pdb_headers(A ) if len(A ) > 0: pdb_lines.extend(A ) lowercase__ = aatype.shape[0] lowercase__ = 1 lowercase__ = 0 lowercase__ = string.ascii_uppercase lowercase__ = None # Add all atom sites. for i in range(A ): lowercase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(A , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowercase__ = '''ATOM''' lowercase__ = atom_name if len(A ) == 4 else f" {atom_name}" lowercase__ = '''''' lowercase__ = '''''' lowercase__ = 1.00 lowercase__ = atom_name[0] # Protein supports only C, N, O, S, this works. lowercase__ = '''''' lowercase__ = '''A''' if chain_index is not None: lowercase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowercase__ = ( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(A ) atom_index += 1 lowercase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowercase__ = True lowercase__ = chain_index[i + 1] if should_terminate: # Close the chain. lowercase__ = '''TER''' lowercase__ = ( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(A ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(A , A ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _SCREAMING_SNAKE_CASE (A , A , A = None , A = None , A = None , A = None , A = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=A , remark=A , parents=A , parents_chain_index=A , )
2
1
'''simple docstring''' import pickle import numpy as np from matplotlib import pyplot as plt class __lowerCAmelCase : '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : Any , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : int=0.2 , UpperCamelCase : Optional[int]=0.2 ): '''simple docstring''' lowercase__ = bp_numa lowercase__ = bp_numa lowercase__ = bp_numa lowercase__ = conva_get[:2] lowercase__ = conva_get[2] lowercase__ = size_pa lowercase__ = rate_w lowercase__ = rate_t lowercase__ = [ np.mat(-1 * np.random.rand(self.conva[0] , self.conva[0] ) + 0.5 ) for i in range(self.conva[1] ) ] lowercase__ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowercase__ = np.mat(-1 * np.random.rand(self.num_bpa , self.num_bpa ) + 0.5 ) lowercase__ = -2 * np.random.rand(self.conva[1] ) + 1 lowercase__ = -2 * np.random.rand(self.num_bpa ) + 1 lowercase__ = -2 * np.random.rand(self.num_bpa ) + 1 def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = { '''num_bp1''': self.num_bpa, '''num_bp2''': self.num_bpa, '''num_bp3''': self.num_bpa, '''conv1''': self.conva, '''step_conv1''': self.step_conva, '''size_pooling1''': self.size_poolinga, '''rate_weight''': self.rate_weight, '''rate_thre''': self.rate_thre, '''w_conv1''': self.w_conva, '''wkj''': self.wkj, '''vji''': self.vji, '''thre_conv1''': self.thre_conva, '''thre_bp2''': self.thre_bpa, '''thre_bp3''': self.thre_bpa, } with open(UpperCamelCase , '''wb''' ) as f: pickle.dump(UpperCamelCase , UpperCamelCase ) print(f"Model saved: {save_path}" ) @classmethod def UpperCamelCase__ (cls : Union[str, Any] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' with open(UpperCamelCase , '''rb''' ) as f: lowercase__ = pickle.load(UpperCamelCase ) # noqa: S301 lowercase__ = model_dic.get('''conv1''' ) conv_get.append(model_dic.get('''step_conv1''' ) ) lowercase__ = model_dic.get('''size_pooling1''' ) lowercase__ = model_dic.get('''num_bp1''' ) lowercase__ = model_dic.get('''num_bp2''' ) lowercase__ = model_dic.get('''num_bp3''' ) lowercase__ = model_dic.get('''rate_weight''' ) lowercase__ = model_dic.get('''rate_thre''' ) # create model instance lowercase__ = CNN(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) # modify model parameter lowercase__ = model_dic.get('''w_conv1''' ) lowercase__ = model_dic.get('''wkj''' ) lowercase__ = model_dic.get('''vji''' ) lowercase__ = model_dic.get('''thre_conv1''' ) lowercase__ = model_dic.get('''thre_bp2''' ) lowercase__ = model_dic.get('''thre_bp3''' ) return conv_ins def UpperCamelCase__ (self : Dict , UpperCamelCase : Union[str, Any] ): '''simple docstring''' return 1 / (1 + np.exp(-1 * x )) def UpperCamelCase__ (self : List[str] , UpperCamelCase : str ): '''simple docstring''' return round(UpperCamelCase , 3 ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : Dict , UpperCamelCase : Any , UpperCamelCase : Tuple , UpperCamelCase : Dict , UpperCamelCase : Tuple ): '''simple docstring''' lowercase__ = convs[0] lowercase__ = convs[1] lowercase__ = np.shape(UpperCamelCase )[0] # get the data slice of original image data, data_focus lowercase__ = [] for i_focus in range(0 , size_data - size_conv + 1 , UpperCamelCase ): for j_focus in range(0 , size_data - size_conv + 1 , UpperCamelCase ): lowercase__ = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(UpperCamelCase ) # calculate the feature map of every single kernel, and saved as list of matrix lowercase__ = [] lowercase__ = int((size_data - size_conv) / conv_step + 1 ) for i_map in range(UpperCamelCase ): lowercase__ = [] for i_focus in range(len(UpperCamelCase ) ): lowercase__ = ( np.sum(np.multiply(data_focus[i_focus] , w_convs[i_map] ) ) - thre_convs[i_map] ) featuremap.append(self.sig(UpperCamelCase ) ) lowercase__ = np.asmatrix(UpperCamelCase ).reshape( UpperCamelCase , UpperCamelCase ) data_featuremap.append(UpperCamelCase ) # expanding the data slice to One dimenssion lowercase__ = [] for each_focus in data_focus: focusa_list.extend(self.Expand_Mat(UpperCamelCase ) ) lowercase__ = np.asarray(UpperCamelCase ) return focus_list, data_featuremap def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[int] , UpperCamelCase : List[Any]="average_pool" ): '''simple docstring''' lowercase__ = len(featuremaps[0] ) lowercase__ = int(size_map / size_pooling ) lowercase__ = [] for i_map in range(len(UpperCamelCase ) ): lowercase__ = featuremaps[i_map] lowercase__ = [] for i_focus in range(0 , UpperCamelCase , UpperCamelCase ): for j_focus in range(0 , UpperCamelCase , UpperCamelCase ): lowercase__ = feature_map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if pooling_type == "average_pool": # average pooling map_pooled.append(np.average(UpperCamelCase ) ) elif pooling_type == "max_pooling": # max pooling map_pooled.append(np.max(UpperCamelCase ) ) lowercase__ = np.asmatrix(UpperCamelCase ).reshape(UpperCamelCase , UpperCamelCase ) featuremap_pooled.append(UpperCamelCase ) return featuremap_pooled def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = [] for i in range(len(UpperCamelCase ) ): lowercase__ = np.shape(data[i] ) lowercase__ = data[i].reshape(1 , shapes[0] * shapes[1] ) lowercase__ = data_listed.getA().tolist()[0] data_expanded.extend(UpperCamelCase ) lowercase__ = np.asarray(UpperCamelCase ) return data_expanded def UpperCamelCase__ (self : int , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = np.asarray(UpperCamelCase ) lowercase__ = np.shape(UpperCamelCase ) lowercase__ = data_mat.reshape(1 , shapes[0] * shapes[1] ) return data_expanded def UpperCamelCase__ (self : Any , UpperCamelCase : int , UpperCamelCase : List[Any] , UpperCamelCase : int , UpperCamelCase : Any , UpperCamelCase : str ): '''simple docstring''' lowercase__ = [] lowercase__ = 0 for i_map in range(UpperCamelCase ): lowercase__ = np.ones((size_map, size_map) ) for i in range(0 , UpperCamelCase , UpperCamelCase ): for j in range(0 , UpperCamelCase , UpperCamelCase ): lowercase__ = pd_pool[ i_pool ] lowercase__ = i_pool + 1 lowercase__ = np.multiply( UpperCamelCase , np.multiply(out_map[i_map] , (1 - out_map[i_map]) ) ) pd_all.append(UpperCamelCase ) return pd_all def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : str , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : str=bool ): '''simple docstring''' print('''----------------------Start Training-------------------------''' ) print((''' - - Shape: Train_Data ''', np.shape(UpperCamelCase )) ) print((''' - - Shape: Teach_Data ''', np.shape(UpperCamelCase )) ) lowercase__ = 0 lowercase__ = [] lowercase__ = 10000 while rp < n_repeat and mse >= error_accuracy: lowercase__ = 0 print(f"-------------Learning Time {rp}--------------" ) for p in range(len(UpperCamelCase ) ): # print('------------Learning Image: %d--------------'%p) lowercase__ = np.asmatrix(datas_train[p] ) lowercase__ = np.asarray(datas_teach[p] ) lowercase__ ,lowercase__ = self.convolute( UpperCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase__ = self.pooling(UpperCamelCase , self.size_poolinga ) lowercase__ = np.shape(UpperCamelCase ) lowercase__ = self._expand(UpperCamelCase ) lowercase__ = data_bp_input lowercase__ = np.dot(UpperCamelCase , self.vji.T ) - self.thre_bpa lowercase__ = self.sig(UpperCamelCase ) lowercase__ = np.dot(UpperCamelCase , self.wkj.T ) - self.thre_bpa lowercase__ = self.sig(UpperCamelCase ) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- lowercase__ = np.multiply( (data_teach - bp_outa) , np.multiply(UpperCamelCase , (1 - bp_outa) ) ) lowercase__ = np.multiply( np.dot(UpperCamelCase , self.wkj ) , np.multiply(UpperCamelCase , (1 - bp_outa) ) ) lowercase__ = np.dot(UpperCamelCase , self.vji ) lowercase__ = pd_i_all / (self.size_poolinga * self.size_poolinga) lowercase__ = pd_conva_pooled.T.getA().tolist() lowercase__ = self._calculate_gradient_from_pool( UpperCamelCase , UpperCamelCase , shape_featuremapa[0] , shape_featuremapa[1] , self.size_poolinga , ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conva[1] ): lowercase__ = self._expand_mat(pd_conva_all[k_conv] ) lowercase__ = self.rate_weight * np.dot(UpperCamelCase , UpperCamelCase ) lowercase__ = self.w_conva[k_conv] + delta_w.reshape( (self.conva[0], self.conva[0]) ) lowercase__ = ( self.thre_conva[k_conv] - np.sum(pd_conva_all[k_conv] ) * self.rate_thre ) # all connected layer lowercase__ = self.wkj + pd_k_all.T * bp_outa * self.rate_weight lowercase__ = self.vji + pd_j_all.T * bp_outa * self.rate_weight lowercase__ = self.thre_bpa - pd_k_all * self.rate_thre lowercase__ = self.thre_bpa - pd_j_all * self.rate_thre # calculate the sum error of all single image lowercase__ = np.sum(abs(data_teach - bp_outa ) ) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) lowercase__ = rp + 1 lowercase__ = error_count / patterns all_mse.append(UpperCamelCase ) def draw_error(): lowercase__ = [error_accuracy for i in range(int(n_repeat * 1.2 ) )] plt.plot(UpperCamelCase , '''+-''' ) plt.plot(UpperCamelCase , '''r--''' ) plt.xlabel('''Learning Times''' ) plt.ylabel('''All_mse''' ) plt.grid(UpperCamelCase , alpha=0.5 ) plt.show() print('''------------------Training Complished---------------------''' ) print((''' - - Training epoch: ''', rp, f" - - Mse: {mse:.6f}") ) if draw_e: draw_error() return mse def UpperCamelCase__ (self : List[str] , UpperCamelCase : Optional[Any] ): '''simple docstring''' lowercase__ = [] print('''-------------------Start Testing-------------------------''' ) print((''' - - Shape: Test_Data ''', np.shape(UpperCamelCase )) ) for p in range(len(UpperCamelCase ) ): lowercase__ = np.asmatrix(datas_test[p] ) lowercase__ ,lowercase__ = self.convolute( UpperCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase__ = self.pooling(UpperCamelCase , self.size_poolinga ) lowercase__ = self._expand(UpperCamelCase ) lowercase__ = data_bp_input lowercase__ = bp_outa * self.vji.T - self.thre_bpa lowercase__ = self.sig(UpperCamelCase ) lowercase__ = bp_outa * self.wkj.T - self.thre_bpa lowercase__ = self.sig(UpperCamelCase ) produce_out.extend(bp_outa.getA().tolist() ) lowercase__ = [list(map(self.do_round , UpperCamelCase ) ) for each in produce_out] return np.asarray(UpperCamelCase ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = np.asmatrix(UpperCamelCase ) lowercase__ ,lowercase__ = self.convolute( UpperCamelCase , self.conva , self.w_conva , self.thre_conva , conv_step=self.step_conva , ) lowercase__ = self.pooling(UpperCamelCase , self.size_poolinga ) return data_conveda, data_pooleda if __name__ == "__main__": pass
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> None: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(A , total_number - level + 2 ): current_list.append(A ) create_all_state(i + 1 , A , level - 1 , A , A ) current_list.pop() def _SCREAMING_SNAKE_CASE (A ) -> None: """simple docstring""" for i in total_list: print(*A ) if __name__ == "__main__": lowerCamelCase : Tuple = 4 lowerCamelCase : Union[str, Any] = 2 lowerCamelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
2
1
'''simple docstring''' import math from datetime import datetime, timedelta def _SCREAMING_SNAKE_CASE (A ) -> datetime: """simple docstring""" lowercase__ = year % 19 lowercase__ = year % 4 lowercase__ = year % 7 lowercase__ = math.floor(year / 100 ) lowercase__ = math.floor((13 + 8 * leap_day_inhibits) / 25 ) lowercase__ = leap_day_inhibits / 4 lowercase__ = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 lowercase__ = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 lowercase__ = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon lowercase__ = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(A , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(A , 4 , 18 ) else: return datetime(A , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_994, 2_000, 2_010, 2_021, 2_023): lowerCamelCase : str = 'will be' if year > datetime.now().year else 'was' print(f"""Easter in {year} {tense} {gauss_easter(year)}""")
2
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCamelCase : Optional[Any] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) lowerCamelCase : Tuple = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) lowerCamelCase : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) lowerCamelCase : Any = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) lowerCamelCase : Tuple = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) lowerCamelCase : Optional[int] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) lowerCamelCase : Dict = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ = randrange(len(A ) ), randrange(len(A ) ) lowercase__ = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] lowercase__ ,lowercase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE (A = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(A )) @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" assert PokerHand(A )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = PokerHand(A ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" assert PokerHand(A )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = [PokerHand(A ) for hand in SORTED_HANDS] lowercase__ = poker_hands.copy() shuffle(A ) lowercase__ = chain(sorted(A ) ) for index, hand in enumerate(A ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=A ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE () -> int: """simple docstring""" lowercase__ = PokerHand('''2C 4S AS 3D 5C''' ) lowercase__ = True lowercase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = 0 lowercase__ = os.path.abspath(os.path.dirname(A ) ) lowercase__ = os.path.join(A , '''poker_hands.txt''' ) with open(A ) as file_hand: for line in file_hand: lowercase__ = line[:14].strip() lowercase__ = line[15:].strip() lowercase__ ,lowercase__ = PokerHand(A ), PokerHand(A ) lowercase__ = player.compare_with(A ) if output == "Win": answer += 1 assert answer == 376
2
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule lowerCamelCase : Tuple = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys lowerCamelCase : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase : str = parser.parse_args() if args.model_type == "bert": lowerCamelCase : List[Any] = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase : Any = 'bert' else: raise ValueError('args.model_type should be "bert".') lowerCamelCase : int = model.state_dict() lowerCamelCase : int = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] lowerCamelCase : Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] lowerCamelCase : List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] lowerCamelCase : Tuple = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] lowerCamelCase : Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] lowerCamelCase : Optional[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] lowerCamelCase : Any = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 lowerCamelCase : Optional[int] = state_dict['cls.predictions.decoder.weight'] lowerCamelCase : str = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase : str = state_dict[f"""cls.predictions.transform.dense.{w}"""] lowerCamelCase : Any = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
2
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 lowerCamelCase : Dict = 'true' def _SCREAMING_SNAKE_CASE (A , A=82 , A=16 ) -> List[Any]: """simple docstring""" set_seed(42 ) lowercase__ = RegressionModel() lowercase__ = deepcopy(A ) lowercase__ = RegressionDataset(length=A ) lowercase__ = DataLoader(A , batch_size=A ) model.to(accelerator.device ) lowercase__ ,lowercase__ = accelerator.prepare(A , A ) return model, ddp_model, dataloader def _SCREAMING_SNAKE_CASE (A , A=False ) -> Dict: """simple docstring""" lowercase__ = AutoTokenizer.from_pretrained('''hf-internal-testing/mrpc-bert-base-cased''' ) lowercase__ = load_dataset('''glue''' , '''mrpc''' , split='''validation''' ) def tokenize_function(A ): lowercase__ = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=A , max_length=A ) return outputs with accelerator.main_process_first(): lowercase__ = dataset.map( A , batched=A , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) lowercase__ = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(A ): if use_longest: return tokenizer.pad(A , padding='''longest''' , return_tensors='''pt''' ) return tokenizer.pad(A , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return DataLoader(A , shuffle=A , collate_fn=A , batch_size=16 ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[Any]: """simple docstring""" lowercase__ = Accelerator(dispatch_batches=A , split_batches=A ) lowercase__ = get_dataloader(A , not dispatch_batches ) lowercase__ = AutoModelForSequenceClassification.from_pretrained( '''hf-internal-testing/mrpc-bert-base-cased''' , return_dict=A ) lowercase__ ,lowercase__ = accelerator.prepare(A , A ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def _SCREAMING_SNAKE_CASE (A , A , A ) -> str: """simple docstring""" lowercase__ = [] for batch in dataloader: lowercase__ ,lowercase__ = batch.values() with torch.no_grad(): lowercase__ = model(A ) lowercase__ ,lowercase__ = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) lowercase__ ,lowercase__ = [], [] for logit, targ in logits_and_targets: logits.append(A ) targs.append(A ) lowercase__ ,lowercase__ = torch.cat(A ), torch.cat(A ) return logits, targs def _SCREAMING_SNAKE_CASE (A , A=82 , A=False , A=False , A=16 ) -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ ,lowercase__ = get_basic_setup(A , A , A ) lowercase__ ,lowercase__ = generate_predictions(A , A , A ) assert ( len(A ) == num_samples ), f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(A )}" def _SCREAMING_SNAKE_CASE (A = False , A = False ) -> List[str]: """simple docstring""" lowercase__ = evaluate.load('''glue''' , '''mrpc''' ) lowercase__ ,lowercase__ = get_mrpc_setup(A , A ) # First do baseline lowercase__ ,lowercase__ ,lowercase__ = setup['''no'''] model.to(A ) model.eval() for batch in dataloader: batch.to(A ) with torch.inference_mode(): lowercase__ = model(**A ) lowercase__ = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=A , references=batch['''labels'''] ) lowercase__ = metric.compute() # Then do distributed lowercase__ ,lowercase__ ,lowercase__ = setup['''ddp'''] model.eval() for batch in dataloader: with torch.inference_mode(): lowercase__ = model(**A ) lowercase__ = outputs.logits.argmax(dim=-1 ) lowercase__ = batch['''labels'''] lowercase__ ,lowercase__ = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=A , references=A ) lowercase__ = 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 _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = Accelerator(split_batches=A , dispatch_batches=A ) 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(A , A ) 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]: lowercase__ = Accelerator(split_batches=A , dispatch_batches=A ) if accelerator.is_local_main_process: print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99" ) test_torch_metrics(A , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('''**Test last batch is not dropped when perfectly divisible**''' ) lowercase__ = Accelerator() test_torch_metrics(A , 512 ) accelerator.state._reset_state() def _SCREAMING_SNAKE_CASE (A ) -> Any: """simple docstring""" main() if __name__ == "__main__": main()
2
'''simple docstring''' from ....utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : int=2048 ): '''simple docstring''' lowercase__ = config.__dict__ lowercase__ = modal_hidden_size if num_labels: lowercase__ = num_labels
2
1
'''simple docstring''' from ...processing_utils import ProcessorMixin class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """SpeechT5FeatureExtractor""" lowerCAmelCase__ : Union[str, Any] = """SpeechT5Tokenizer""" def __init__(self : Any , UpperCamelCase : List[str] , UpperCamelCase : List[Any] ): '''simple docstring''' super().__init__(UpperCamelCase , UpperCamelCase ) def __call__(self : Optional[int] , *UpperCamelCase : int , **UpperCamelCase : Tuple ): '''simple docstring''' lowercase__ = kwargs.pop('''audio''' , UpperCamelCase ) lowercase__ = kwargs.pop('''text''' , UpperCamelCase ) lowercase__ = kwargs.pop('''text_target''' , UpperCamelCase ) lowercase__ = kwargs.pop('''audio_target''' , UpperCamelCase ) lowercase__ = kwargs.pop('''sampling_rate''' , UpperCamelCase ) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''' ) if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''' ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''' ) if audio is not None: lowercase__ = self.feature_extractor(UpperCamelCase , *UpperCamelCase , sampling_rate=UpperCamelCase , **UpperCamelCase ) elif text is not None: lowercase__ = self.tokenizer(UpperCamelCase , **UpperCamelCase ) else: lowercase__ = None if audio_target is not None: lowercase__ = self.feature_extractor(audio_target=UpperCamelCase , *UpperCamelCase , sampling_rate=UpperCamelCase , **UpperCamelCase ) lowercase__ = targets['''input_values'''] elif text_target is not None: lowercase__ = self.tokenizer(UpperCamelCase , **UpperCamelCase ) lowercase__ = targets['''input_ids'''] else: lowercase__ = None if inputs is None: return targets if targets is not None: lowercase__ = labels lowercase__ = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: lowercase__ = decoder_attention_mask return inputs def UpperCamelCase__ (self : Tuple , *UpperCamelCase : Optional[Any] , **UpperCamelCase : str ): '''simple docstring''' lowercase__ = kwargs.pop('''input_values''' , UpperCamelCase ) lowercase__ = kwargs.pop('''input_ids''' , UpperCamelCase ) lowercase__ = kwargs.pop('''labels''' , UpperCamelCase ) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''' ) if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''' ) if input_values is not None: lowercase__ = self.feature_extractor.pad(UpperCamelCase , *UpperCamelCase , **UpperCamelCase ) elif input_ids is not None: lowercase__ = self.tokenizer.pad(UpperCamelCase , **UpperCamelCase ) else: lowercase__ = None if labels is not None: if "input_ids" in labels or (isinstance(UpperCamelCase , UpperCamelCase ) and "input_ids" in labels[0]): lowercase__ = self.tokenizer.pad(UpperCamelCase , **UpperCamelCase ) lowercase__ = targets['''input_ids'''] else: lowercase__ = self.feature_extractor.feature_size lowercase__ = self.feature_extractor.num_mel_bins lowercase__ = self.feature_extractor.pad(UpperCamelCase , *UpperCamelCase , **UpperCamelCase ) lowercase__ = feature_size_hack lowercase__ = targets['''input_values'''] else: lowercase__ = None if inputs is None: return targets if targets is not None: lowercase__ = labels lowercase__ = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: lowercase__ = decoder_attention_mask return inputs def UpperCamelCase__ (self : str , *UpperCamelCase : int , **UpperCamelCase : Any ): '''simple docstring''' return self.tokenizer.batch_decode(*UpperCamelCase , **UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] , *UpperCamelCase : Optional[Any] , **UpperCamelCase : Optional[int] ): '''simple docstring''' return self.tokenizer.decode(*UpperCamelCase , **UpperCamelCase )
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """cvt""" def __init__(self : int , UpperCamelCase : List[Any]=3 , UpperCamelCase : int=[7, 3, 3] , UpperCamelCase : str=[4, 2, 2] , UpperCamelCase : Dict=[2, 1, 1] , UpperCamelCase : Dict=[64, 192, 384] , UpperCamelCase : Dict=[1, 3, 6] , UpperCamelCase : Dict=[1, 2, 10] , UpperCamelCase : Any=[4.0, 4.0, 4.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : int=[0.0, 0.0, 0.1] , UpperCamelCase : Any=[True, True, True] , UpperCamelCase : int=[False, False, True] , UpperCamelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase : Optional[int]=[3, 3, 3] , UpperCamelCase : Tuple=[1, 1, 1] , UpperCamelCase : Any=[2, 2, 2] , UpperCamelCase : Dict=[1, 1, 1] , UpperCamelCase : List[str]=[1, 1, 1] , UpperCamelCase : str=0.02 , UpperCamelCase : int=1E-12 , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" return number | (1 << position) def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" return number & ~(1 << position) def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" return number ^ (1 << position) def _SCREAMING_SNAKE_CASE (A , A ) -> bool: """simple docstring""" return ((number >> position) & 1) == 1 def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
2
'''simple docstring''' import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCamelCase : Any = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCamelCase : Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCamelCase : Any = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) lowerCamelCase : List[Any] = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) lowerCamelCase : List[str] = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions lowerCamelCase : List[str] = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(64, 64) ) lowerCamelCase : Optional[int] = tf.keras.preprocessing.image.img_to_array(test_image) lowerCamelCase : str = np.expand_dims(test_image, axis=0) lowerCamelCase : List[str] = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCamelCase : Any = 'Normal' if result[0][0] == 1: lowerCamelCase : Any = 'Abnormality detected'
2
1
'''simple docstring''' import warnings from diffusers import StableDiffusionImgaImgPipeline # noqa F401 warnings.warn( 'The `image_to_image.py` script is outdated. Please use directly `from diffusers import' ' StableDiffusionImg2ImgPipeline` instead.' )
2
'''simple docstring''' class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__(self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = row lowercase__ = col lowercase__ = graph def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowercase__ = [-1, 0, 1, -1, 1, -1, 0, 1] lowercase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): # And finally, count all islands. '''simple docstring''' lowercase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] lowercase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += 1 return count
2
1
'''simple docstring''' import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters lowerCamelCase : int = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (A , A , A , A=None , A=None ) -> int: """simple docstring""" if "." in tensor_name: lowercase__ = tensor_name.split('''.''' ) for split in splits[:-1]: lowercase__ = getattr(A , A ) if new_module is None: raise ValueError(f"{module} has no attribute {split}." ) lowercase__ = new_module lowercase__ = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}." ) lowercase__ = tensor_name in module._buffers lowercase__ = getattr(A , A ) if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None: raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}." ) lowercase__ = False lowercase__ = False if is_buffer or not is_bitsandbytes_available(): lowercase__ = False lowercase__ = False else: lowercase__ = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) lowercase__ = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: lowercase__ = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: lowercase__ = old_value.to(A ) elif isinstance(A , torch.Tensor ): lowercase__ = value.to('''cpu''' ) if value.dtype == torch.inta: lowercase__ = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse( '''0.37.2''' ) if not is_abit_serializable: raise ValueError( '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ''' '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' ) else: lowercase__ = torch.tensor(A , device='''cpu''' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , A ) and fpaa_statistics is None: lowercase__ = new_value.T lowercase__ = old_value.__dict__ if is_abit: lowercase__ = bnb.nn.IntaParams(A , requires_grad=A , **A ).to(A ) elif is_abit: lowercase__ = bnb.nn.Paramsabit(A , requires_grad=A , **A ).to(A ) lowercase__ = new_value if fpaa_statistics is not None: setattr(module.weight , '''SCB''' , fpaa_statistics.to(A ) ) else: if value is None: lowercase__ = old_value.to(A ) elif isinstance(A , torch.Tensor ): lowercase__ = value.to(A ) else: lowercase__ = torch.tensor(A , device=A ) if is_buffer: lowercase__ = new_value else: lowercase__ = nn.Parameter(A , requires_grad=old_value.requires_grad ) lowercase__ = new_value def _SCREAMING_SNAKE_CASE (A , A=None , A=None , A=None , A=False ) -> Union[str, Any]: """simple docstring""" for name, module in model.named_children(): if current_key_name is None: lowercase__ = [] current_key_name.append(A ) if (isinstance(A , nn.Linear ) or isinstance(A , A )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '''.'''.join(A ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(A , A ): lowercase__ ,lowercase__ = module.weight.shape else: lowercase__ = module.in_features lowercase__ = module.out_features if quantization_config.quantization_method() == "llm_int8": lowercase__ = bnb.nn.LinearabitLt( A , A , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) lowercase__ = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: lowercase__ = bnb.nn.Linearabit( A , A , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) lowercase__ = True # Store the module class in case we need to transpose the weight later lowercase__ = type(A ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(A ) if len(list(module.children() ) ) > 0: lowercase__ ,lowercase__ = _replace_with_bnb_linear( A , A , A , A , has_been_replaced=A , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def _SCREAMING_SNAKE_CASE (A , A=None , A=None , A=None ) -> Optional[int]: """simple docstring""" lowercase__ = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert lowercase__ ,lowercase__ = _replace_with_bnb_linear( A , A , A , A ) if not has_been_replaced: logger.warning( '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.''' ''' Please double check your model architecture, or submit an issue on github if you think this is''' ''' a bug.''' ) return model def _SCREAMING_SNAKE_CASE (*A , **A ) -> List[str]: """simple docstring""" warnings.warn( '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , A , ) return replace_with_bnb_linear(*A , **A ) def _SCREAMING_SNAKE_CASE (*A , **A ) -> Tuple: """simple docstring""" warnings.warn( '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , A , ) return set_module_quantized_tensor_to_device(*A , **A ) def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" lowercase__ = deepcopy(A ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() lowercase__ = find_tied_parameters(A ) # For compatibility with Accelerate < 0.18 if isinstance(A , A ): lowercase__ = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: lowercase__ = sum(A , [] ) lowercase__ = len(A ) > 0 # Check if it is a base model lowercase__ = not hasattr(A , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head lowercase__ = list(model.named_children() ) lowercase__ = [list_modules[-1][0]] # add last module together with tied weights lowercase__ = set(A ) - set(A ) lowercase__ = list(set(A ) ) + list(A ) # remove ".weight" from the keys lowercase__ = ['''.weight''', '''.bias'''] lowercase__ = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: lowercase__ = name.replace(A , '''''' ) filtered_module_names.append(A ) return filtered_module_names
2
'''simple docstring''' import unittest from transformers import DonutProcessor lowerCamelCase : Tuple = 'naver-clova-ix/donut-base' class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = DonutProcessor.from_pretrained(UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowercase__ = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowercase__ = self.processor.tokenajson(UpperCamelCase ) self.assertDictEqual(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A = 50 ) -> int: """simple docstring""" lowercase__ = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(f"""{solution() = }""")
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return len(set(A ) ) == len(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" lowercase__ = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue lowercase__ = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) lowercase__ = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) lowercase__ = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) lowercase__ = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) lowercase__ = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) lowercase__ = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) lowercase__ = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) lowercase__ = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) lowercase__ = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) lowercase__ = key.replace('''image_encoder.module''' , '''flava.image_model''' ) lowercase__ = key.replace('''text_encoder.module''' , '''flava.text_model''' ) lowercase__ = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) lowercase__ = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) lowercase__ = key.replace('''text_projection''' , '''flava.text_projection''' ) lowercase__ = key.replace('''image_projection''' , '''flava.image_projection''' ) lowercase__ = value.float() for key, value in codebook_state_dict.items(): lowercase__ = value return upgrade @torch.no_grad() def _SCREAMING_SNAKE_CASE (A , A , A , A=None ) -> Any: """simple docstring""" if config_path is not None: lowercase__ = FlavaConfig.from_pretrained(A ) else: lowercase__ = FlavaConfig() lowercase__ = FlavaForPreTraining(A ).eval() lowercase__ = convert_dalle_checkpoint(A , A , save_checkpoint=A ) if os.path.exists(A ): lowercase__ = torch.load(A , map_location='''cpu''' ) else: lowercase__ = torch.hub.load_state_dict_from_url(A , map_location='''cpu''' ) lowercase__ = upgrade_state_dict(A , A ) hf_model.load_state_dict(A ) lowercase__ = hf_model.state_dict() lowercase__ = count_parameters(A ) lowercase__ = count_parameters(A ) + count_parameters(A ) assert torch.allclose(A , A , atol=1E-3 ) hf_model.save_pretrained(A ) if __name__ == "__main__": lowerCamelCase : str = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') lowerCamelCase : Tuple = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
2
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: lowerCamelCase : Any = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : List[str] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 lowerCamelCase : Any = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : str = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = TaTokenizer lowerCAmelCase__ : List[int] = [] def __init__(self : Dict , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any="</s>" , UpperCamelCase : str="<unk>" , UpperCamelCase : List[str]="<pad>" , UpperCamelCase : List[str]=100 , UpperCamelCase : Tuple=None , **UpperCamelCase : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase__ = [f"<extra_id_{i}>" for i in range(UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase__ = len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) ) , UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , extra_ids=UpperCamelCase , additional_special_tokens=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True lowercase__ = extra_ids @staticmethod def UpperCamelCase__ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f" {pretrained_model_name_or_path} automatically truncating your input to" f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase , ) return max_model_length def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) logger.info(f"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>''' , UpperCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]
2
1
'''simple docstring''' lowerCamelCase : int = [ (1_000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" lowercase__ = {'''I''': 1, '''V''': 5, '''X''': 10, '''L''': 50, '''C''': 100, '''D''': 500, '''M''': 1_000} lowercase__ = 0 lowercase__ = 0 while place < len(A ): if (place + 1 < len(A )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = [] for arabic, roman in ROMAN: ((lowercase__) ,(lowercase__)) = divmod(A , A ) result.append(roman * factor ) if number == 0: break return "".join(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = ShapEImgaImgPipeline lowerCAmelCase__ : List[str] = ["""image"""] lowerCAmelCase__ : Any = ["""image"""] lowerCAmelCase__ : Any = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] lowerCAmelCase__ : Tuple = False @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : str ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase__ (self : int ): '''simple docstring''' return 8 @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(UpperCamelCase ) return model @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase , do_normalize=UpperCamelCase , do_resize=UpperCamelCase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def UpperCamelCase__ (self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase__ = PriorTransformer(**UpperCamelCase ) return model @property def UpperCamelCase__ (self : int ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**UpperCamelCase ) return model def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase , clip_sample=UpperCamelCase , clip_sample_range=1.0 , ) lowercase__ = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : str=0 ): '''simple docstring''' lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) if str(UpperCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(UpperCamelCase ) else: lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowercase__ = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = '''cpu''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = pipe(**self.get_dummy_inputs(UpperCamelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = torch_device == '''cpu''' lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase , relax_max_difference=UpperCamelCase , ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(UpperCamelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**UpperCamelCase , num_images_per_prompt=UpperCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase__ = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(0 ) lowercase__ = pipe( UpperCamelCase , generator=UpperCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = {'vocab_file': 'spiece.model'} lowerCamelCase : int = { 'vocab_file': { 'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model', } } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : List[str]=False , UpperCamelCase : Tuple=True , UpperCamelCase : Optional[int]=False , UpperCamelCase : str="<s>" , UpperCamelCase : Optional[Any]="</s>" , UpperCamelCase : Any="<unk>" , UpperCamelCase : Tuple="<sep>" , UpperCamelCase : Union[str, Any]="<pad>" , UpperCamelCase : Any="<cls>" , UpperCamelCase : Tuple="<mask>" , UpperCamelCase : Any=["<eop>", "<eod>"] , UpperCamelCase : Optional[Dict[str, Any]] = None , **UpperCamelCase : Optional[int] , ): '''simple docstring''' lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else mask_token lowercase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase , remove_space=UpperCamelCase , keep_accents=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , sep_token=UpperCamelCase , pad_token=UpperCamelCase , cls_token=UpperCamelCase , mask_token=UpperCamelCase , additional_special_tokens=UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase , ) lowercase__ = 3 lowercase__ = do_lower_case lowercase__ = remove_space lowercase__ = keep_accents lowercase__ = vocab_file lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) lowercase__ = jieba lowercase__ = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def UpperCamelCase__ (self : Dict ): '''simple docstring''' return len(self.sp_model ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = {self.convert_ids_to_tokens(UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self : str ): '''simple docstring''' lowercase__ = self.__dict__.copy() lowercase__ = None return state def __setstate__(self : Dict , UpperCamelCase : int ): '''simple docstring''' lowercase__ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase__ = {} lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if self.remove_space: lowercase__ = ''' '''.join(inputs.strip().split() ) else: lowercase__ = inputs lowercase__ = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: lowercase__ = unicodedata.normalize('''NFKD''' , UpperCamelCase ) lowercase__ = ''''''.join([c for c in outputs if not unicodedata.combining(UpperCamelCase )] ) if self.do_lower_case: lowercase__ = outputs.lower() return outputs def UpperCamelCase__ (self : List[str] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = self.preprocess_text(UpperCamelCase ) lowercase__ = self.sp_model.encode(UpperCamelCase , out_type=UpperCamelCase ) lowercase__ = [] for piece in pieces: if len(UpperCamelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): lowercase__ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase__ = cur_pieces[1:] else: lowercase__ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase ) else: new_pieces.append(UpperCamelCase ) return new_pieces def UpperCamelCase__ (self : Dict , UpperCamelCase : Optional[int] ): '''simple docstring''' return self.sp_model.PieceToId(UpperCamelCase ) def UpperCamelCase__ (self : int , UpperCamelCase : Any ): '''simple docstring''' return self.sp_model.IdToPiece(UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Optional[int] ): '''simple docstring''' lowercase__ = ''''''.join(UpperCamelCase ).replace(UpperCamelCase , ''' ''' ).strip() return out_string def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def UpperCamelCase__ (self : int , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None , UpperCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase , token_ids_a=UpperCamelCase , already_has_special_tokens=UpperCamelCase ) if token_ids_a is not None: return ([0] * len(UpperCamelCase )) + [1] + ([0] * len(UpperCamelCase )) + [1, 1] return ([0] * len(UpperCamelCase )) + [1, 1] def UpperCamelCase__ (self : str , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def UpperCamelCase__ (self : Dict , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase , '''wb''' ) as fi: lowercase__ = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase ) return (out_vocab_file,) def UpperCamelCase__ (self : Optional[Any] , *UpperCamelCase : int , **UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = super()._decode(*UpperCamelCase , **UpperCamelCase ) lowercase__ = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
2
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = BlenderbotConfig lowerCAmelCase__ : Dict = {} lowerCAmelCase__ : List[Any] = """gelu""" def __init__(self : str , UpperCamelCase : Dict , UpperCamelCase : Any=13 , UpperCamelCase : List[Any]=7 , UpperCamelCase : str=True , UpperCamelCase : Dict=False , UpperCamelCase : Optional[Any]=99 , UpperCamelCase : Dict=32 , UpperCamelCase : int=2 , UpperCamelCase : str=4 , UpperCamelCase : Any=37 , UpperCamelCase : str=0.1 , UpperCamelCase : int=0.1 , UpperCamelCase : Dict=20 , UpperCamelCase : Union[str, Any]=2 , UpperCamelCase : Optional[int]=1 , UpperCamelCase : Optional[int]=0 , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = eos_token_id lowercase__ = pad_token_id lowercase__ = bos_token_id def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) lowercase__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) lowercase__ = tf.concat([input_ids, eos_tensor] , axis=1 ) lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) lowercase__ = prepare_blenderbot_inputs_dict(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return config, inputs_dict def UpperCamelCase__ (self : List[Any] , UpperCamelCase : List[str] , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = TFBlenderbotModel(config=UpperCamelCase ).get_decoder() lowercase__ = inputs_dict['''input_ids'''] lowercase__ = input_ids[:1, :] lowercase__ = inputs_dict['''attention_mask'''][:1, :] lowercase__ = inputs_dict['''head_mask'''] lowercase__ = 1 # first forward pass lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , head_mask=UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ ,lowercase__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowercase__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and lowercase__ = tf.concat([input_ids, next_tokens] , axis=-1 ) lowercase__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase )[0] lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , past_key_values=UpperCamelCase )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice lowercase__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) lowercase__ = output_from_no_past[:, -3:, random_slice_idx] lowercase__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(UpperCamelCase , UpperCamelCase , rtol=1E-3 ) def _SCREAMING_SNAKE_CASE (A , A , A , A=None , A=None , A=None , A=None , A=None , ) -> Any: """simple docstring""" if attention_mask is None: lowercase__ = tf.cast(tf.math.not_equal(A , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: lowercase__ = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: lowercase__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __lowerCAmelCase (lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : str = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () lowerCAmelCase__ : Tuple = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () lowerCAmelCase__ : List[Any] = ( { """conversational""": TFBlenderbotForConditionalGeneration, """feature-extraction""": TFBlenderbotModel, """summarization""": TFBlenderbotForConditionalGeneration, """text2text-generation""": TFBlenderbotForConditionalGeneration, """translation""": TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : str = False def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = TFBlenderbotModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*UpperCamelCase ) @require_tokenizers @require_tf class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : int = ["""My friends are cool but they eat too many carbs."""] lowerCAmelCase__ : Any = """facebook/blenderbot-400M-distill""" @cached_property def UpperCamelCase__ (self : List[str] ): '''simple docstring''' return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.tokenizer(self.src_text , return_tensors='''tf''' ) lowercase__ = self.model.generate( model_inputs.input_ids , ) lowercase__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=UpperCamelCase )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) lowerCamelCase : Dict = { 'xlm-mlm-en-2048': 'https://huggingface.co/xlm-mlm-en-2048/resolve/main/config.json', 'xlm-mlm-ende-1024': 'https://huggingface.co/xlm-mlm-ende-1024/resolve/main/config.json', 'xlm-mlm-enfr-1024': 'https://huggingface.co/xlm-mlm-enfr-1024/resolve/main/config.json', 'xlm-mlm-enro-1024': 'https://huggingface.co/xlm-mlm-enro-1024/resolve/main/config.json', 'xlm-mlm-tlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-tlm-xnli15-1024/resolve/main/config.json', 'xlm-mlm-xnli15-1024': 'https://huggingface.co/xlm-mlm-xnli15-1024/resolve/main/config.json', 'xlm-clm-enfr-1024': 'https://huggingface.co/xlm-clm-enfr-1024/resolve/main/config.json', 'xlm-clm-ende-1024': 'https://huggingface.co/xlm-clm-ende-1024/resolve/main/config.json', 'xlm-mlm-17-1280': 'https://huggingface.co/xlm-mlm-17-1280/resolve/main/config.json', 'xlm-mlm-100-1280': 'https://huggingface.co/xlm-mlm-100-1280/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """xlm""" lowerCAmelCase__ : Any = { """hidden_size""": """emb_dim""", """num_attention_heads""": """n_heads""", """num_hidden_layers""": """n_layers""", """n_words""": """vocab_size""", # For backward compatibility } def __init__(self : Union[str, Any] , UpperCamelCase : Union[str, Any]=30145 , UpperCamelCase : Union[str, Any]=2048 , UpperCamelCase : Union[str, Any]=12 , UpperCamelCase : List[str]=16 , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : List[Any]=True , UpperCamelCase : Dict=False , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : Dict=False , UpperCamelCase : List[Any]=1 , UpperCamelCase : Dict=True , UpperCamelCase : int=512 , UpperCamelCase : int=2048**-0.5 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : int=0 , UpperCamelCase : Any=1 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=3 , UpperCamelCase : str=5 , UpperCamelCase : Union[str, Any]=True , UpperCamelCase : Tuple="first" , UpperCamelCase : int=True , UpperCamelCase : int=None , UpperCamelCase : List[str]=True , UpperCamelCase : Optional[int]=0.1 , UpperCamelCase : int=5 , UpperCamelCase : int=5 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Any=0 , UpperCamelCase : str=2 , UpperCamelCase : List[str]=0 , **UpperCamelCase : Optional[Any] , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = emb_dim lowercase__ = n_layers lowercase__ = n_heads lowercase__ = dropout lowercase__ = attention_dropout lowercase__ = gelu_activation lowercase__ = sinusoidal_embeddings lowercase__ = causal lowercase__ = asm lowercase__ = n_langs lowercase__ = use_lang_emb lowercase__ = layer_norm_eps lowercase__ = bos_index lowercase__ = eos_index lowercase__ = pad_index lowercase__ = unk_index lowercase__ = mask_index lowercase__ = is_encoder lowercase__ = max_position_embeddings lowercase__ = embed_init_std lowercase__ = init_std lowercase__ = summary_type lowercase__ = summary_use_proj lowercase__ = summary_activation lowercase__ = summary_proj_to_labels lowercase__ = summary_first_dropout lowercase__ = start_n_top lowercase__ = end_n_top lowercase__ = mask_token_id lowercase__ = lang_id if "n_words" in kwargs: lowercase__ = kwargs['''n_words'''] super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , **UpperCamelCase ) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' @property def UpperCamelCase__ (self : int ): '''simple docstring''' if self.task == "multiple-choice": lowercase__ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase__ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
2
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" while second != 0: lowercase__ = first & second first ^= second lowercase__ = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase : Tuple = int(input('Enter the first number: ').strip()) lowerCamelCase : List[str] = int(input('Enter the second number: ').strip()) print(f"""{add(first, second) = }""")
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 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, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging lowerCamelCase : List[str] = logging.get_logger(__name__) if is_vision_available(): import PIL class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Dict = ["""pixel_values"""] def __init__(self : Any , UpperCamelCase : bool = True , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase : bool = True , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : bool = True , UpperCamelCase : Union[int, float] = 1 / 255 , UpperCamelCase : bool = True , UpperCamelCase : Optional[Union[float, List[float]]] = None , UpperCamelCase : Optional[Union[float, List[float]]] = None , UpperCamelCase : bool = True , **UpperCamelCase : Any , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = size if size is not None else {'''shortest_edge''': 224} lowercase__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase ) lowercase__ = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} lowercase__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase , param_name='''crop_size''' ) lowercase__ = do_resize lowercase__ = size lowercase__ = resample lowercase__ = do_center_crop lowercase__ = crop_size lowercase__ = do_rescale lowercase__ = rescale_factor lowercase__ = do_normalize lowercase__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN lowercase__ = image_std if image_std is not None else OPENAI_CLIP_STD lowercase__ = do_convert_rgb def UpperCamelCase__ (self : int , UpperCamelCase : np.ndarray , UpperCamelCase : Dict[str, int] , UpperCamelCase : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : List[Any] , ): '''simple docstring''' lowercase__ = get_size_dict(UpperCamelCase , default_to_square=UpperCamelCase ) if "shortest_edge" not in size: raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) lowercase__ = get_resize_output_image_size(UpperCamelCase , size=size['''shortest_edge'''] , default_to_square=UpperCamelCase ) return resize(UpperCamelCase , size=UpperCamelCase , resample=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def UpperCamelCase__ (self : int , UpperCamelCase : np.ndarray , UpperCamelCase : Dict[str, int] , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = get_size_dict(UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}" ) return center_crop(UpperCamelCase , size=(size['''height'''], size['''width''']) , data_format=UpperCamelCase , **UpperCamelCase ) def UpperCamelCase__ (self : Dict , UpperCamelCase : np.ndarray , UpperCamelCase : Union[int, float] , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : List[Any] , ): '''simple docstring''' return rescale(UpperCamelCase , scale=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def UpperCamelCase__ (self : Any , UpperCamelCase : np.ndarray , UpperCamelCase : Union[float, List[float]] , UpperCamelCase : Union[float, List[float]] , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : List[str] , ): '''simple docstring''' return normalize(UpperCamelCase , mean=UpperCamelCase , std=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : ImageInput , UpperCamelCase : bool = None , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : PILImageResampling = None , UpperCamelCase : bool = None , UpperCamelCase : int = None , UpperCamelCase : bool = None , UpperCamelCase : float = None , UpperCamelCase : bool = None , UpperCamelCase : Optional[Union[float, List[float]]] = None , UpperCamelCase : Optional[Union[float, List[float]]] = None , UpperCamelCase : bool = None , UpperCamelCase : Optional[Union[str, TensorType]] = None , UpperCamelCase : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase : Optional[int] , ): '''simple docstring''' lowercase__ = do_resize if do_resize is not None else self.do_resize lowercase__ = size if size is not None else self.size lowercase__ = get_size_dict(UpperCamelCase , param_name='''size''' , default_to_square=UpperCamelCase ) lowercase__ = resample if resample is not None else self.resample lowercase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase__ = crop_size if crop_size is not None else self.crop_size lowercase__ = get_size_dict(UpperCamelCase , param_name='''crop_size''' , default_to_square=UpperCamelCase ) lowercase__ = do_rescale if do_rescale is not None else self.do_rescale lowercase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase__ = do_normalize if do_normalize is not None else self.do_normalize lowercase__ = image_mean if image_mean is not None else self.image_mean lowercase__ = image_std if image_std is not None else self.image_std lowercase__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb lowercase__ = make_list_of_images(UpperCamelCase ) if not valid_images(UpperCamelCase ): 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.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: lowercase__ = [convert_to_rgb(UpperCamelCase ) for image in images] # All transformations expect numpy arrays. lowercase__ = [to_numpy_array(UpperCamelCase ) for image in images] if do_resize: lowercase__ = [self.resize(image=UpperCamelCase , size=UpperCamelCase , resample=UpperCamelCase ) for image in images] if do_center_crop: lowercase__ = [self.center_crop(image=UpperCamelCase , size=UpperCamelCase ) for image in images] if do_rescale: lowercase__ = [self.rescale(image=UpperCamelCase , scale=UpperCamelCase ) for image in images] if do_normalize: lowercase__ = [self.normalize(image=UpperCamelCase , mean=UpperCamelCase , std=UpperCamelCase ) for image in images] lowercase__ = [to_channel_dimension_format(UpperCamelCase , UpperCamelCase ) for image in images] lowercase__ = {'''pixel_values''': images} return BatchFeature(data=UpperCamelCase , tensor_type=UpperCamelCase )
2
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
1
'''simple docstring''' import argparse from collections import defaultdict import yaml lowerCamelCase : Optional[Any] = 'docs/source/en/_toctree.yml' def _SCREAMING_SNAKE_CASE (A ) -> List[Any]: """simple docstring""" lowercase__ = defaultdict(A ) for doc in model_doc: counts[doc["local"]] += 1 lowercase__ = [key for key, value in counts.items() if value > 1] lowercase__ = [] for duplicate_key in duplicates: lowercase__ = 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 _SCREAMING_SNAKE_CASE (A=False ) -> Optional[Any]: """simple docstring""" with open(A , encoding='''utf-8''' ) as f: lowercase__ = yaml.safe_load(f.read() ) # Get to the API doc lowercase__ = 0 while content[api_idx]["title"] != "API": api_idx += 1 lowercase__ = content[api_idx]['''sections'''] # Then to the model doc lowercase__ = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 lowercase__ = api_doc[model_idx]['''sections'''] lowercase__ = [(idx, section) for idx, section in enumerate(A ) if '''sections''' in section] lowercase__ = False for idx, modality_doc in modalities_docs: lowercase__ = modality_doc['''sections'''] lowercase__ = clean_model_doc_toc(A ) if old_modality_doc != new_modality_doc: lowercase__ = True if overwrite: lowercase__ = new_modality_doc if diff: if overwrite: lowercase__ = model_doc lowercase__ = 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 : Dict = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') lowerCamelCase : Optional[Any] = parser.parse_args() check_model_doc(args.fix_and_overwrite)
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """megatron-bert""" def __init__(self : Tuple , UpperCamelCase : Optional[int]=29056 , UpperCamelCase : Optional[Any]=1024 , UpperCamelCase : Any=24 , UpperCamelCase : int=16 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : int="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any=512 , UpperCamelCase : int=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Optional[int]="absolute" , UpperCamelCase : List[Any]=True , **UpperCamelCase : str , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache
2
1
'''simple docstring''' import heapq import sys import numpy as np lowerCamelCase : List[Any] = tuple[int, int] class __lowerCAmelCase : '''simple docstring''' def __init__(self : Dict ): '''simple docstring''' lowercase__ = [] lowercase__ = set() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' if not self.empty(): return self.elements[0][0] else: return float('''inf''' ) def UpperCamelCase__ (self : str ): '''simple docstring''' return len(self.elements ) == 0 def UpperCamelCase__ (self : Tuple , UpperCamelCase : Tuple , UpperCamelCase : Optional[int] ): '''simple docstring''' if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(UpperCamelCase ) else: # update # print("update", item) lowercase__ = [] ((lowercase__) ,(lowercase__)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((lowercase__) ,(lowercase__)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : int ): '''simple docstring''' if item in self.set: self.set.remove(UpperCamelCase ) lowercase__ = [] ((lowercase__) ,(lowercase__)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((lowercase__) ,(lowercase__)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' return self.elements[0][1] def UpperCamelCase__ (self : str ): '''simple docstring''' ((lowercase__) ,(lowercase__)) = heapq.heappop(self.elements ) self.set.remove(UpperCamelCase ) return (priority, item) def _SCREAMING_SNAKE_CASE (A , A ) -> List[Any]: """simple docstring""" lowercase__ = np.array(A ) lowercase__ = np.array(A ) return np.linalg.norm(a - b ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[int]: """simple docstring""" return consistent_heuristic(A , A ) // t def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _SCREAMING_SNAKE_CASE (A , A , A , A ) -> Tuple: """simple docstring""" lowercase__ = g_function[start] + Wa * heuristics[i](A , A ) return ans def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" lowercase__ = np.chararray((n, n) ) for i in range(A ): for j in range(A ): lowercase__ = '''*''' for i in range(A ): for j in range(A ): if (j, (n - 1) - i) in blocks: lowercase__ = '''#''' lowercase__ = '''-''' lowercase__ = back_pointer[goal] while x != start: ((lowercase__) ,(lowercase__)) = x # print(x) lowercase__ = '''-''' lowercase__ = back_pointer[x] lowercase__ = '''-''' for i in range(A ): for j in range(A ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) lowercase__ = back_pointer[goal] while x != start: print(A , end=''' ''' ) lowercase__ = back_pointer[x] print(A ) sys.exit() def _SCREAMING_SNAKE_CASE (A ) -> Optional[int]: """simple docstring""" if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _SCREAMING_SNAKE_CASE (A , A , A , A , A , A , A , A , ) -> int: """simple docstring""" for itera in range(A ): open_list[itera].remove_element(A ) # print("s", s) # print("j", j) ((lowercase__) ,(lowercase__)) = s lowercase__ = (x - 1, y) lowercase__ = (x + 1, y) lowercase__ = (x, y + 1) lowercase__ = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(A ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(A ) lowercase__ = -1 lowercase__ = float('''inf''' ) if valid(A ) and g_function[neighbours] > g_function[s] + 1: lowercase__ = g_function[s] + 1 lowercase__ = s if neighbours not in close_list_anchor: open_list[0].put(A , key(A , 0 , A , A ) ) if neighbours not in close_list_inad: for var in range(1 , A ): if key(A , A , A , A ) <= Wa * key( A , 0 , A , A ): open_list[j].put( A , key(A , A , A , A ) ) def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list lowerCamelCase : Dict = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} lowerCamelCase : Union[str, Any] = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] lowerCamelCase : str = make_common_ground() lowerCamelCase : List[Any] = blocks_blk # hyper parameters lowerCamelCase : Tuple = 1 lowerCamelCase : Optional[int] = 1 lowerCamelCase : List[Any] = 20 lowerCamelCase : Optional[int] = 3 # one consistent and two other inconsistent # start and end destination lowerCamelCase : Dict = (0, 0) lowerCamelCase : Optional[Any] = (n - 1, n - 1) lowerCamelCase : Any = 1 def _SCREAMING_SNAKE_CASE (A , A , A ) -> Tuple: """simple docstring""" lowercase__ = {start: 0, goal: float('''inf''' )} lowercase__ = {start: -1, goal: -1} lowercase__ = [] lowercase__ = set() for i in range(A ): open_list.append(PriorityQueue() ) open_list[i].put(A , key(A , A , A , A ) ) lowercase__ = [] lowercase__ = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , A ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(A , A , A ) else: lowercase__ ,lowercase__ = open_list[i].top_show() visited.add(A ) expand_state( A , A , A , A , A , A , A , A , ) close_list_inad.append(A ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(A , A , A ) else: lowercase__ = open_list[0].top_show() visited.add(A ) expand_state( A , 0 , A , A , A , A , A , A , ) close_list_anchor.append(A ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(A ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
2
'''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
1
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" return "".join(sorted(A ) ) def _SCREAMING_SNAKE_CASE (A ) -> list[str]: """simple docstring""" return word_by_signature[signature(A )] lowerCamelCase : str = Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') lowerCamelCase : List[Any] = sorted({word.strip().lower() for word in data.splitlines()}) lowerCamelCase : List[str] = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": lowerCamelCase : Any = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
2
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : List[str] = { 'configuration_nllb_moe': [ 'NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NllbMoeConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[Any] = [ 'NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST', 'NllbMoeForConditionalGeneration', 'NllbMoeModel', 'NllbMoePreTrainedModel', 'NllbMoeTop2Router', 'NllbMoeSparseMLP', ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys lowerCamelCase : str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
1
'''simple docstring''' from sklearn.metrics import mean_squared_error import datasets lowerCamelCase : Dict = '\\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n' lowerCamelCase : Tuple = '\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n' lowerCamelCase : List[str] = '\nArgs:\n predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Estimated target values.\n references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n Ground truth (correct) target values.\n sample_weight: array-like of shape (n_samples,), default=None\n Sample weights.\n multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"\n Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n "raw_values" : Returns a full set of errors in case of multioutput input.\n\n "uniform_average" : Errors of all outputs are averaged with uniform weight.\n\n squared : bool, default=True\n If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n mse : mean squared error.\nExamples:\n\n >>> mse_metric = datasets.load_metric("mse")\n >>> predictions = [2.5, 0.0, 2, 8]\n >>> references = [3, -0.5, 2, 7]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.375}\n >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n >>> print(rmse_result)\n {\'mse\': 0.6123724356957945}\n\n If you\'re using multi-dimensional lists, then set the config as follows :\n\n >>> mse_metric = datasets.load_metric("mse", "multilist")\n >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n >>> references = [[0, 2], [-1, 2], [8, -5]]\n >>> results = mse_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'mse\': 0.7083333333333334}\n >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mse\': array([0.41666667, 1. ])}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __lowerCAmelCase (datasets.Metric ): '''simple docstring''' def UpperCamelCase__ (self : Tuple ): '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , reference_urls=[ '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html''' ] , ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value('''float''' ) ), "references": datasets.Sequence(datasets.Value('''float''' ) ), } else: return { "predictions": datasets.Value('''float''' ), "references": datasets.Value('''float''' ), } def UpperCamelCase__ (self : List[str] , UpperCamelCase : Optional[Any] , UpperCamelCase : str , UpperCamelCase : Optional[int]=None , UpperCamelCase : Tuple="uniform_average" , UpperCamelCase : Union[str, Any]=True ): '''simple docstring''' lowercase__ = mean_squared_error( UpperCamelCase , UpperCamelCase , sample_weight=UpperCamelCase , multioutput=UpperCamelCase , squared=UpperCamelCase ) return {"mse": mse}
2
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : str = Mapping[str, np.ndarray] lowerCamelCase : List[Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Any = 0.0_1 @dataclasses.dataclass(frozen=lowercase_ ) class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ : Optional[str] = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ : Optional[Sequence[str]] = None # Chain corresponding to each parent lowerCAmelCase__ : Optional[Sequence[int]] = None def _SCREAMING_SNAKE_CASE (A ) -> Protein: """simple docstring""" lowercase__ = R'''(\[[A-Z]+\]\n)''' lowercase__ = [tag.strip() for tag in re.split(A , A ) if len(A ) > 0] lowercase__ = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) lowercase__ = ["N", "CA", "C"] lowercase__ = None lowercase__ = None lowercase__ = None for g in groups: if "[PRIMARY]" == g[0]: lowercase__ = g[1][0].strip() for i in range(len(A ) ): if seq[i] not in residue_constants.restypes: lowercase__ = '''X''' # FIXME: strings are immutable lowercase__ = np.array( [residue_constants.restype_order.get(A , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowercase__ = [] for axis in range(3 ): tertiary.append(list(map(A , g[1][axis].split() ) ) ) lowercase__ = np.array(A ) lowercase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowercase__ = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) lowercase__ = np.zeros( ( len(A ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=A , atom_mask=A , aatype=A , residue_index=np.arange(len(A ) ) , b_factors=A , ) def _SCREAMING_SNAKE_CASE (A , A = 0 ) -> List[str]: """simple docstring""" lowercase__ = [] lowercase__ = prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) lowercase__ = prot.parents lowercase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowercase__ = [p for i, p in zip(A , A ) if i == chain_id] if parents is None or len(A ) == 0: lowercase__ = ['''N/A'''] pdb_headers.append(f"PARENT {' '.join(A )}" ) return pdb_headers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = [] lowercase__ = pdb_str.split('''\n''' ) lowercase__ = prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) lowercase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: lowercase__ = [] if prot.parents_chain_index is not None: lowercase__ = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(A ) , [] ) parent_dict[str(A )].append(A ) lowercase__ = max([int(A ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowercase__ = parent_dict.get(str(A ) , ['''N/A'''] ) parents_per_chain.append(A ) else: parents_per_chain.append(list(prot.parents ) ) else: lowercase__ = [['''N/A''']] def make_parent_line(A ) -> str: return f"PARENT {' '.join(A )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowercase__ = 0 for i, l in enumerate(A ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(A ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(A ): lowercase__ = parents_per_chain[chain_counter] else: lowercase__ = ['''N/A'''] out_pdb_lines.append(make_parent_line(A ) ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = residue_constants.restypes + ['''X'''] def res_atoa(A ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) lowercase__ = residue_constants.atom_types lowercase__ = [] lowercase__ = prot.atom_mask lowercase__ = prot.aatype lowercase__ = prot.atom_positions lowercase__ = prot.residue_index.astype(np.intaa ) lowercase__ = prot.b_factors lowercase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) lowercase__ = get_pdb_headers(A ) if len(A ) > 0: pdb_lines.extend(A ) lowercase__ = aatype.shape[0] lowercase__ = 1 lowercase__ = 0 lowercase__ = string.ascii_uppercase lowercase__ = None # Add all atom sites. for i in range(A ): lowercase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(A , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowercase__ = '''ATOM''' lowercase__ = atom_name if len(A ) == 4 else f" {atom_name}" lowercase__ = '''''' lowercase__ = '''''' lowercase__ = 1.00 lowercase__ = atom_name[0] # Protein supports only C, N, O, S, this works. lowercase__ = '''''' lowercase__ = '''A''' if chain_index is not None: lowercase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowercase__ = ( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(A ) atom_index += 1 lowercase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowercase__ = True lowercase__ = chain_index[i + 1] if should_terminate: # Close the chain. lowercase__ = '''TER''' lowercase__ = ( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(A ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(A , A ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _SCREAMING_SNAKE_CASE (A , A , A = None , A = None , A = None , A = None , A = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=A , remark=A , parents=A , parents_chain_index=A , )
2
1
'''simple docstring''' lowerCamelCase : int = 9.8_0_6_6_5 def _SCREAMING_SNAKE_CASE (A , A , A = g ) -> float: """simple docstring""" if fluid_density <= 0: raise ValueError('''Impossible fluid density''' ) if volume < 0: raise ValueError('''Impossible Object volume''' ) if gravity <= 0: raise ValueError('''Impossible Gravity''' ) return fluid_density * gravity * volume if __name__ == "__main__": import doctest # run doctest doctest.testmod()
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> None: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(A , total_number - level + 2 ): current_list.append(A ) create_all_state(i + 1 , A , level - 1 , A , A ) current_list.pop() def _SCREAMING_SNAKE_CASE (A ) -> None: """simple docstring""" for i in total_list: print(*A ) if __name__ == "__main__": lowerCamelCase : Tuple = 4 lowerCamelCase : Union[str, Any] = 2 lowerCamelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
2
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : List[Any] = logging.get_logger(__name__) lowerCamelCase : int = {'ctrl': 'https://huggingface.co/ctrl/resolve/main/config.json'} class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Dict = """ctrl""" lowerCAmelCase__ : List[Any] = ["""past_key_values"""] lowerCAmelCase__ : str = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__(self : Tuple , UpperCamelCase : Optional[Any]=246534 , UpperCamelCase : Union[str, Any]=256 , UpperCamelCase : Optional[int]=1280 , UpperCamelCase : Any=8192 , UpperCamelCase : List[str]=48 , UpperCamelCase : List[Any]=16 , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : str=1E-6 , UpperCamelCase : Optional[int]=0.02 , UpperCamelCase : Dict=True , **UpperCamelCase : Dict , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = n_positions lowercase__ = n_embd lowercase__ = n_layer lowercase__ = n_head lowercase__ = dff lowercase__ = resid_pdrop lowercase__ = embd_pdrop lowercase__ = layer_norm_epsilon lowercase__ = initializer_range lowercase__ = use_cache super().__init__(**UpperCamelCase )
2
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCamelCase : Optional[Any] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) lowerCamelCase : Tuple = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) lowerCamelCase : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) lowerCamelCase : Any = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) lowerCamelCase : Tuple = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) lowerCamelCase : Optional[int] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) lowerCamelCase : Dict = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ = randrange(len(A ) ), randrange(len(A ) ) lowercase__ = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] lowercase__ ,lowercase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE (A = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(A )) @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" assert PokerHand(A )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = PokerHand(A ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" assert PokerHand(A )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = [PokerHand(A ) for hand in SORTED_HANDS] lowercase__ = poker_hands.copy() shuffle(A ) lowercase__ = chain(sorted(A ) ) for index, hand in enumerate(A ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=A ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE () -> int: """simple docstring""" lowercase__ = PokerHand('''2C 4S AS 3D 5C''' ) lowercase__ = True lowercase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = 0 lowercase__ = os.path.abspath(os.path.dirname(A ) ) lowercase__ = os.path.join(A , '''poker_hands.txt''' ) with open(A ) as file_hand: for line in file_hand: lowercase__ = line[:14].strip() lowercase__ = line[15:].strip() lowercase__ ,lowercase__ = PokerHand(A ), PokerHand(A ) lowercase__ = player.compare_with(A ) if output == "Win": answer += 1 assert answer == 376
2
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_mobilebert import MobileBertTokenizer lowerCamelCase : Any = logging.get_logger(__name__) lowerCamelCase : Any = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : Union[str, Any] = { 'vocab_file': {'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/vocab.txt'}, 'tokenizer_file': { 'mobilebert-uncased': 'https://huggingface.co/google/mobilebert-uncased/resolve/main/tokenizer.json' }, } lowerCamelCase : Tuple = {'mobilebert-uncased': 512} lowerCamelCase : int = {} class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Dict = VOCAB_FILES_NAMES lowerCAmelCase__ : Tuple = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[int] = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = MobileBertTokenizer def __init__(self : Optional[int] , UpperCamelCase : Dict=None , UpperCamelCase : Tuple=None , UpperCamelCase : Tuple=True , UpperCamelCase : Union[str, Any]="[UNK]" , UpperCamelCase : Any="[SEP]" , UpperCamelCase : str="[PAD]" , UpperCamelCase : Optional[int]="[CLS]" , UpperCamelCase : str="[MASK]" , UpperCamelCase : Tuple=True , UpperCamelCase : List[str]=None , **UpperCamelCase : List[str] , ): '''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 , ) lowercase__ = 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 ): lowercase__ = getattr(UpperCamelCase , normalizer_state.pop('''type''' ) ) lowercase__ = do_lower_case lowercase__ = strip_accents lowercase__ = tokenize_chinese_chars lowercase__ = normalizer_class(**UpperCamelCase ) lowercase__ = do_lower_case def UpperCamelCase__ (self : str , UpperCamelCase : Tuple , UpperCamelCase : Any=None ): '''simple docstring''' lowercase__ = [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 UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase__ (self : int , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' lowercase__ = self._tokenizer.model.save(UpperCamelCase , name=UpperCamelCase ) return tuple(UpperCamelCase )
2
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase : str = parser.parse_args() if args.model_type == "bert": lowerCamelCase : List[Any] = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase : Any = 'bert' else: raise ValueError('args.model_type should be "bert".') lowerCamelCase : int = model.state_dict() lowerCamelCase : int = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] lowerCamelCase : Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] lowerCamelCase : List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] lowerCamelCase : Tuple = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] lowerCamelCase : Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] lowerCamelCase : Optional[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] lowerCamelCase : Any = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 lowerCamelCase : Optional[int] = state_dict['cls.predictions.decoder.weight'] lowerCamelCase : str = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase : str = state_dict[f"""cls.predictions.transform.dense.{w}"""] lowerCamelCase : Any = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
2
1
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
'''simple docstring''' from ....utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : int=2048 ): '''simple docstring''' lowercase__ = config.__dict__ lowercase__ = modal_hidden_size if num_labels: lowercase__ = num_labels
2
1
'''simple docstring''' import argparse import os # New Code # 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 import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCamelCase : Union[str, Any] = 16 lowerCamelCase : int = 32 def _SCREAMING_SNAKE_CASE (A , A = 16 ) -> str: """simple docstring""" lowercase__ = AutoTokenizer.from_pretrained('''bert-base-cased''' ) lowercase__ = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(A ): # max_length=None => use the model max length (it's actually the default) lowercase__ = 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 # starting with the main process first: with accelerator.main_process_first(): lowercase__ = datasets.map( A , batched=A , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowercase__ = 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. lowercase__ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowercase__ = 16 elif accelerator.mixed_precision != "no": lowercase__ = 8 else: lowercase__ = None return tokenizer.pad( A , padding='''longest''' , max_length=A , pad_to_multiple_of=A , return_tensors='''pt''' , ) # Instantiate dataloaders. lowercase__ = DataLoader( tokenized_datasets['''train'''] , shuffle=A , collate_fn=A , batch_size=A ) lowercase__ = DataLoader( tokenized_datasets['''validation'''] , shuffle=A , collate_fn=A , batch_size=A ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCamelCase : List[Any] = mocked_dataloaders # noqa: F811 def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , A ) == "1": lowercase__ = 2 # Initialize accelerator lowercase__ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowercase__ = config['''lr'''] lowercase__ = int(config['''num_epochs'''] ) lowercase__ = int(config['''seed'''] ) lowercase__ = int(config['''batch_size'''] ) lowercase__ = evaluate.load('''glue''' , '''mrpc''' ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=A ) def inner_training_loop(A ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(A ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowercase__ = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=A ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowercase__ = model.to(accelerator.device ) # Instantiate optimizer lowercase__ = AdamW(params=model.parameters() , lr=A ) lowercase__ ,lowercase__ = get_dataloaders(A , A ) # Instantiate scheduler lowercase__ = get_linear_schedule_with_warmup( optimizer=A , num_warmup_steps=100 , num_training_steps=(len(A ) * num_epochs) , ) # 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. lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = accelerator.prepare( A , A , A , A , A ) # Now we train the model for epoch in range(A ): model.train() for step, batch in enumerate(A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowercase__ = model(**A ) lowercase__ = outputs.loss accelerator.backward(A ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() 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(): lowercase__ = model(**A ) lowercase__ = outputs.logits.argmax(dim=-1 ) lowercase__ ,lowercase__ = accelerator.gather_for_metrics((predictions, batch['''labels''']) ) metric.add_batch( predictions=A , references=A , ) lowercase__ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"epoch {epoch}:" , A ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def _SCREAMING_SNAKE_CASE () -> Dict: """simple docstring""" lowercase__ = argparse.ArgumentParser(description='''Simple example of training script.''' ) parser.add_argument( '''--mixed_precision''' , type=A , default=A , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose''' '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.''' '''and an Nvidia Ampere GPU.''' , ) parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' ) lowercase__ = parser.parse_args() lowercase__ = {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16} training_function(A , A ) if __name__ == "__main__": main()
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """cvt""" def __init__(self : int , UpperCamelCase : List[Any]=3 , UpperCamelCase : int=[7, 3, 3] , UpperCamelCase : str=[4, 2, 2] , UpperCamelCase : Dict=[2, 1, 1] , UpperCamelCase : Dict=[64, 192, 384] , UpperCamelCase : Dict=[1, 3, 6] , UpperCamelCase : Dict=[1, 2, 10] , UpperCamelCase : Any=[4.0, 4.0, 4.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : int=[0.0, 0.0, 0.1] , UpperCamelCase : Any=[True, True, True] , UpperCamelCase : int=[False, False, True] , UpperCamelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase : Optional[int]=[3, 3, 3] , UpperCamelCase : Tuple=[1, 1, 1] , UpperCamelCase : Any=[2, 2, 2] , UpperCamelCase : Dict=[1, 1, 1] , UpperCamelCase : List[str]=[1, 1, 1] , UpperCamelCase : str=0.02 , UpperCamelCase : int=1E-12 , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
2
1
'''simple docstring''' import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __lowerCAmelCase : '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : int=13 , UpperCamelCase : List[Any]=3 , UpperCamelCase : Union[str, Any]=True , UpperCamelCase : Any=True , UpperCamelCase : Optional[int]=0.1 , UpperCamelCase : List[Any]=0.1 , UpperCamelCase : Optional[Any]=224 , UpperCamelCase : int=1000 , UpperCamelCase : Dict=[3, 3, 6, 4] , UpperCamelCase : str=[48, 56, 112, 220] , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = num_channels lowercase__ = is_training lowercase__ = use_labels lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = num_labels lowercase__ = image_size lowercase__ = layer_depths lowercase__ = embed_dims def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.num_labels ) lowercase__ = self.get_config() return config, pixel_values, labels def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='''gelu''' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=UpperCamelCase , layer_scale_init_value=1E-5 , ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : Any , UpperCamelCase : Optional[int] , UpperCamelCase : Optional[int] ): '''simple docstring''' lowercase__ = SwiftFormerModel(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def UpperCamelCase__ (self : str , UpperCamelCase : Optional[Any] , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = self.num_labels lowercase__ = SwiftFormerForImageClassification(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) lowercase__ = SwiftFormerForImageClassification(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = model(UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' ((lowercase__) ,(lowercase__) ,(lowercase__)) = self.prepare_config_and_inputs() lowercase__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : int = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () lowerCAmelCase__ : int = ( {"""feature-extraction""": SwiftFormerModel, """image-classification""": SwiftFormerForImageClassification} if is_torch_available() else {} ) lowerCAmelCase__ : str = False lowerCAmelCase__ : Dict = False lowerCAmelCase__ : str = False lowerCAmelCase__ : Tuple = False lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = SwiftFormerModelTester(self ) lowercase__ = ConfigTester( self , config_class=UpperCamelCase , has_text_modality=UpperCamelCase , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase ) lowercase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase , nn.Linear ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase ) 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] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase ) @slow def UpperCamelCase__ (self : Dict ): '''simple docstring''' for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ = SwiftFormerModel.from_pretrained(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @unittest.skip(reason='''SwiftFormer does not output attentions''' ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' pass def UpperCamelCase__ (self : int ): '''simple docstring''' def check_hidden_states_output(UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : str ): lowercase__ = model_class(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() with torch.no_grad(): lowercase__ = model(**self._prepare_for_class(UpperCamelCase , UpperCamelCase ) ) lowercase__ = outputs.hidden_states lowercase__ = 8 self.assertEqual(len(UpperCamelCase ) , UpperCamelCase ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(UpperCamelCase ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = True check_hidden_states_output(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ = True check_hidden_states_output(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' def _config_zero_init(UpperCamelCase : int ): lowercase__ = copy.deepcopy(UpperCamelCase ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(UpperCamelCase , UpperCamelCase , 1E-10 ) if isinstance(getattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) , UpperCamelCase ): lowercase__ = _config_zero_init(getattr(UpperCamelCase , UpperCamelCase ) ) setattr(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return configs_no_init lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = _config_zero_init(UpperCamelCase ) for model_class in self.all_model_classes: lowercase__ = model_class(config=UpperCamelCase ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' pass def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ (self : Dict ): '''simple docstring''' return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None @slow def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(UpperCamelCase ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=UpperCamelCase , return_tensors='''pt''' ).to(UpperCamelCase ) # forward pass with torch.no_grad(): lowercase__ = model(**UpperCamelCase ) # verify the logits lowercase__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase ) lowercase__ = torch.tensor([[-2.17_03E00, 2.11_07E00, -2.08_11E00]] ).to(UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1E-4 ) )
2
'''simple docstring''' import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCamelCase : Any = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCamelCase : Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCamelCase : Any = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) lowerCamelCase : List[Any] = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) lowerCamelCase : List[str] = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions lowerCamelCase : List[str] = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(64, 64) ) lowerCamelCase : Optional[int] = tf.keras.preprocessing.image.img_to_array(test_image) lowerCamelCase : str = np.expand_dims(test_image, axis=0) lowerCamelCase : List[str] = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCamelCase : Any = 'Normal' if result[0][0] == 1: lowerCamelCase : Any = 'Abnormality detected'
2
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor lowerCamelCase : str = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , *UpperCamelCase : int , **UpperCamelCase : Optional[int] ): '''simple docstring''' warnings.warn( '''The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use ImageGPTImageProcessor instead.''' , UpperCamelCase , ) super().__init__(*UpperCamelCase , **UpperCamelCase )
2
'''simple docstring''' class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__(self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = row lowercase__ = col lowercase__ = graph def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowercase__ = [-1, 0, 1, -1, 1, -1, 0, 1] lowercase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): # And finally, count all islands. '''simple docstring''' lowercase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] lowercase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += 1 return count
2
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
'''simple docstring''' import unittest from transformers import DonutProcessor lowerCamelCase : Tuple = 'naver-clova-ix/donut-base' class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = DonutProcessor.from_pretrained(UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowercase__ = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowercase__ = self.processor.tokenajson(UpperCamelCase ) self.assertDictEqual(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' import requests from bsa import BeautifulSoup def _SCREAMING_SNAKE_CASE (A = "https://www.worldometers.info/coronavirus" ) -> dict: """simple docstring""" lowercase__ = BeautifulSoup(requests.get(A ).text , '''html.parser''' ) lowercase__ = soup.findAll('''h1''' ) lowercase__ = soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(A , A )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(f"""{key}\n{value}\n""")
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return len(set(A ) ) == len(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
'''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() lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : List[Any] = ['model.decoder.embed_positions.weights'] def _SCREAMING_SNAKE_CASE (A ) -> Any: """simple docstring""" if "emb" in name: lowercase__ = name.replace('''emb''' , '''model.decoder.embed_tokens''' ) if "transformer" in name: lowercase__ = name.replace('''transformer''' , '''model.decoder''' ) if "cross_attention" in name: lowercase__ = name.replace('''cross_attention''' , '''encoder_attn''' ) if "linear1" in name: lowercase__ = name.replace('''linear1''' , '''fc1''' ) if "linear2" in name: lowercase__ = name.replace('''linear2''' , '''fc2''' ) if "norm1" in name: lowercase__ = name.replace('''norm1''' , '''self_attn_layer_norm''' ) if "norm_cross" in name: lowercase__ = name.replace('''norm_cross''' , '''encoder_attn_layer_norm''' ) if "norm2" in name: lowercase__ = name.replace('''norm2''' , '''final_layer_norm''' ) if "out_norm" in name: lowercase__ = name.replace('''out_norm''' , '''model.decoder.layer_norm''' ) if "linears" in name: lowercase__ = name.replace('''linears''' , '''lm_heads''' ) if "condition_provider.conditioners.description.output_proj" in name: lowercase__ = name.replace('''condition_provider.conditioners.description.output_proj''' , '''enc_to_dec_proj''' ) return name def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple[Dict, Dict]: """simple docstring""" lowercase__ = list(state_dict.keys() ) lowercase__ = {} for key in keys: lowercase__ = state_dict.pop(A ) lowercase__ = rename_keys(A ) if "in_proj_weight" in key: # split fused qkv proj lowercase__ = val[:hidden_size, :] lowercase__ = val[hidden_size : 2 * hidden_size, :] lowercase__ = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: lowercase__ = val else: lowercase__ = val return state_dict, enc_dec_proj_state_dict def _SCREAMING_SNAKE_CASE (A ) -> MusicgenDecoderConfig: """simple docstring""" if checkpoint == "small": # default config values lowercase__ = 1_024 lowercase__ = 24 lowercase__ = 16 elif checkpoint == "medium": lowercase__ = 1_536 lowercase__ = 48 lowercase__ = 24 elif checkpoint == "large": lowercase__ = 2_048 lowercase__ = 48 lowercase__ = 32 else: raise ValueError(f"Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}." ) lowercase__ = MusicgenDecoderConfig( hidden_size=A , ffn_dim=hidden_size * 4 , num_hidden_layers=A , num_attention_heads=A , ) return config @torch.no_grad() def _SCREAMING_SNAKE_CASE (A , A=None , A=None , A="cpu" ) -> List[str]: """simple docstring""" lowercase__ = MusicGen.get_pretrained(A , device=A ) lowercase__ = decoder_config_from_checkpoint(A ) lowercase__ = fairseq_model.lm.state_dict() lowercase__ ,lowercase__ = rename_state_dict( A , hidden_size=decoder_config.hidden_size ) lowercase__ = TaEncoderModel.from_pretrained('''t5-base''' ) lowercase__ = EncodecModel.from_pretrained('''facebook/encodec_32khz''' ) lowercase__ = MusicgenForCausalLM(A ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection lowercase__ ,lowercase__ = decoder.load_state_dict(A , strict=A ) for key in missing_keys.copy(): if key.startswith(('''text_encoder''', '''audio_encoder''') ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(A ) if len(A ) > 0: raise ValueError(f"Missing key(s) in state_dict: {missing_keys}" ) if len(A ) > 0: raise ValueError(f"Unexpected key(s) in state_dict: {unexpected_keys}" ) # init the composite model lowercase__ = MusicgenForConditionalGeneration(text_encoder=A , audio_encoder=A , decoder=A ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(A ) # check we can do a forward pass lowercase__ = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) lowercase__ = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): lowercase__ = model(input_ids=A , decoder_input_ids=A ).logits if logits.shape != (8, 1, 2_048): raise ValueError('''Incorrect shape for logits''' ) # now construct the processor lowercase__ = AutoTokenizer.from_pretrained('''t5-base''' ) lowercase__ = AutoFeatureExtractor.from_pretrained('''facebook/encodec_32khz''' , padding_side='''left''' ) lowercase__ = MusicgenProcessor(feature_extractor=A , tokenizer=A ) # set the appropriate bos/pad token ids lowercase__ = 2_048 lowercase__ = 2_048 # set other default generation config params lowercase__ = int(30 * audio_encoder.config.frame_rate ) lowercase__ = True lowercase__ = 3.0 if pytorch_dump_folder is not None: Path(A ).mkdir(exist_ok=A ) logger.info(f"Saving model {checkpoint} to {pytorch_dump_folder}" ) model.save_pretrained(A ) processor.save_pretrained(A ) if repo_id: logger.info(f"Pushing model {checkpoint} to {repo_id}" ) model.push_to_hub(A ) processor.push_to_hub(A ) if __name__ == "__main__": lowerCamelCase : Union[str, Any] = 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.' ) lowerCamelCase : List[str] = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
2
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: lowerCamelCase : Any = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : List[str] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 lowerCamelCase : Any = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : str = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = TaTokenizer lowerCAmelCase__ : List[int] = [] def __init__(self : Dict , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any="</s>" , UpperCamelCase : str="<unk>" , UpperCamelCase : List[str]="<pad>" , UpperCamelCase : List[str]=100 , UpperCamelCase : Tuple=None , **UpperCamelCase : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase__ = [f"<extra_id_{i}>" for i in range(UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase__ = len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) ) , UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , extra_ids=UpperCamelCase , additional_special_tokens=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True lowercase__ = extra_ids @staticmethod def UpperCamelCase__ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f" {pretrained_model_name_or_path} automatically truncating your input to" f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase , ) return max_model_length def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) logger.info(f"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>''' , UpperCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]
2
1
'''simple docstring''' from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class __lowerCAmelCase : '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple=12 , UpperCamelCase : Tuple=7 , UpperCamelCase : List[str]=True , UpperCamelCase : Dict=True , UpperCamelCase : int=True , UpperCamelCase : str=99 , UpperCamelCase : Tuple=32 , UpperCamelCase : Dict=32 , UpperCamelCase : List[str]=2 , UpperCamelCase : int=4 , UpperCamelCase : Optional[int]=37 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.1 , UpperCamelCase : List[str]=512 , UpperCamelCase : Optional[int]=0.02 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Union[str, Any]=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_input_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = projection_dim lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = dropout lowercase__ = attention_dropout lowercase__ = max_position_embeddings lowercase__ = initializer_range lowercase__ = scope lowercase__ = bos_token_id def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = None if self.use_input_mask: lowercase__ = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: lowercase__ = input_mask.numpy() lowercase__ ,lowercase__ = input_mask.shape lowercase__ = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCamelCase ): lowercase__ = 1 lowercase__ = 0 lowercase__ = self.get_config() return config, input_ids, tf.convert_to_tensor(UpperCamelCase ) def UpperCamelCase__ (self : Any ): '''simple docstring''' return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = TFBlipTextModel(config=UpperCamelCase ) lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , training=UpperCamelCase ) lowercase__ = model(UpperCamelCase , training=UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : str = (TFBlipTextModel,) if is_tf_available() else () lowerCAmelCase__ : Union[str, Any] = False lowerCAmelCase__ : int = False lowerCAmelCase__ : Tuple = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = BlipTextModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase , hidden_size=37 ) def UpperCamelCase__ (self : int ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' pass @slow def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ = TFBlipTextModel.from_pretrained(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : Any=True ): '''simple docstring''' super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase )
2
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = ShapEImgaImgPipeline lowerCAmelCase__ : List[str] = ["""image"""] lowerCAmelCase__ : Any = ["""image"""] lowerCAmelCase__ : Any = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] lowerCAmelCase__ : Tuple = False @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : str ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase__ (self : int ): '''simple docstring''' return 8 @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(UpperCamelCase ) return model @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase , do_normalize=UpperCamelCase , do_resize=UpperCamelCase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def UpperCamelCase__ (self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase__ = PriorTransformer(**UpperCamelCase ) return model @property def UpperCamelCase__ (self : int ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**UpperCamelCase ) return model def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase , clip_sample=UpperCamelCase , clip_sample_range=1.0 , ) lowercase__ = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : str=0 ): '''simple docstring''' lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) if str(UpperCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(UpperCamelCase ) else: lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowercase__ = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = '''cpu''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = pipe(**self.get_dummy_inputs(UpperCamelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = torch_device == '''cpu''' lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase , relax_max_difference=UpperCamelCase , ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(UpperCamelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**UpperCamelCase , num_images_per_prompt=UpperCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase__ = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(0 ) lowercase__ = pipe( UpperCamelCase , generator=UpperCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : Any = { 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxConfig', 'GroupViTTextConfig', 'GroupViTVisionConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GroupViTModel', 'GroupViTPreTrainedModel', 'GroupViTTextModel', 'GroupViTVisionModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ 'TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFGroupViTModel', 'TFGroupViTPreTrainedModel', 'TFGroupViTTextModel', 'TFGroupViTVisionModel', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys lowerCamelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
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, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : jnp.ndarray lowerCAmelCase__ : jnp.ndarray class __lowerCAmelCase (nn.Module ): '''simple docstring''' lowerCAmelCase__ : int lowerCAmelCase__ : Tuple[int] = (16, 32, 96, 256) lowerCAmelCase__ : jnp.dtype = jnp.floataa def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowercase__ = [] for i in range(len(self.block_out_channels ) - 1 ): lowercase__ = self.block_out_channels[i] lowercase__ = self.block_out_channels[i + 1] lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(UpperCamelCase ) lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(UpperCamelCase ) lowercase__ = blocks lowercase__ = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self : int , UpperCamelCase : Tuple ): '''simple docstring''' lowercase__ = self.conv_in(UpperCamelCase ) lowercase__ = nn.silu(UpperCamelCase ) for block in self.blocks: lowercase__ = block(UpperCamelCase ) lowercase__ = nn.silu(UpperCamelCase ) lowercase__ = self.conv_out(UpperCamelCase ) return embedding @flax_register_to_config class __lowerCAmelCase (nn.Module , lowercase_ , lowercase_ ): '''simple docstring''' lowerCAmelCase__ : int = 32 lowerCAmelCase__ : int = 4 lowerCAmelCase__ : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) 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__ : str = "rgb" lowerCAmelCase__ : Tuple[int] = (16, 32, 96, 256) def UpperCamelCase__ (self : str , UpperCamelCase : jax.random.KeyArray ): '''simple docstring''' lowercase__ = (1, self.in_channels, self.sample_size, self.sample_size) lowercase__ = jnp.zeros(UpperCamelCase , dtype=jnp.floataa ) lowercase__ = jnp.ones((1,) , dtype=jnp.intaa ) lowercase__ = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowercase__ = (1, 3, self.sample_size * 8, self.sample_size * 8) lowercase__ = jnp.zeros(UpperCamelCase , dtype=jnp.floataa ) lowercase__ ,lowercase__ = jax.random.split(UpperCamelCase ) lowercase__ = {'''params''': params_rng, '''dropout''': dropout_rng} return self.init(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase )["params"] def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.block_out_channels lowercase__ = block_out_channels[0] * 4 # 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. lowercase__ = self.num_attention_heads or self.attention_head_dim # input lowercase__ = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowercase__ = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowercase__ = FlaxTimestepEmbedding(UpperCamelCase , dtype=self.dtype ) lowercase__ = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowercase__ = self.only_cross_attention if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = (only_cross_attention,) * len(self.down_block_types ) if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = (num_attention_heads,) * len(self.down_block_types ) # down lowercase__ = [] lowercase__ = [] lowercase__ = block_out_channels[0] lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCamelCase ) for i, down_block_type in enumerate(self.down_block_types ): lowercase__ = output_channel lowercase__ = block_out_channels[i] lowercase__ = i == len(UpperCamelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowercase__ = FlaxCrossAttnDownBlockaD( in_channels=UpperCamelCase , out_channels=UpperCamelCase , 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] , dtype=self.dtype , ) else: lowercase__ = FlaxDownBlockaD( in_channels=UpperCamelCase , out_channels=UpperCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(UpperCamelCase ) for _ in range(self.layers_per_block ): lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCamelCase ) if not is_final_block: lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(UpperCamelCase ) lowercase__ = down_blocks lowercase__ = controlnet_down_blocks # mid lowercase__ = block_out_channels[-1] lowercase__ = FlaxUNetMidBlockaDCrossAttn( in_channels=UpperCamelCase , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowercase__ = nn.Conv( UpperCamelCase , kernel_size=(1, 1) , padding='''VALID''' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__(self : str , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : List[Any] , UpperCamelCase : Any , UpperCamelCase : float = 1.0 , UpperCamelCase : bool = True , UpperCamelCase : bool = False , ): '''simple docstring''' lowercase__ = self.controlnet_conditioning_channel_order if channel_order == "bgr": lowercase__ = jnp.flip(UpperCamelCase , axis=1 ) # 1. time if not isinstance(UpperCamelCase , jnp.ndarray ): lowercase__ = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(UpperCamelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: lowercase__ = timesteps.astype(dtype=jnp.floataa ) lowercase__ = jnp.expand_dims(UpperCamelCase , 0 ) lowercase__ = self.time_proj(UpperCamelCase ) lowercase__ = self.time_embedding(UpperCamelCase ) # 2. pre-process lowercase__ = jnp.transpose(UpperCamelCase , (0, 2, 3, 1) ) lowercase__ = self.conv_in(UpperCamelCase ) lowercase__ = jnp.transpose(UpperCamelCase , (0, 2, 3, 1) ) lowercase__ = self.controlnet_cond_embedding(UpperCamelCase ) sample += controlnet_cond # 3. down lowercase__ = (sample,) for down_block in self.down_blocks: if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ ,lowercase__ = down_block(UpperCamelCase , UpperCamelCase , UpperCamelCase , deterministic=not train ) else: lowercase__ ,lowercase__ = down_block(UpperCamelCase , UpperCamelCase , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowercase__ = self.mid_block(UpperCamelCase , UpperCamelCase , UpperCamelCase , deterministic=not train ) # 5. contronet blocks lowercase__ = () for down_block_res_sample, controlnet_block in zip(UpperCamelCase , self.controlnet_down_blocks ): lowercase__ = controlnet_block(UpperCamelCase ) controlnet_down_block_res_samples += (down_block_res_sample,) lowercase__ = controlnet_down_block_res_samples lowercase__ = self.controlnet_mid_block(UpperCamelCase ) # 6. scaling lowercase__ = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=UpperCamelCase , mid_block_res_sample=UpperCamelCase )
2
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : int = (DPMSolverSinglestepScheduler,) lowerCAmelCase__ : Optional[int] = (("""num_inference_steps""", 25),) def UpperCamelCase__ (self : Optional[int] , **UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = { '''num_train_timesteps''': 1000, '''beta_start''': 0.00_01, '''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(**UpperCamelCase ) return config def UpperCamelCase__ (self : int , UpperCamelCase : Tuple=0 , **UpperCamelCase : int ): '''simple docstring''' lowercase__ = dict(self.forward_default_kwargs ) lowercase__ = kwargs.pop('''num_inference_steps''' , UpperCamelCase ) lowercase__ = self.dummy_sample lowercase__ = 0.1 * sample lowercase__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowercase__ = self.get_scheduler_config(**UpperCamelCase ) lowercase__ = scheduler_class(**UpperCamelCase ) scheduler.set_timesteps(UpperCamelCase ) # copy over dummy past residuals lowercase__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase ) lowercase__ = scheduler_class.from_pretrained(UpperCamelCase ) new_scheduler.set_timesteps(UpperCamelCase ) # copy over dummy past residuals lowercase__ = dummy_past_residuals[: new_scheduler.config.solver_order] lowercase__ ,lowercase__ = sample, sample for t in range(UpperCamelCase , time_step + scheduler.config.solver_order + 1 ): lowercase__ = scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , **UpperCamelCase ).prev_sample lowercase__ = new_scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , **UpperCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase__ (self : str ): '''simple docstring''' pass def UpperCamelCase__ (self : List[Any] , UpperCamelCase : Union[str, Any]=0 , **UpperCamelCase : Optional[int] ): '''simple docstring''' lowercase__ = dict(self.forward_default_kwargs ) lowercase__ = kwargs.pop('''num_inference_steps''' , UpperCamelCase ) lowercase__ = self.dummy_sample lowercase__ = 0.1 * sample lowercase__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: lowercase__ = self.get_scheduler_config() lowercase__ = scheduler_class(**UpperCamelCase ) scheduler.set_timesteps(UpperCamelCase ) # copy over dummy past residuals (must be after setting timesteps) lowercase__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCamelCase ) lowercase__ = scheduler_class.from_pretrained(UpperCamelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(UpperCamelCase ) # copy over dummy past residual (must be after setting timesteps) lowercase__ = dummy_past_residuals[: new_scheduler.config.solver_order] lowercase__ = scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , **UpperCamelCase ).prev_sample lowercase__ = new_scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , **UpperCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCamelCase__ (self : Dict , UpperCamelCase : Union[str, Any]=None , **UpperCamelCase : Any ): '''simple docstring''' if scheduler is None: lowercase__ = self.scheduler_classes[0] lowercase__ = self.get_scheduler_config(**UpperCamelCase ) lowercase__ = scheduler_class(**UpperCamelCase ) lowercase__ = self.scheduler_classes[0] lowercase__ = self.get_scheduler_config(**UpperCamelCase ) lowercase__ = scheduler_class(**UpperCamelCase ) lowercase__ = 10 lowercase__ = self.dummy_model() lowercase__ = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase ) for i, t in enumerate(scheduler.timesteps ): lowercase__ = model(UpperCamelCase , UpperCamelCase ) lowercase__ = scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase ).prev_sample return sample def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) lowercase__ = 50 lowercase__ = self.dummy_model() lowercase__ = self.dummy_sample_deter scheduler.set_timesteps(UpperCamelCase ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): lowercase__ = model(UpperCamelCase , UpperCamelCase ) lowercase__ = scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase ).prev_sample lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.25_74 ) < 1E-3 def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' for timesteps in [25, 50, 100, 999, 1000]: self.check_over_configs(num_train_timesteps=UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) lowercase__ = self.full_loop(scheduler=UpperCamelCase ) lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.27_91 ) < 1E-3 lowercase__ = DEISMultistepScheduler.from_config(scheduler.config ) lowercase__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) lowercase__ = UniPCMultistepScheduler.from_config(scheduler.config ) lowercase__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) lowercase__ = self.full_loop(scheduler=UpperCamelCase ) lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.27_91 ) < 1E-3 def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' self.check_over_configs(thresholding=UpperCamelCase ) 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=UpperCamelCase , prediction_type=UpperCamelCase , sample_max_value=UpperCamelCase , algorithm_type='''dpmsolver++''' , solver_order=UpperCamelCase , solver_type=UpperCamelCase , ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCamelCase ) def UpperCamelCase__ (self : 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=UpperCamelCase , solver_type=UpperCamelCase , prediction_type=UpperCamelCase , algorithm_type=UpperCamelCase , ) lowercase__ = self.full_loop( solver_order=UpperCamelCase , solver_type=UpperCamelCase , prediction_type=UpperCamelCase , algorithm_type=UpperCamelCase , ) assert not torch.isnan(UpperCamelCase ).any(), "Samples have nan numbers" def UpperCamelCase__ (self : int ): '''simple docstring''' self.check_over_configs(lower_order_final=UpperCamelCase ) self.check_over_configs(lower_order_final=UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float('''inf''' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' self.check_over_configs(variance_type=UpperCamelCase ) self.check_over_configs(variance_type='''learned_range''' ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]: self.check_over_forward(num_inference_steps=UpperCamelCase , time_step=0 ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.full_loop() lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.27_91 ) < 1E-3 def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = self.full_loop(use_karras_sigmas=UpperCamelCase ) lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.22_48 ) < 1E-3 def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = self.full_loop(prediction_type='''v_prediction''' ) lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.14_53 ) < 1E-3 def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.full_loop(prediction_type='''v_prediction''' , use_karras_sigmas=UpperCamelCase ) lowercase__ = torch.mean(torch.abs(UpperCamelCase ) ) assert abs(result_mean.item() - 0.06_49 ) < 1E-3 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.scheduler_classes[0] lowercase__ = self.get_scheduler_config(thresholding=UpperCamelCase , dynamic_thresholding_ratio=0 ) lowercase__ = scheduler_class(**UpperCamelCase ) lowercase__ = 10 lowercase__ = self.dummy_model() lowercase__ = self.dummy_sample_deter.half() scheduler.set_timesteps(UpperCamelCase ) for i, t in enumerate(scheduler.timesteps ): lowercase__ = model(UpperCamelCase , UpperCamelCase ) lowercase__ = scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase ).prev_sample assert sample.dtype == torch.floataa
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 __future__ import annotations from fractions import Fraction from math import gcd, sqrt def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" lowercase__ = int(number**0.5 ) return number == sq * sq def _SCREAMING_SNAKE_CASE (A , A , A , A , A , A ) -> tuple[int, int]: """simple docstring""" lowercase__ = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den lowercase__ = x_den * y_den * z_den lowercase__ = gcd(A , A ) top //= hcf bottom //= hcf return top, bottom def _SCREAMING_SNAKE_CASE (A = 35 ) -> int: """simple docstring""" lowercase__ = set() lowercase__ = 42 lowercase__ = Fraction(0 ) lowercase__ = 42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 lowercase__ = x_num * y_den + x_den * y_num lowercase__ = x_den * y_den lowercase__ = gcd(A , A ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowercase__ = add_three( A , A , A , A , A , A ) unique_s.add(A ) # n=2 lowercase__ = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) lowercase__ = x_den * x_den * y_den * y_den if is_sq(A ) and is_sq(A ): lowercase__ = int(sqrt(A ) ) lowercase__ = int(sqrt(A ) ) lowercase__ = gcd(A , A ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowercase__ = add_three( A , A , A , A , A , A ) unique_s.add(A ) # n=-1 lowercase__ = x_num * y_num lowercase__ = x_den * y_num + x_num * y_den lowercase__ = gcd(A , A ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowercase__ = add_three( A , A , A , A , A , A ) unique_s.add(A ) # n=2 lowercase__ = x_num * x_num * y_num * y_num lowercase__ = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(A ) and is_sq(A ): lowercase__ = int(sqrt(A ) ) lowercase__ = int(sqrt(A ) ) lowercase__ = gcd(A , A ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowercase__ = add_three( A , A , A , A , A , A ) unique_s.add(A ) for num, den in unique_s: total += Fraction(A , A ) return total.denominator + total.numerator if __name__ == "__main__": print(f"""{solution() = }""")
2
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = 0 lowercase__ = len(A ) for i in range(n - 1 ): for j in range(i + 1 , A ): if arr[i] > arr[j]: num_inversions += 1 return num_inversions def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" if len(A ) <= 1: return arr, 0 lowercase__ = len(A ) // 2 lowercase__ = arr[0:mid] lowercase__ = arr[mid:] lowercase__ ,lowercase__ = count_inversions_recursive(A ) lowercase__ ,lowercase__ = count_inversions_recursive(A ) lowercase__ ,lowercase__ = _count_cross_inversions(A , A ) lowercase__ = inversion_p + inversions_q + cross_inversions return c, num_inversions def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" lowercase__ = [] lowercase__ = lowercase__ = lowercase__ = 0 while i < len(A ) and j < len(A ): if p[i] > q[j]: # if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P) # These are all inversions. The claim emerges from the # property that P is sorted. num_inversion += len(A ) - i r.append(q[j] ) j += 1 else: r.append(p[i] ) i += 1 if i < len(A ): r.extend(p[i:] ) else: r.extend(q[j:] ) return r, num_inversion def _SCREAMING_SNAKE_CASE () -> str: """simple docstring""" lowercase__ = [10, 2, 1, 5, 5, 2, 11] # this arr has 8 inversions: # (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2) lowercase__ = count_inversions_bf(A ) lowercase__ ,lowercase__ = count_inversions_recursive(A ) assert num_inversions_bf == num_inversions_recursive == 8 print('''number of inversions = ''' , A ) # testing an array with zero inversion (a sorted arr_1) arr_a.sort() lowercase__ = count_inversions_bf(A ) lowercase__ ,lowercase__ = count_inversions_recursive(A ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , A ) # an empty list should also have zero inversions lowercase__ = [] lowercase__ = count_inversions_bf(A ) lowercase__ ,lowercase__ = count_inversions_recursive(A ) assert num_inversions_bf == num_inversions_recursive == 0 print('''number of inversions = ''' , A ) if __name__ == "__main__": main()
2
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
1
'''simple docstring''' import os from collections.abc import Iterator def _SCREAMING_SNAKE_CASE (A = "." ) -> Iterator[str]: """simple docstring""" for dir_path, dir_names, filenames in os.walk(A ): lowercase__ = [d for d in dir_names if d != '''scripts''' and d[0] not in '''._'''] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(A )[1] in (".py", ".ipynb"): yield os.path.join(A , A ).lstrip('''./''' ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" return f"{i * ' '}*" if i else "\n##" def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(A ) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(A )} {new_part.replace('_' , ' ' ).title()}" ) return new_path def _SCREAMING_SNAKE_CASE (A = "." ) -> None: """simple docstring""" lowercase__ = '''''' for filepath in sorted(good_file_paths(A ) ): lowercase__ ,lowercase__ = os.path.split(A ) if filepath != old_path: lowercase__ = print_path(A , A ) lowercase__ = (filepath.count(os.sep ) + 1) if filepath else 0 lowercase__ = f"{filepath}/{filename}".replace(''' ''' , '''%20''' ) lowercase__ = os.path.splitext(filename.replace('''_''' , ''' ''' ).title() )[0] print(f"{md_prefix(A )} [{filename}]({url})" ) if __name__ == "__main__": print_directory_md('.')
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """megatron-bert""" def __init__(self : Tuple , UpperCamelCase : Optional[int]=29056 , UpperCamelCase : Optional[Any]=1024 , UpperCamelCase : Any=24 , UpperCamelCase : int=16 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : int="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any=512 , UpperCamelCase : int=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Optional[int]="absolute" , UpperCamelCase : List[Any]=True , **UpperCamelCase : str , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache
2
1
'''simple docstring''' from __future__ import annotations from statistics import mean def _SCREAMING_SNAKE_CASE (A , A , A ) -> list[int]: """simple docstring""" lowercase__ = [0] * no_of_processes lowercase__ = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(A ): lowercase__ = burst_time[i] lowercase__ = [] lowercase__ = 0 lowercase__ = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: lowercase__ = [] lowercase__ = -1 for i in range(A ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(A ) if len(A ) > 0: lowercase__ = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: lowercase__ = i total_time += burst_time[target_process] completed += 1 lowercase__ = 0 lowercase__ = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def _SCREAMING_SNAKE_CASE (A , A , A ) -> list[int]: """simple docstring""" lowercase__ = [0] * no_of_processes for i in range(A ): lowercase__ = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print('[TEST CASE 01]') lowerCamelCase : Union[str, Any] = 4 lowerCamelCase : Optional[Any] = [2, 5, 3, 7] lowerCamelCase : str = [0, 0, 0, 0] lowerCamelCase : Any = calculate_waitingtime(arrival_time, burst_time, no_of_processes) lowerCamelCase : Optional[int] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print('PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time') for i, process_id in enumerate(list(range(1, 5))): print( f"""{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t""" f"""{waiting_time[i]}\t\t\t\t{turn_around_time[i]}""" ) print(f"""\nAverage waiting time = {mean(waiting_time):.5f}""") print(f"""Average turnaround time = {mean(turn_around_time):.5f}""")
2
'''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
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Union[str, Any] = {'configuration_timm_backbone': ['TimmBackboneConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : List[str] = ['TimmBackbone'] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
1
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: lowerCamelCase : Any = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : List[str] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 lowerCamelCase : Any = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : str = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = TaTokenizer lowerCAmelCase__ : List[int] = [] def __init__(self : Dict , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any="</s>" , UpperCamelCase : str="<unk>" , UpperCamelCase : List[str]="<pad>" , UpperCamelCase : List[str]=100 , UpperCamelCase : Tuple=None , **UpperCamelCase : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase__ = [f"<extra_id_{i}>" for i in range(UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase__ = len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) ) , UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , extra_ids=UpperCamelCase , additional_special_tokens=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True lowercase__ = extra_ids @staticmethod def UpperCamelCase__ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f" {pretrained_model_name_or_path} automatically truncating your input to" f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase , ) return max_model_length def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) logger.info(f"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>''' , UpperCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]
2
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" _enforce_args(A , A ) if n == 0: return 0 lowercase__ = float('''-inf''' ) for i in range(1 , n + 1 ): lowercase__ = max( A , prices[i - 1] + naive_cut_rod_recursive(n - i , A ) ) return max_revue def _SCREAMING_SNAKE_CASE (A , A ) -> Dict: """simple docstring""" _enforce_args(A , A ) lowercase__ = [float('''-inf''' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(A , A , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> List[Any]: """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: lowercase__ = float('''-inf''' ) for i in range(1 , n + 1 ): lowercase__ = max( A , prices[i - 1] + _top_down_cut_rod_recursive(n - i , A , A ) , ) lowercase__ = max_revenue return max_rev[n] def _SCREAMING_SNAKE_CASE (A , A ) -> Any: """simple docstring""" _enforce_args(A , A ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. lowercase__ = [float('''-inf''' ) for _ in range(n + 1 )] lowercase__ = 0 for i in range(1 , n + 1 ): lowercase__ = max_rev[i] for j in range(1 , i + 1 ): lowercase__ = max(A , prices[j - 1] + max_rev[i - j] ) lowercase__ = max_revenue_i return max_rev[n] def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" if n < 0: lowercase__ = f"n must be greater than or equal to 0. Got n = {n}" raise ValueError(A ) if n > len(A ): lowercase__ = ( '''Each integral piece of rod must have a corresponding price. ''' f"Got n = {n} but length of prices = {len(A )}" ) raise ValueError(A ) def _SCREAMING_SNAKE_CASE () -> Any: """simple docstring""" lowercase__ = [6, 10, 12, 15, 20, 23] lowercase__ = len(A ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. lowercase__ = 36 lowercase__ = top_down_cut_rod(A , A ) lowercase__ = bottom_up_cut_rod(A , A ) lowercase__ = naive_cut_rod_recursive(A , A ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
2
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : str = Mapping[str, np.ndarray] lowerCamelCase : List[Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Any = 0.0_1 @dataclasses.dataclass(frozen=lowercase_ ) class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ : Optional[str] = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ : Optional[Sequence[str]] = None # Chain corresponding to each parent lowerCAmelCase__ : Optional[Sequence[int]] = None def _SCREAMING_SNAKE_CASE (A ) -> Protein: """simple docstring""" lowercase__ = R'''(\[[A-Z]+\]\n)''' lowercase__ = [tag.strip() for tag in re.split(A , A ) if len(A ) > 0] lowercase__ = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) lowercase__ = ["N", "CA", "C"] lowercase__ = None lowercase__ = None lowercase__ = None for g in groups: if "[PRIMARY]" == g[0]: lowercase__ = g[1][0].strip() for i in range(len(A ) ): if seq[i] not in residue_constants.restypes: lowercase__ = '''X''' # FIXME: strings are immutable lowercase__ = np.array( [residue_constants.restype_order.get(A , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowercase__ = [] for axis in range(3 ): tertiary.append(list(map(A , g[1][axis].split() ) ) ) lowercase__ = np.array(A ) lowercase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowercase__ = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) lowercase__ = np.zeros( ( len(A ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=A , atom_mask=A , aatype=A , residue_index=np.arange(len(A ) ) , b_factors=A , ) def _SCREAMING_SNAKE_CASE (A , A = 0 ) -> List[str]: """simple docstring""" lowercase__ = [] lowercase__ = prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) lowercase__ = prot.parents lowercase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowercase__ = [p for i, p in zip(A , A ) if i == chain_id] if parents is None or len(A ) == 0: lowercase__ = ['''N/A'''] pdb_headers.append(f"PARENT {' '.join(A )}" ) return pdb_headers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = [] lowercase__ = pdb_str.split('''\n''' ) lowercase__ = prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) lowercase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: lowercase__ = [] if prot.parents_chain_index is not None: lowercase__ = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(A ) , [] ) parent_dict[str(A )].append(A ) lowercase__ = max([int(A ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowercase__ = parent_dict.get(str(A ) , ['''N/A'''] ) parents_per_chain.append(A ) else: parents_per_chain.append(list(prot.parents ) ) else: lowercase__ = [['''N/A''']] def make_parent_line(A ) -> str: return f"PARENT {' '.join(A )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowercase__ = 0 for i, l in enumerate(A ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(A ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(A ): lowercase__ = parents_per_chain[chain_counter] else: lowercase__ = ['''N/A'''] out_pdb_lines.append(make_parent_line(A ) ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = residue_constants.restypes + ['''X'''] def res_atoa(A ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) lowercase__ = residue_constants.atom_types lowercase__ = [] lowercase__ = prot.atom_mask lowercase__ = prot.aatype lowercase__ = prot.atom_positions lowercase__ = prot.residue_index.astype(np.intaa ) lowercase__ = prot.b_factors lowercase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) lowercase__ = get_pdb_headers(A ) if len(A ) > 0: pdb_lines.extend(A ) lowercase__ = aatype.shape[0] lowercase__ = 1 lowercase__ = 0 lowercase__ = string.ascii_uppercase lowercase__ = None # Add all atom sites. for i in range(A ): lowercase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(A , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowercase__ = '''ATOM''' lowercase__ = atom_name if len(A ) == 4 else f" {atom_name}" lowercase__ = '''''' lowercase__ = '''''' lowercase__ = 1.00 lowercase__ = atom_name[0] # Protein supports only C, N, O, S, this works. lowercase__ = '''''' lowercase__ = '''A''' if chain_index is not None: lowercase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowercase__ = ( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(A ) atom_index += 1 lowercase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowercase__ = True lowercase__ = chain_index[i + 1] if should_terminate: # Close the chain. lowercase__ = '''TER''' lowercase__ = ( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(A ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(A , A ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _SCREAMING_SNAKE_CASE (A , A , A = None , A = None , A = None , A = None , A = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=A , remark=A , parents=A , parents_chain_index=A , )
2
1
'''simple docstring''' import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, Pipeline, ZeroShotClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. lowerCamelCase : Dict = {'LayoutLMv2Config', 'LayoutLMv3Config'} @is_pipeline_test class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : str = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowerCAmelCase__ : Dict = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: lowerCAmelCase__ : List[str] = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: lowerCAmelCase__ : Union[str, Any] = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' lowercase__ = ZeroShotClassificationPipeline( model=UpperCamelCase , tokenizer=UpperCamelCase , candidate_labels=['''polics''', '''health'''] ) return classifier, ["Who are you voting for in 2020?", "My stomach hurts."] def UpperCamelCase__ (self : Any , UpperCamelCase : List[Any] , UpperCamelCase : Optional[int] ): '''simple docstring''' lowercase__ = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics''' ) self.assertEqual(UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase )]} ) # No kwarg lowercase__ = classifier('''Who are you voting for in 2020?''' , ['''politics'''] ) self.assertEqual(UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase )]} ) lowercase__ = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics'''] ) self.assertEqual(UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase )]} ) lowercase__ = classifier('''Who are you voting for in 2020?''' , candidate_labels='''politics, public health''' ) self.assertEqual( UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) lowercase__ = classifier('''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health'''] ) self.assertEqual( UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )]} ) self.assertAlmostEqual(sum(nested_simplify(outputs['''scores'''] ) ) , 1.0 ) lowercase__ = classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''This text is about {}''' ) self.assertEqual(UpperCamelCase , {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase )]} ) # https://github.com/huggingface/transformers/issues/13846 lowercase__ = classifier(['''I am happy'''] , ['''positive''', '''negative'''] ) self.assertEqual( UpperCamelCase , [ {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )]} for i in range(1 ) ] , ) lowercase__ = classifier(['''I am happy''', '''I am sad'''] , ['''positive''', '''negative'''] ) self.assertEqual( UpperCamelCase , [ {'''sequence''': ANY(UpperCamelCase ), '''labels''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )], '''scores''': [ANY(UpperCamelCase ), ANY(UpperCamelCase )]} for i in range(2 ) ] , ) with self.assertRaises(UpperCamelCase ): classifier('''''' , candidate_labels='''politics''' ) with self.assertRaises(UpperCamelCase ): classifier(UpperCamelCase , candidate_labels='''politics''' ) with self.assertRaises(UpperCamelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels='''''' ) with self.assertRaises(UpperCamelCase ): classifier('''Who are you voting for in 2020?''' , candidate_labels=UpperCamelCase ) with self.assertRaises(UpperCamelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template='''Not formatting template''' , ) with self.assertRaises(UpperCamelCase ): classifier( '''Who are you voting for in 2020?''' , candidate_labels='''politics''' , hypothesis_template=UpperCamelCase , ) self.run_entailment_id(UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Pipeline ): '''simple docstring''' lowercase__ = zero_shot_classifier.model.config lowercase__ = config.labelaid lowercase__ = zero_shot_classifier.entailment_id lowercase__ = {'''LABEL_0''': 0, '''LABEL_1''': 1, '''LABEL_2''': 2} self.assertEqual(zero_shot_classifier.entailment_id , -1 ) lowercase__ = {'''entailment''': 0, '''neutral''': 1, '''contradiction''': 2} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) lowercase__ = {'''ENTAIL''': 0, '''NON-ENTAIL''': 1} self.assertEqual(zero_shot_classifier.entailment_id , 0 ) lowercase__ = {'''ENTAIL''': 2, '''NEUTRAL''': 1, '''CONTR''': 0} self.assertEqual(zero_shot_classifier.entailment_id , 2 ) lowercase__ = original_labelaid self.assertEqual(UpperCamelCase , zero_shot_classifier.entailment_id ) @require_torch def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) # There was a regression in 4.10 for this # Adding a test so we don't make the mistake again. # https://github.com/huggingface/transformers/issues/13381#issuecomment-912343499 zero_shot_classifier( '''Who are you voting for in 2020?''' * 100 , candidate_labels=['''politics''', '''public health''', '''science'''] ) @require_torch def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''pt''' , ) lowercase__ = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.3_33, 0.3_33, 0.3_33], } , ) @require_tf def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = pipeline( '''zero-shot-classification''' , model='''sshleifer/tiny-distilbert-base-cased-distilled-squad''' , framework='''tf''' , ) lowercase__ = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''science''', '''public health''', '''politics'''], '''scores''': [0.3_33, 0.3_33, 0.3_33], } , ) @slow @require_torch def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''pt''' ) lowercase__ = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.9_76, 0.0_15, 0.0_09], } , ) lowercase__ = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=UpperCamelCase , ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.8_17, 0.7_13, 0.0_18, 0.0_18], } , ) @slow @require_tf def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = pipeline('''zero-shot-classification''' , model='''roberta-large-mnli''' , framework='''tf''' ) lowercase__ = zero_shot_classifier( '''Who are you voting for in 2020?''' , candidate_labels=['''politics''', '''public health''', '''science'''] ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': '''Who are you voting for in 2020?''', '''labels''': ['''politics''', '''public health''', '''science'''], '''scores''': [0.9_76, 0.0_15, 0.0_09], } , ) lowercase__ = zero_shot_classifier( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural networks''' ''' in an encoder-decoder configuration. The best performing models also connect the encoder and decoder''' ''' through an attention mechanism. We propose a new simple network architecture, the Transformer, based''' ''' solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two''' ''' machine translation tasks show these models to be superior in quality while being more parallelizable''' ''' and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014''' ''' English-to-German translation task, improving over the existing best results, including ensembles by''' ''' over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new''' ''' single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small''' ''' fraction of the training costs of the best models from the literature. We show that the Transformer''' ''' generalizes well to other tasks by applying it successfully to English constituency parsing both with''' ''' large and limited training data.''' , candidate_labels=['''machine learning''', '''statistics''', '''translation''', '''vision'''] , multi_label=UpperCamelCase , ) self.assertEqual( nested_simplify(UpperCamelCase ) , { '''sequence''': ( '''The dominant sequence transduction models are based on complex recurrent or convolutional neural''' ''' networks in an encoder-decoder configuration. The best performing models also connect the''' ''' encoder and decoder through an attention mechanism. We propose a new simple network''' ''' architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence''' ''' and convolutions entirely. Experiments on two machine translation tasks show these models to be''' ''' superior in quality while being more parallelizable and requiring significantly less time to''' ''' train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task,''' ''' improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014''' ''' English-to-French translation task, our model establishes a new single-model state-of-the-art''' ''' BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training''' ''' costs of the best models from the literature. We show that the Transformer generalizes well to''' ''' other tasks by applying it successfully to English constituency parsing both with large and''' ''' limited training data.''' ), '''labels''': ['''translation''', '''machine learning''', '''vision''', '''statistics'''], '''scores''': [0.8_17, 0.7_13, 0.0_18, 0.0_18], } , )
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> None: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(A , total_number - level + 2 ): current_list.append(A ) create_all_state(i + 1 , A , level - 1 , A , A ) current_list.pop() def _SCREAMING_SNAKE_CASE (A ) -> None: """simple docstring""" for i in total_list: print(*A ) if __name__ == "__main__": lowerCamelCase : Tuple = 4 lowerCamelCase : Union[str, Any] = 2 lowerCamelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
2
1
'''simple docstring''' import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights lowercase__ = FlaxDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase , cache_dir=UpperCamelCase ) lowercase__ = [t[-1] for t in os.walk(os.path.join(UpperCamelCase , os.listdir(UpperCamelCase )[0] , '''snapshots''' ) )] lowercase__ = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('''.bin''' ) for f in files ) @slow @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-pipe''' , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 4 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_51_47_45 ) < 1E-3 assert np.abs(np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 4_99_47.8_75 ) < 5E-1 lowercase__ = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(UpperCamelCase ) == num_samples def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''flax''' , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_65_24_01) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_38_38_08.2) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa ) lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule='''scaled_linear''' , set_alpha_to_one=UpperCamelCase , steps_offset=1 , ) lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , scheduler=UpperCamelCase , safety_checker=UpperCamelCase , ) lowercase__ = scheduler.create_state() lowercase__ = scheduler_state lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.random.PRNGKey(0 ) lowercase__ = 50 lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) # shard inputs and rng lowercase__ = replicate(UpperCamelCase ) lowercase__ = jax.random.split(UpperCamelCase , UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_45_04_39_45) ) < 1E-3 assert np.abs((np.abs(UpperCamelCase , dtype=np.floataa ).sum() - 2_34_76_93.5) ) < 5E-1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ( '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of''' ''' field, close up, split lighting, cinematic''' ) lowercase__ = jax.device_count() lowercase__ = num_samples * [prompt] lowercase__ = jax.random.split(jax.random.PRNGKey(0 ) , UpperCamelCase ) lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase , ) lowercase__ = replicate(UpperCamelCase ) lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) lowercase__ = images[2, 0, 256, 10:17, 1] # With memory efficient attention lowercase__ ,lowercase__ = FlaxStableDiffusionPipeline.from_pretrained( '''CompVis/stable-diffusion-v1-4''' , revision='''bf16''' , dtype=jnp.bfloataa , safety_checker=UpperCamelCase , use_memory_efficient_attention=UpperCamelCase , ) lowercase__ = replicate(UpperCamelCase ) lowercase__ = pipeline.prepare_inputs(UpperCamelCase ) lowercase__ = shard(UpperCamelCase ) lowercase__ = pipeline(UpperCamelCase , UpperCamelCase , UpperCamelCase , jit=UpperCamelCase ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) lowercase__ = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
2
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCamelCase : Optional[Any] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) lowerCamelCase : Tuple = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) lowerCamelCase : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) lowerCamelCase : Any = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) lowerCamelCase : Tuple = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) lowerCamelCase : Optional[int] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) lowerCamelCase : Dict = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ = randrange(len(A ) ), randrange(len(A ) ) lowercase__ = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] lowercase__ ,lowercase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE (A = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(A )) @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" assert PokerHand(A )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = PokerHand(A ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" assert PokerHand(A )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = [PokerHand(A ) for hand in SORTED_HANDS] lowercase__ = poker_hands.copy() shuffle(A ) lowercase__ = chain(sorted(A ) ) for index, hand in enumerate(A ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=A ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE () -> int: """simple docstring""" lowercase__ = PokerHand('''2C 4S AS 3D 5C''' ) lowercase__ = True lowercase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = 0 lowercase__ = os.path.abspath(os.path.dirname(A ) ) lowercase__ = os.path.join(A , '''poker_hands.txt''' ) with open(A ) as file_hand: for line in file_hand: lowercase__ = line[:14].strip() lowercase__ = line[15:].strip() lowercase__ ,lowercase__ = PokerHand(A ), PokerHand(A ) lowercase__ = player.compare_with(A ) if output == "Win": answer += 1 assert answer == 376
2
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: lowerCamelCase : List[str] = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : List[str] = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : Tuple = { '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' ), }, 'tokenizer_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json' ), }, } lowerCamelCase : Optional[int] = { 'moussaKam/mbarthez': 1_024, 'moussaKam/barthez': 1_024, 'moussaKam/barthez-orangesum-title': 1_024, } lowerCamelCase : Tuple = '▁' class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = VOCAB_FILES_NAMES lowerCAmelCase__ : int = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = BarthezTokenizer def __init__(self : Any , UpperCamelCase : str=None , UpperCamelCase : Any=None , UpperCamelCase : int="<s>" , UpperCamelCase : Optional[int]="</s>" , UpperCamelCase : Tuple="</s>" , UpperCamelCase : int="<s>" , UpperCamelCase : Tuple="<unk>" , UpperCamelCase : Optional[Any]="<pad>" , UpperCamelCase : Dict="<mask>" , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else mask_token super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , sep_token=UpperCamelCase , cls_token=UpperCamelCase , pad_token=UpperCamelCase , mask_token=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True def UpperCamelCase__ (self : str , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowercase__ = [self.cls_token_id] lowercase__ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [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 : Union[str, Any] , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) return (out_vocab_file,)
2
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase : str = parser.parse_args() if args.model_type == "bert": lowerCamelCase : List[Any] = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase : Any = 'bert' else: raise ValueError('args.model_type should be "bert".') lowerCamelCase : int = model.state_dict() lowerCamelCase : int = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] lowerCamelCase : Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] lowerCamelCase : List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] lowerCamelCase : Tuple = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] lowerCamelCase : Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] lowerCamelCase : Optional[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] lowerCamelCase : Any = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 lowerCamelCase : Optional[int] = state_dict['cls.predictions.decoder.weight'] lowerCamelCase : str = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase : str = state_dict[f"""cls.predictions.transform.dense.{w}"""] lowerCamelCase : Any = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
2
1
'''simple docstring''' import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __lowerCAmelCase : '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Any=3 , UpperCamelCase : str=32 , UpperCamelCase : Tuple=3 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : int=[8, 16, 32, 64] , UpperCamelCase : Dict=[1, 1, 2, 1] , UpperCamelCase : int=True , UpperCamelCase : List[Any]=True , UpperCamelCase : Optional[int]="relu" , UpperCamelCase : Optional[Any]=3 , UpperCamelCase : Tuple=None , UpperCamelCase : Optional[int]=["stage2", "stage3", "stage4"] , UpperCamelCase : Optional[int]=[2, 3, 4] , UpperCamelCase : Tuple=1 , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = image_size lowercase__ = num_channels lowercase__ = embeddings_size lowercase__ = hidden_sizes lowercase__ = depths lowercase__ = is_training lowercase__ = use_labels lowercase__ = hidden_act lowercase__ = num_labels lowercase__ = scope lowercase__ = len(UpperCamelCase ) lowercase__ = out_features lowercase__ = out_indices lowercase__ = num_groups def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.num_labels ) lowercase__ = self.get_config() return config, pixel_values, labels def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Optional[Any] , UpperCamelCase : List[Any] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = BitModel(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase ) 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 : Union[str, Any] , UpperCamelCase : Optional[int] , UpperCamelCase : str , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = self.num_labels lowercase__ = BitForImageClassification(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ (self : Any , UpperCamelCase : List[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = BitBackbone(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None lowercase__ = None lowercase__ = BitBackbone(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[Any] = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowerCAmelCase__ : Union[str, Any] = ( {"""feature-extraction""": BitModel, """image-classification""": BitForImageClassification} if is_torch_available() else {} ) lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : str = False lowerCAmelCase__ : Tuple = False lowerCAmelCase__ : int = False lowerCAmelCase__ : str = False def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = BitModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase , has_text_modality=UpperCamelCase ) def UpperCamelCase__ (self : str ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase__ (self : Tuple ): '''simple docstring''' return @unittest.skip(reason='''Bit does not output attentions''' ) def UpperCamelCase__ (self : Any ): '''simple docstring''' pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def UpperCamelCase__ (self : Any ): '''simple docstring''' pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' pass def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(UpperCamelCase ) 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] , UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase ) def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ = model_class(config=UpperCamelCase ) for name, module in model.named_modules(): if isinstance(UpperCamelCase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f"Parameter {name} of model {model_class} seems not properly initialized" , ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' def check_hidden_states_output(UpperCamelCase : List[str] , UpperCamelCase : Optional[int] , UpperCamelCase : List[str] ): lowercase__ = model_class(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() with torch.no_grad(): lowercase__ = model(**self._prepare_for_class(UpperCamelCase , UpperCamelCase ) ) lowercase__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowercase__ = self.model_tester.num_stages self.assertEqual(len(UpperCamelCase ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: lowercase__ = layer_type lowercase__ = True check_hidden_states_output(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ = True check_hidden_states_output(UpperCamelCase , UpperCamelCase , UpperCamelCase ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' pass def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCamelCase ) @slow def UpperCamelCase__ (self : Any ): '''simple docstring''' for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ = BitModel.from_pretrained(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) def _SCREAMING_SNAKE_CASE () -> List[str]: """simple docstring""" lowercase__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase__ (self : int ): '''simple docstring''' return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(UpperCamelCase ) lowercase__ = self.default_image_processor lowercase__ = prepare_img() lowercase__ = image_processor(images=UpperCamelCase , return_tensors='''pt''' ).to(UpperCamelCase ) # forward pass with torch.no_grad(): lowercase__ = model(**UpperCamelCase ) # verify the logits lowercase__ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , UpperCamelCase ) lowercase__ = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]] ).to(UpperCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase , atol=1E-4 ) ) @require_torch class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = (BitBackbone,) if is_torch_available() else () lowerCAmelCase__ : Optional[int] = BitConfig lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = BitModelTester(self )
2
'''simple docstring''' from ....utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : int=2048 ): '''simple docstring''' lowercase__ = config.__dict__ lowercase__ = modal_hidden_size if num_labels: lowercase__ = num_labels
2
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = self.dummy_uncond_unet lowercase__ = ScoreSdeVeScheduler() lowercase__ = ScoreSdeVePipeline(unet=UpperCamelCase , scheduler=UpperCamelCase ) sde_ve.to(UpperCamelCase ) sde_ve.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.manual_seed(0 ) lowercase__ = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=UpperCamelCase ).images lowercase__ = torch.manual_seed(0 ) lowercase__ = sde_ve(num_inference_steps=2 , output_type='''numpy''' , generator=UpperCamelCase , return_dict=UpperCamelCase )[ 0 ] lowercase__ = image[0, -3:, -3:, -1] lowercase__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowercase__ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = '''google/ncsnpp-church-256''' lowercase__ = UNetaDModel.from_pretrained(UpperCamelCase ) lowercase__ = ScoreSdeVeScheduler.from_pretrained(UpperCamelCase ) lowercase__ = ScoreSdeVePipeline(unet=UpperCamelCase , scheduler=UpperCamelCase ) sde_ve.to(UpperCamelCase ) sde_ve.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.manual_seed(0 ) lowercase__ = sde_ve(num_inference_steps=10 , output_type='''numpy''' , generator=UpperCamelCase ).images lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowercase__ = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """cvt""" def __init__(self : int , UpperCamelCase : List[Any]=3 , UpperCamelCase : int=[7, 3, 3] , UpperCamelCase : str=[4, 2, 2] , UpperCamelCase : Dict=[2, 1, 1] , UpperCamelCase : Dict=[64, 192, 384] , UpperCamelCase : Dict=[1, 3, 6] , UpperCamelCase : Dict=[1, 2, 10] , UpperCamelCase : Any=[4.0, 4.0, 4.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : int=[0.0, 0.0, 0.1] , UpperCamelCase : Any=[True, True, True] , UpperCamelCase : int=[False, False, True] , UpperCamelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase : Optional[int]=[3, 3, 3] , UpperCamelCase : Tuple=[1, 1, 1] , UpperCamelCase : Any=[2, 2, 2] , UpperCamelCase : Dict=[1, 1, 1] , UpperCamelCase : List[str]=[1, 1, 1] , UpperCamelCase : str=0.02 , UpperCamelCase : int=1E-12 , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> float: """simple docstring""" lowercase__ = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('''All input parameters must be positive''' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('''Relative densities cannot be greater than one''' ) else: lowercase__ = 1 - (matter_density + radiation_density + dark_energy) lowercase__ = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) lowercase__ = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCamelCase : int = 0.3 print( hubble_parameter( hubble_constant=6_8.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
2
'''simple docstring''' import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCamelCase : Any = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCamelCase : Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCamelCase : Any = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) lowerCamelCase : List[Any] = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) lowerCamelCase : List[str] = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions lowerCamelCase : List[str] = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(64, 64) ) lowerCamelCase : Optional[int] = tf.keras.preprocessing.image.img_to_array(test_image) lowerCamelCase : str = np.expand_dims(test_image, axis=0) lowerCamelCase : List[str] = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCamelCase : Any = 'Normal' if result[0][0] == 1: lowerCamelCase : Any = 'Abnormality detected'
2
1
'''simple docstring''' import math class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : List[Any]=0 ): # a graph with Node 0,1,...,N-1 '''simple docstring''' lowercase__ = n lowercase__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # adjacency matrix for weight lowercase__ = [ [math.inf for j in range(0 , UpperCamelCase )] for i in range(0 , UpperCamelCase ) ] # dp[i][j] stores minimum distance from i to j def UpperCamelCase__ (self : Any , UpperCamelCase : int , UpperCamelCase : Optional[int] , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = w def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): lowercase__ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCamelCase__ (self : Any , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' return self.dp[u][v] if __name__ == "__main__": lowerCamelCase : Any = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) 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)
2
'''simple docstring''' class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__(self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = row lowercase__ = col lowercase__ = graph def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowercase__ = [-1, 0, 1, -1, 1, -1, 0, 1] lowercase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): # And finally, count all islands. '''simple docstring''' lowercase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] lowercase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += 1 return count
2
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : int = { 'bigscience/bloom': 'https://huggingface.co/bigscience/bloom/resolve/main/config.json', 'bigscience/bloom-560m': 'https://huggingface.co/bigscience/bloom-560m/blob/main/config.json', 'bigscience/bloom-1b1': 'https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json', 'bigscience/bloom-1b7': 'https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json', 'bigscience/bloom-3b': 'https://huggingface.co/bigscience/bloom-3b/blob/main/config.json', 'bigscience/bloom-7b1': 'https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Any = """bloom""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : Optional[int] = { """num_hidden_layers""": """n_layer""", """num_attention_heads""": """n_head""", } def __init__(self : Dict , UpperCamelCase : int=250880 , UpperCamelCase : Any=64 , UpperCamelCase : List[Any]=2 , UpperCamelCase : Any=8 , UpperCamelCase : Any=1E-5 , UpperCamelCase : Any=0.02 , UpperCamelCase : str=True , UpperCamelCase : Optional[int]=1 , UpperCamelCase : Optional[int]=2 , UpperCamelCase : Union[str, Any]=False , UpperCamelCase : List[str]=0.0 , UpperCamelCase : Any=0.0 , UpperCamelCase : Optional[Any]=1 , UpperCamelCase : List[Any]=False , **UpperCamelCase : Tuple , ): '''simple docstring''' lowercase__ = vocab_size # Backward compatibility with n_embed kwarg lowercase__ = kwargs.pop('''n_embed''' , UpperCamelCase ) lowercase__ = hidden_size if n_embed is None else n_embed lowercase__ = n_layer lowercase__ = n_head lowercase__ = layer_norm_epsilon lowercase__ = initializer_range lowercase__ = use_cache lowercase__ = pretraining_tp lowercase__ = apply_residual_connection_post_layernorm lowercase__ = hidden_dropout lowercase__ = attention_dropout lowercase__ = bos_token_id lowercase__ = eos_token_id lowercase__ = slow_but_exact super().__init__(bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = version.parse("""1.12""" ) def __init__(self : Optional[Any] , UpperCamelCase : PretrainedConfig , UpperCamelCase : str = "default" , UpperCamelCase : List[PatchingSpec] = None , UpperCamelCase : bool = False , ): '''simple docstring''' super().__init__(UpperCamelCase , task=UpperCamelCase , patching_specs=UpperCamelCase , use_past=UpperCamelCase ) if not getattr(self._config , '''pad_token_id''' , UpperCamelCase ): # TODO: how to do that better? lowercase__ = 0 @property def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(UpperCamelCase , direction='''inputs''' , inverted_values_shape=UpperCamelCase ) lowercase__ = {0: '''batch''', 1: '''past_sequence + sequence'''} else: lowercase__ = {0: '''batch''', 1: '''sequence'''} return common_inputs @property def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' return self._config.n_layer @property def UpperCamelCase__ (self : int ): '''simple docstring''' return self._config.n_head @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 1E-3 def UpperCamelCase__ (self : str , UpperCamelCase : "PreTrainedTokenizer" , UpperCamelCase : int = -1 , UpperCamelCase : int = -1 , UpperCamelCase : bool = False , UpperCamelCase : Optional["TensorType"] = None , ): '''simple docstring''' lowercase__ = super(UpperCamelCase , self ).generate_dummy_inputs( UpperCamelCase , batch_size=UpperCamelCase , seq_length=UpperCamelCase , is_pair=UpperCamelCase , framework=UpperCamelCase ) # We need to order the input in the way they appears in the forward() lowercase__ = OrderedDict({'''input_ids''': common_inputs['''input_ids''']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.''' ) else: import torch lowercase__ ,lowercase__ = common_inputs['''input_ids'''].shape # Not using the same length for past_key_values lowercase__ = seqlen + 2 lowercase__ = self._config.hidden_size // self.num_attention_heads lowercase__ = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) lowercase__ = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) lowercase__ = [ (torch.zeros(UpperCamelCase ), torch.zeros(UpperCamelCase )) for _ in range(self.num_layers ) ] lowercase__ = common_inputs['''attention_mask'''] if self.use_past: lowercase__ = ordered_inputs['''attention_mask'''].dtype lowercase__ = torch.cat( [ordered_inputs['''attention_mask'''], torch.ones(UpperCamelCase , UpperCamelCase , dtype=UpperCamelCase )] , dim=1 ) return ordered_inputs @property def UpperCamelCase__ (self : Any ): '''simple docstring''' return 13
2
'''simple docstring''' import unittest from transformers import DonutProcessor lowerCamelCase : Tuple = 'naver-clova-ix/donut-base' class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = DonutProcessor.from_pretrained(UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowercase__ = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowercase__ = self.processor.tokenajson(UpperCamelCase ) self.assertDictEqual(UpperCamelCase , UpperCamelCase )
2
1
'''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 _SCREAMING_SNAKE_CASE (A , A=0.999 , A="cosine" , ) -> Optional[Any]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(A ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(A ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) lowercase__ = [] for i in range(A ): lowercase__ = i / num_diffusion_timesteps lowercase__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(A ) / alpha_bar_fn(A ) , A ) ) return torch.tensor(A , dtype=torch.floataa ) class __lowerCAmelCase (lowercase_ , lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Dict = [e.name for e in KarrasDiffusionSchedulers] lowerCAmelCase__ : Optional[int] = 2 @register_to_config def __init__(self : int , UpperCamelCase : int = 1000 , UpperCamelCase : float = 0.0_00_85 , UpperCamelCase : float = 0.0_12 , UpperCamelCase : str = "linear" , UpperCamelCase : Optional[Union[np.ndarray, List[float]]] = None , UpperCamelCase : str = "epsilon" , UpperCamelCase : str = "linspace" , UpperCamelCase : int = 0 , ): '''simple docstring''' if trained_betas is not None: lowercase__ = torch.tensor(UpperCamelCase , dtype=torch.floataa ) elif beta_schedule == "linear": lowercase__ = torch.linspace(UpperCamelCase , UpperCamelCase , UpperCamelCase , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. lowercase__ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , UpperCamelCase , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule lowercase__ = betas_for_alpha_bar(UpperCamelCase ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) lowercase__ = 1.0 - self.betas lowercase__ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Any , UpperCamelCase : Optional[int] , UpperCamelCase : int=None ): '''simple docstring''' if schedule_timesteps is None: lowercase__ = self.timesteps lowercase__ = (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: lowercase__ = 1 if len(UpperCamelCase ) > 1 else 0 else: lowercase__ = timestep.cpu().item() if torch.is_tensor(UpperCamelCase ) else timestep lowercase__ = self._index_counter[timestep_int] return indices[pos].item() @property def UpperCamelCase__ (self : List[str] ): '''simple docstring''' if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def UpperCamelCase__ (self : str , UpperCamelCase : torch.FloatTensor , UpperCamelCase : Union[float, torch.FloatTensor] , ): '''simple docstring''' lowercase__ = self.index_for_timestep(UpperCamelCase ) if self.state_in_first_order: lowercase__ = self.sigmas[step_index] else: lowercase__ = self.sigmas_interpol[step_index] lowercase__ = sample / ((sigma**2 + 1) ** 0.5) return sample def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : int , UpperCamelCase : Union[str, torch.device] = None , UpperCamelCase : Optional[int] = None , ): '''simple docstring''' lowercase__ = num_inference_steps lowercase__ = 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": lowercase__ = np.linspace(0 , num_train_timesteps - 1 , UpperCamelCase , dtype=UpperCamelCase )[::-1].copy() elif self.config.timestep_spacing == "leading": lowercase__ = 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 lowercase__ = (np.arange(0 , UpperCamelCase ) * step_ratio).round()[::-1].copy().astype(UpperCamelCase ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": lowercase__ = 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 lowercase__ = (np.arange(UpperCamelCase , 0 , -step_ratio )).round().copy().astype(UpperCamelCase ) timesteps -= 1 else: raise ValueError( f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." ) lowercase__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) lowercase__ = torch.from_numpy(np.log(UpperCamelCase ) ).to(UpperCamelCase ) lowercase__ = np.interp(UpperCamelCase , np.arange(0 , len(UpperCamelCase ) ) , UpperCamelCase ) lowercase__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) lowercase__ = torch.from_numpy(UpperCamelCase ).to(device=UpperCamelCase ) # interpolate sigmas lowercase__ = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() lowercase__ = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) lowercase__ = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(UpperCamelCase ).startswith('''mps''' ): # mps does not support float64 lowercase__ = torch.from_numpy(UpperCamelCase ).to(UpperCamelCase , dtype=torch.floataa ) else: lowercase__ = torch.from_numpy(UpperCamelCase ).to(UpperCamelCase ) # interpolate timesteps lowercase__ = self.sigma_to_t(UpperCamelCase ).to(UpperCamelCase , dtype=timesteps.dtype ) lowercase__ = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() lowercase__ = torch.cat([timesteps[:1], interleaved_timesteps] ) lowercase__ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter lowercase__ = defaultdict(UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = sigma.log() # get distribution lowercase__ = log_sigma - self.log_sigmas[:, None] # get sigmas range lowercase__ = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) lowercase__ = low_idx + 1 lowercase__ = self.log_sigmas[low_idx] lowercase__ = self.log_sigmas[high_idx] # interpolate sigmas lowercase__ = (low - log_sigma) / (low - high) lowercase__ = w.clamp(0 , 1 ) # transform interpolation to time range lowercase__ = (1 - w) * low_idx + w * high_idx lowercase__ = t.view(sigma.shape ) return t @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return self.sample is None def UpperCamelCase__ (self : str , UpperCamelCase : Union[torch.FloatTensor, np.ndarray] , UpperCamelCase : Union[float, torch.FloatTensor] , UpperCamelCase : Union[torch.FloatTensor, np.ndarray] , UpperCamelCase : bool = True , ): '''simple docstring''' lowercase__ = self.index_for_timestep(UpperCamelCase ) # advance index counter by 1 lowercase__ = timestep.cpu().item() if torch.is_tensor(UpperCamelCase ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: lowercase__ = self.sigmas[step_index] lowercase__ = self.sigmas_interpol[step_index + 1] lowercase__ = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method lowercase__ = self.sigmas[step_index - 1] lowercase__ = self.sigmas_interpol[step_index] lowercase__ = 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 lowercase__ = 0 lowercase__ = 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": lowercase__ = sigma_hat if self.state_in_first_order else sigma_interpol lowercase__ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": lowercase__ = sigma_hat if self.state_in_first_order else sigma_interpol lowercase__ = 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 lowercase__ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep lowercase__ = sigma_interpol - sigma_hat # store for 2nd order step lowercase__ = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order lowercase__ = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep lowercase__ = sigma_next - sigma_hat lowercase__ = self.sample lowercase__ = None lowercase__ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : torch.FloatTensor , UpperCamelCase : torch.FloatTensor , UpperCamelCase : torch.FloatTensor , ): '''simple docstring''' lowercase__ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(UpperCamelCase ): # mps does not support float64 lowercase__ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) lowercase__ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: lowercase__ = self.timesteps.to(original_samples.device ) lowercase__ = timesteps.to(original_samples.device ) lowercase__ = [self.index_for_timestep(UpperCamelCase , UpperCamelCase ) for t in timesteps] lowercase__ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): lowercase__ = sigma.unsqueeze(-1 ) lowercase__ = original_samples + noise * sigma return noisy_samples def __len__(self : List[Any] ): '''simple docstring''' return self.config.num_train_timesteps
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return len(set(A ) ) == len(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
'''simple docstring''' import math from typing import Any, Callable, List, Optional, Tuple, Union import numpy as np import torch from ...models import TaFilmDecoder from ...schedulers import DDPMScheduler from ...utils import is_onnx_available, logging, randn_tensor if is_onnx_available(): from ..onnx_utils import OnnxRuntimeModel from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline from .continous_encoder import SpectrogramContEncoder from .notes_encoder import SpectrogramNotesEncoder lowerCamelCase : Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase : Dict = 256 class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[Any] = ["""melgan"""] def __init__(self : Tuple , UpperCamelCase : SpectrogramNotesEncoder , UpperCamelCase : SpectrogramContEncoder , UpperCamelCase : TaFilmDecoder , UpperCamelCase : DDPMScheduler , UpperCamelCase : OnnxRuntimeModel if is_onnx_available() else Any , ): '''simple docstring''' super().__init__() # From MELGAN lowercase__ = math.log(1E-5 ) # Matches MelGAN training. lowercase__ = 4.0 # Largest value for most examples lowercase__ = 128 self.register_modules( notes_encoder=UpperCamelCase , continuous_encoder=UpperCamelCase , decoder=UpperCamelCase , scheduler=UpperCamelCase , melgan=UpperCamelCase , ) def UpperCamelCase__ (self : str , UpperCamelCase : Dict , UpperCamelCase : Tuple=(-1.0, 1.0) , UpperCamelCase : int=False ): '''simple docstring''' lowercase__ ,lowercase__ = output_range if clip: lowercase__ = torch.clip(UpperCamelCase , self.min_value , self.max_value ) # Scale to [0, 1]. lowercase__ = (features - self.min_value) / (self.max_value - self.min_value) # Scale to [min_out, max_out]. return zero_one * (max_out - min_out) + min_out def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any]=(-1.0, 1.0) , UpperCamelCase : Dict=False ): '''simple docstring''' lowercase__ ,lowercase__ = input_range lowercase__ = torch.clip(UpperCamelCase , UpperCamelCase , UpperCamelCase ) if clip else outputs # Scale to [0, 1]. lowercase__ = (outputs - min_out) / (max_out - min_out) # Scale to [self.min_value, self.max_value]. return zero_one * (self.max_value - self.min_value) + self.min_value def UpperCamelCase__ (self : Dict , UpperCamelCase : List[Any] , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = input_tokens > 0 lowercase__ ,lowercase__ = self.notes_encoder( encoder_input_tokens=UpperCamelCase , encoder_inputs_mask=UpperCamelCase ) lowercase__ ,lowercase__ = self.continuous_encoder( encoder_inputs=UpperCamelCase , encoder_inputs_mask=UpperCamelCase ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def UpperCamelCase__ (self : Dict , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Any ): '''simple docstring''' lowercase__ = noise_time if not torch.is_tensor(UpperCamelCase ): lowercase__ = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(UpperCamelCase ) and len(timesteps.shape ) == 0: lowercase__ = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML lowercase__ = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) lowercase__ = self.decoder( encodings_and_masks=UpperCamelCase , decoder_input_tokens=UpperCamelCase , decoder_noise_time=UpperCamelCase ) return logits @torch.no_grad() def __call__(self : List[Any] , UpperCamelCase : List[List[int]] , UpperCamelCase : Optional[torch.Generator] = None , UpperCamelCase : int = 100 , UpperCamelCase : bool = True , UpperCamelCase : str = "numpy" , UpperCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , UpperCamelCase : int = 1 , ): '''simple docstring''' if (callback_steps is None) or ( callback_steps is not None and (not isinstance(UpperCamelCase , UpperCamelCase ) or callback_steps <= 0) ): raise ValueError( f"`callback_steps` has to be a positive integer but is {callback_steps} of type" f" {type(UpperCamelCase )}." ) lowercase__ = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) lowercase__ = np.zeros([1, 0, self.n_dims] , np.floataa ) lowercase__ = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase , device=self.device ) for i, encoder_input_tokens in enumerate(UpperCamelCase ): if i == 0: lowercase__ = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. lowercase__ = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=UpperCamelCase , device=self.device ) else: # The full song pipeline does not feed in a context feature, so the mask # will be all 0s after the feature converter. Because we know we're # feeding in a full context chunk from the previous prediction, set it # to all 1s. lowercase__ = ones lowercase__ = self.scale_features( UpperCamelCase , output_range=[-1.0, 1.0] , clip=UpperCamelCase ) lowercase__ = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=UpperCamelCase , continuous_mask=UpperCamelCase , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop lowercase__ = randn_tensor( shape=encoder_continuous_inputs.shape , generator=UpperCamelCase , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(UpperCamelCase ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): lowercase__ = self.decode( encodings_and_masks=UpperCamelCase , input_tokens=UpperCamelCase , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 lowercase__ = self.scheduler.step(UpperCamelCase , UpperCamelCase , UpperCamelCase , generator=UpperCamelCase ).prev_sample lowercase__ = self.scale_to_features(UpperCamelCase , input_range=[-1.0, 1.0] ) lowercase__ = mel[:1] lowercase__ = mel.cpu().float().numpy() lowercase__ = np.concatenate([full_pred_mel, pred_mel[:1]] , axis=1 ) # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(UpperCamelCase , UpperCamelCase ) logger.info('''Generated segment''' , UpperCamelCase ) if output_type == "numpy" and not is_onnx_available(): raise ValueError( '''Cannot return output in \'np\' format if ONNX is not available. Make sure to have ONNX installed or set \'output_type\' to \'mel\'.''' ) elif output_type == "numpy" and self.melgan is None: raise ValueError( '''Cannot return output in \'np\' format if melgan component is not defined. Make sure to define `self.melgan` or set \'output_type\' to \'mel\'.''' ) if output_type == "numpy": lowercase__ = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: lowercase__ = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=UpperCamelCase )
2
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: lowerCamelCase : Any = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : List[str] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 lowerCamelCase : Any = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : str = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = TaTokenizer lowerCAmelCase__ : List[int] = [] def __init__(self : Dict , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any="</s>" , UpperCamelCase : str="<unk>" , UpperCamelCase : List[str]="<pad>" , UpperCamelCase : List[str]=100 , UpperCamelCase : Tuple=None , **UpperCamelCase : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase__ = [f"<extra_id_{i}>" for i in range(UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase__ = len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) ) , UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , extra_ids=UpperCamelCase , additional_special_tokens=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True lowercase__ = extra_ids @staticmethod def UpperCamelCase__ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f" {pretrained_model_name_or_path} automatically truncating your input to" f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase , ) return max_model_length def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) logger.info(f"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>''' , UpperCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> Optional[int]: # noqa: E741 """simple docstring""" lowercase__ = len(A ) lowercase__ = 0 lowercase__ = [0] * n lowercase__ = [False] * n lowercase__ = [False] * n def dfs(A , A , A , A ): if parent == root: out_edge_count += 1 lowercase__ = True lowercase__ = at for to in l[at]: if to == parent: pass elif not visited[to]: lowercase__ = dfs(A , A , A , A ) lowercase__ = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: lowercase__ = True # AP found via cycle if at == low[to]: lowercase__ = True else: lowercase__ = min(low[at] , A ) return out_edge_count for i in range(A ): if not visited[i]: lowercase__ = 0 lowercase__ = dfs(A , A , -1 , A ) lowercase__ = out_edge_count > 1 for x in range(len(A ) ): if is_art[x] is True: print(A ) # Adjacency list of graph lowerCamelCase : int = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
2
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = ShapEImgaImgPipeline lowerCAmelCase__ : List[str] = ["""image"""] lowerCAmelCase__ : Any = ["""image"""] lowerCAmelCase__ : Any = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] lowerCAmelCase__ : Tuple = False @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : str ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase__ (self : int ): '''simple docstring''' return 8 @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(UpperCamelCase ) return model @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase , do_normalize=UpperCamelCase , do_resize=UpperCamelCase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def UpperCamelCase__ (self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase__ = PriorTransformer(**UpperCamelCase ) return model @property def UpperCamelCase__ (self : int ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**UpperCamelCase ) return model def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase , clip_sample=UpperCamelCase , clip_sample_range=1.0 , ) lowercase__ = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : str=0 ): '''simple docstring''' lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) if str(UpperCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(UpperCamelCase ) else: lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowercase__ = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = '''cpu''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = pipe(**self.get_dummy_inputs(UpperCamelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = torch_device == '''cpu''' lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase , relax_max_difference=UpperCamelCase , ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(UpperCamelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**UpperCamelCase , num_images_per_prompt=UpperCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase__ = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(0 ) lowercase__ = pipe( UpperCamelCase , generator=UpperCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
'''simple docstring''' class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__(self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = row lowercase__ = col lowercase__ = graph def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowercase__ = [-1, 0, 1, -1, 1, -1, 0, 1] lowercase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): # And finally, count all islands. '''simple docstring''' lowercase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] lowercase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += 1 return count
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
1
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = '''ZinengTang/tvlt-base''' lowercase__ = tempfile.mkdtemp() def UpperCamelCase__ (self : int , **UpperCamelCase : List[str] ): '''simple docstring''' return TvltImageProcessor.from_pretrained(self.checkpoint , **UpperCamelCase ) def UpperCamelCase__ (self : int , **UpperCamelCase : str ): '''simple docstring''' return TvltFeatureExtractor.from_pretrained(self.checkpoint , **UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.get_image_processor() lowercase__ = self.get_feature_extractor() lowercase__ = TvltProcessor(image_processor=UpperCamelCase , feature_extractor=UpperCamelCase ) processor.save_pretrained(self.tmpdirname ) lowercase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , UpperCamelCase ) self.assertIsInstance(processor.image_processor , UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.get_image_processor() lowercase__ = self.get_feature_extractor() lowercase__ = TvltProcessor(image_processor=UpperCamelCase , feature_extractor=UpperCamelCase ) lowercase__ = np.ones([12000] ) lowercase__ = feature_extractor(UpperCamelCase , return_tensors='''np''' ) lowercase__ = processor(audio=UpperCamelCase , return_tensors='''np''' ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.get_image_processor() lowercase__ = self.get_feature_extractor() lowercase__ = TvltProcessor(image_processor=UpperCamelCase , feature_extractor=UpperCamelCase ) lowercase__ = np.ones([3, 224, 224] ) lowercase__ = image_processor(UpperCamelCase , return_tensors='''np''' ) lowercase__ = processor(images=UpperCamelCase , return_tensors='''np''' ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = self.get_image_processor() lowercase__ = self.get_feature_extractor() lowercase__ = TvltProcessor(image_processor=UpperCamelCase , feature_extractor=UpperCamelCase ) lowercase__ = np.ones([12000] ) lowercase__ = np.ones([3, 224, 224] ) lowercase__ = processor(audio=UpperCamelCase , images=UpperCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''audio_values''', '''audio_mask''', '''pixel_values''', '''pixel_mask'''] ) # test if it raises when no input is passed with pytest.raises(UpperCamelCase ): processor() def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = self.get_image_processor() lowercase__ = self.get_feature_extractor() lowercase__ = TvltProcessor(image_processor=UpperCamelCase , feature_extractor=UpperCamelCase ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg='''`processor` and `image_processor`+`feature_extractor` model input names do not match''' , )
2
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Union[str, Any] = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Tuple = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
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''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowerCamelCase : Union[str, Any] = 'platform' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def _SCREAMING_SNAKE_CASE (A , A , A=None , A=None , A=None , A=None , A=None , A=None , ) -> Union[str, Any]: """simple docstring""" if attention_mask is None: lowercase__ = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: lowercase__ = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: lowercase__ = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowercase__ = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowercase__ = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class __lowerCAmelCase : '''simple docstring''' def __init__(self : List[str] , UpperCamelCase : Optional[int] , UpperCamelCase : Any=13 , UpperCamelCase : Optional[int]=7 , UpperCamelCase : Dict=True , UpperCamelCase : Tuple=False , UpperCamelCase : Union[str, Any]=99 , UpperCamelCase : List[Any]=16 , UpperCamelCase : List[Any]=2 , UpperCamelCase : List[str]=4 , UpperCamelCase : Tuple=4 , UpperCamelCase : Dict="gelu" , UpperCamelCase : Tuple=0.1 , UpperCamelCase : List[Any]=0.1 , UpperCamelCase : Any=32 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=1 , UpperCamelCase : List[Any]=0 , UpperCamelCase : List[str]=0.02 , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_labels 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__ = eos_token_id lowercase__ = pad_token_id lowercase__ = bos_token_id lowercase__ = initializer_range def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) lowercase__ = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) lowercase__ = shift_tokens_right(UpperCamelCase , 1 , 2 ) lowercase__ = BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=UpperCamelCase , ) lowercase__ = prepare_blenderbot_inputs_dict(UpperCamelCase , UpperCamelCase , UpperCamelCase ) return config, inputs_dict def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ ,lowercase__ = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ (self : Any , UpperCamelCase : Any , UpperCamelCase : List[str] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = 20 lowercase__ = model_class_name(UpperCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] ) lowercase__ ,lowercase__ = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase__ = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase , UpperCamelCase ) lowercase__ = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowercase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) lowercase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCamelCase , ) lowercase__ = model.decode(UpperCamelCase , UpperCamelCase ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) def UpperCamelCase__ (self : str , UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple ): '''simple docstring''' lowercase__ = 20 lowercase__ = model_class_name(UpperCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] ) lowercase__ ,lowercase__ = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowercase__ = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowercase__ = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase , UpperCamelCase ) lowercase__ = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowercase__ = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase , decoder_attention_mask=UpperCamelCase , past_key_values=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) lowercase__ = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowercase__ = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCamelCase , decoder_position_ids=UpperCamelCase , ) lowercase__ = model.decode(UpperCamelCase , UpperCamelCase , decoder_attention_mask=UpperCamelCase ) lowercase__ = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1E-3 , msg=f"Max diff is {diff}" ) @require_flax class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[Any] = 99 def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) lowercase__ = input_ids.shape[0] lowercase__ = BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ ,lowercase__ ,lowercase__ = self._get_config_and_data() lowercase__ = FlaxBlenderbotForConditionalGeneration(UpperCamelCase ) lowercase__ = lm_model(input_ids=UpperCamelCase ) lowercase__ = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) lowercase__ = FlaxBlenderbotForConditionalGeneration(UpperCamelCase ) lowercase__ = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) lowercase__ = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) lowercase__ = lm_model(input_ids=UpperCamelCase , decoder_input_ids=UpperCamelCase ) lowercase__ = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase ) def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) lowercase__ = shift_tokens_right(UpperCamelCase , 1 , 2 ) lowercase__ = np.equal(UpperCamelCase , 1 ).astype(np.floataa ).sum() lowercase__ = np.equal(UpperCamelCase , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(UpperCamelCase , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class __lowerCAmelCase (lowercase_ , unittest.TestCase , lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = True lowerCAmelCase__ : str = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) lowerCAmelCase__ : List[Any] = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = FlaxBlenderbotModelTester(self ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(UpperCamelCase , UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ = self._prepare_for_class(UpperCamelCase , UpperCamelCase ) lowercase__ = model_class(UpperCamelCase ) @jax.jit def encode_jitted(UpperCamelCase : List[str] , UpperCamelCase : List[str]=None , **UpperCamelCase : Optional[Any] ): return model.encode(input_ids=UpperCamelCase , attention_mask=UpperCamelCase ) with self.subTest('''JIT Enabled''' ): lowercase__ = encode_jitted(**UpperCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase__ = encode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase , UpperCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ ,lowercase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowercase__ = model_class(UpperCamelCase ) lowercase__ = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) lowercase__ = { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(UpperCamelCase : Tuple , UpperCamelCase : Dict , UpperCamelCase : Dict ): return model.decode( decoder_input_ids=UpperCamelCase , decoder_attention_mask=UpperCamelCase , encoder_outputs=UpperCamelCase , ) with self.subTest('''JIT Enabled''' ): lowercase__ = decode_jitted(**UpperCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowercase__ = decode_jitted(**UpperCamelCase ).to_tuple() self.assertEqual(len(UpperCamelCase ) , len(UpperCamelCase ) ) for jitted_output, output in zip(UpperCamelCase , UpperCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase__ (self : str ): '''simple docstring''' for model_class_name in self.all_model_classes: lowercase__ = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids lowercase__ = np.ones((1, 1) ) * model.config.eos_token_id lowercase__ = model(UpperCamelCase ) self.assertIsNotNone(UpperCamelCase ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} lowercase__ = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} lowercase__ = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=UpperCamelCase ) lowercase__ = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) lowercase__ = ['''Sam'''] lowercase__ = tokenizer(UpperCamelCase , return_tensors='''jax''' ) lowercase__ = model.generate(**UpperCamelCase , **UpperCamelCase ) lowercase__ = '''Sam is a great name. It means "sun" in Gaelic.''' lowercase__ = tokenizer.batch_decode(UpperCamelCase , **UpperCamelCase ) assert generated_txt[0].strip() == tgt_text
2
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A , A , A ) -> int: """simple docstring""" lowercase__ = [False] * len(A ) lowercase__ = [] queue.append(A ) lowercase__ = True while queue: lowercase__ = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(A ) lowercase__ = True lowercase__ = u return visited[t] def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[int]: """simple docstring""" lowercase__ = [-1] * (len(A )) lowercase__ = 0 while bfs(A , A , A , A ): lowercase__ = float('''Inf''' ) lowercase__ = sink while s != source: # Find the minimum value in select path lowercase__ = min(A , graph[parent[s]][s] ) lowercase__ = parent[s] max_flow += path_flow lowercase__ = sink while v != source: lowercase__ = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow lowercase__ = parent[v] return max_flow lowerCamelCase : Any = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] lowerCamelCase , lowerCamelCase : Tuple = 0, 5 print(ford_fulkerson(graph, source, sink))
2
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Any = """philschmid/bart-large-cnn-samsum""" lowerCAmelCase__ : Union[str, Any] = ( """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.""" ) lowerCAmelCase__ : Tuple = """summarizer""" lowerCAmelCase__ : Optional[Any] = AutoTokenizer lowerCAmelCase__ : Dict = AutoModelForSeqaSeqLM lowerCAmelCase__ : Dict = ["""text"""] lowerCAmelCase__ : str = ["""text"""] def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[Any] ): '''simple docstring''' return self.pre_processor(UpperCamelCase , return_tensors='''pt''' , truncation=UpperCamelCase ) def UpperCamelCase__ (self : Dict , UpperCamelCase : Optional[Any] ): '''simple docstring''' return self.model.generate(**UpperCamelCase )[0] def UpperCamelCase__ (self : Tuple , UpperCamelCase : int ): '''simple docstring''' return self.pre_processor.decode(UpperCamelCase , skip_special_tokens=UpperCamelCase , clean_up_tokenization_spaces=UpperCamelCase )
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """megatron-bert""" def __init__(self : Tuple , UpperCamelCase : Optional[int]=29056 , UpperCamelCase : Optional[Any]=1024 , UpperCamelCase : Any=24 , UpperCamelCase : int=16 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : int="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any=512 , UpperCamelCase : int=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Optional[int]="absolute" , UpperCamelCase : List[Any]=True , **UpperCamelCase : str , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache
2
1
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = CTRLTokenizer lowerCAmelCase__ : str = False lowerCAmelCase__ : List[Any] = False def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowercase__ = ['''adapt''', '''re@@''', '''a@@''', '''apt''', '''c@@''', '''t''', '''<unk>'''] lowercase__ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) lowercase__ = ['''#version: 0.2''', '''a p''', '''ap t</w>''', '''r e''', '''a d''', '''ad apt</w>''', ''''''] lowercase__ = {'''unk_token''': '''<unk>'''} lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(UpperCamelCase ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(UpperCamelCase ) ) def UpperCamelCase__ (self : int , **UpperCamelCase : List[Any] ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = '''adapt react readapt apt''' lowercase__ = '''adapt react readapt apt''' return input_text, output_text def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowercase__ = '''adapt react readapt apt''' lowercase__ = '''adapt re@@ a@@ c@@ t re@@ adapt apt'''.split() lowercase__ = tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokens + [tokenizer.unk_token] lowercase__ = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , UpperCamelCase )
2
'''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
1
'''simple docstring''' lowerCamelCase : Union[str, Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n' lowerCamelCase : Any = [{'type': 'code', 'content': INSTALL_CONTENT}] lowerCamelCase : Dict = { '{processor_class}': 'FakeProcessorClass', '{model_class}': 'FakeModelClass', '{object_class}': 'FakeObjectClass', }
2
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
1
'''simple docstring''' import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _SCREAMING_SNAKE_CASE (A , A , A , A ) -> Union[str, Any]: """simple docstring""" if isinstance(A , A ): lowercase__ = np.full((len(A ), sequence_length, 2) , A ) else: lowercase__ = np.full((len(A ), sequence_length) , A ) for i, tensor in enumerate(A ): if padding_side == "right": if isinstance(A , A ): lowercase__ = tensor[:sequence_length] else: lowercase__ = tensor[:sequence_length] else: if isinstance(A , A ): lowercase__ = tensor[:sequence_length] else: lowercase__ = tensor[:sequence_length] return out_tensor.tolist() def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = ord(A ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True lowercase__ = unicodedata.category(A ) if cat.startswith('''P''' ): return True return False @dataclass class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : PreTrainedTokenizerBase lowerCAmelCase__ : Union[bool, str, PaddingStrategy] = True lowerCAmelCase__ : Optional[int] = None lowerCAmelCase__ : Optional[int] = None lowerCAmelCase__ : int = -100 lowerCAmelCase__ : str = "pt" def UpperCamelCase__ (self : Dict , UpperCamelCase : int ): '''simple docstring''' import torch lowercase__ = '''label''' if '''label''' in features[0].keys() else '''labels''' lowercase__ = [feature[label_name] for feature in features] if label_name in features[0].keys() else None lowercase__ = self.tokenizer.pad( UpperCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='''pt''' if labels is None else None , ) if labels is None: return batch lowercase__ = torch.tensor(batch['''entity_ids'''] ).shape[1] lowercase__ = self.tokenizer.padding_side if padding_side == "right": lowercase__ = [ list(UpperCamelCase ) + [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase )) for label in labels ] else: lowercase__ = [ [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase )) + list(UpperCamelCase ) for label in labels ] lowercase__ = [feature['''ner_tags'''] for feature in features] lowercase__ = padding_tensor(UpperCamelCase , -1 , UpperCamelCase , UpperCamelCase ) lowercase__ = [feature['''original_entity_spans'''] for feature in features] lowercase__ = padding_tensor(UpperCamelCase , (-1, -1) , UpperCamelCase , UpperCamelCase ) lowercase__ = {k: torch.tensor(UpperCamelCase , dtype=torch.intaa ) for k, v in batch.items()} return batch
2
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
1
'''simple docstring''' import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _SCREAMING_SNAKE_CASE (A = 8 ) -> str: """simple docstring""" lowercase__ = ascii_letters + digits + punctuation return "".join(secrets.choice(A ) for _ in range(A ) ) def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" i -= len(A ) lowercase__ = i // 3 lowercase__ = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) lowercase__ = ( chars_incl + random(A , quotient + remainder ) + random(A , A ) + random(A , A ) ) lowercase__ = list(A ) shuffle(A ) return "".join(A ) # random is a generalised function for letters, characters and numbers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" return "".join(secrets.choice(A ) for _ in range(A ) ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[Any]: """simple docstring""" pass # Put your code here... def _SCREAMING_SNAKE_CASE (A , A ) -> Dict: """simple docstring""" pass # Put your code here... def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" pass # Put your code here... def _SCREAMING_SNAKE_CASE (A , A = 8 ) -> bool: """simple docstring""" if len(A ) < min_length: # Your Password must be at least 8 characters long return False lowercase__ = any(char in ascii_uppercase for char in password ) lowercase__ = any(char in ascii_lowercase for char in password ) lowercase__ = any(char in digits for char in password ) lowercase__ = 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 _SCREAMING_SNAKE_CASE () -> Any: """simple docstring""" lowercase__ = int(input('''Please indicate the max length of your password: ''' ).strip() ) lowercase__ = input( '''Please indicate the characters that must be in your password: ''' ).strip() print('''Password generated:''' , password_generator(A ) ) print( '''Alternative Password generated:''' , alternative_password_generator(A , A ) , ) print('''[If you are thinking of using this passsword, You better save it.]''' ) if __name__ == "__main__": main()
2
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : str = Mapping[str, np.ndarray] lowerCamelCase : List[Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Any = 0.0_1 @dataclasses.dataclass(frozen=lowercase_ ) class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ : Optional[str] = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ : Optional[Sequence[str]] = None # Chain corresponding to each parent lowerCAmelCase__ : Optional[Sequence[int]] = None def _SCREAMING_SNAKE_CASE (A ) -> Protein: """simple docstring""" lowercase__ = R'''(\[[A-Z]+\]\n)''' lowercase__ = [tag.strip() for tag in re.split(A , A ) if len(A ) > 0] lowercase__ = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) lowercase__ = ["N", "CA", "C"] lowercase__ = None lowercase__ = None lowercase__ = None for g in groups: if "[PRIMARY]" == g[0]: lowercase__ = g[1][0].strip() for i in range(len(A ) ): if seq[i] not in residue_constants.restypes: lowercase__ = '''X''' # FIXME: strings are immutable lowercase__ = np.array( [residue_constants.restype_order.get(A , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowercase__ = [] for axis in range(3 ): tertiary.append(list(map(A , g[1][axis].split() ) ) ) lowercase__ = np.array(A ) lowercase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowercase__ = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) lowercase__ = np.zeros( ( len(A ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=A , atom_mask=A , aatype=A , residue_index=np.arange(len(A ) ) , b_factors=A , ) def _SCREAMING_SNAKE_CASE (A , A = 0 ) -> List[str]: """simple docstring""" lowercase__ = [] lowercase__ = prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) lowercase__ = prot.parents lowercase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowercase__ = [p for i, p in zip(A , A ) if i == chain_id] if parents is None or len(A ) == 0: lowercase__ = ['''N/A'''] pdb_headers.append(f"PARENT {' '.join(A )}" ) return pdb_headers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = [] lowercase__ = pdb_str.split('''\n''' ) lowercase__ = prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) lowercase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: lowercase__ = [] if prot.parents_chain_index is not None: lowercase__ = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(A ) , [] ) parent_dict[str(A )].append(A ) lowercase__ = max([int(A ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowercase__ = parent_dict.get(str(A ) , ['''N/A'''] ) parents_per_chain.append(A ) else: parents_per_chain.append(list(prot.parents ) ) else: lowercase__ = [['''N/A''']] def make_parent_line(A ) -> str: return f"PARENT {' '.join(A )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowercase__ = 0 for i, l in enumerate(A ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(A ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(A ): lowercase__ = parents_per_chain[chain_counter] else: lowercase__ = ['''N/A'''] out_pdb_lines.append(make_parent_line(A ) ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = residue_constants.restypes + ['''X'''] def res_atoa(A ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) lowercase__ = residue_constants.atom_types lowercase__ = [] lowercase__ = prot.atom_mask lowercase__ = prot.aatype lowercase__ = prot.atom_positions lowercase__ = prot.residue_index.astype(np.intaa ) lowercase__ = prot.b_factors lowercase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) lowercase__ = get_pdb_headers(A ) if len(A ) > 0: pdb_lines.extend(A ) lowercase__ = aatype.shape[0] lowercase__ = 1 lowercase__ = 0 lowercase__ = string.ascii_uppercase lowercase__ = None # Add all atom sites. for i in range(A ): lowercase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(A , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowercase__ = '''ATOM''' lowercase__ = atom_name if len(A ) == 4 else f" {atom_name}" lowercase__ = '''''' lowercase__ = '''''' lowercase__ = 1.00 lowercase__ = atom_name[0] # Protein supports only C, N, O, S, this works. lowercase__ = '''''' lowercase__ = '''A''' if chain_index is not None: lowercase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowercase__ = ( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(A ) atom_index += 1 lowercase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowercase__ = True lowercase__ = chain_index[i + 1] if should_terminate: # Close the chain. lowercase__ = '''TER''' lowercase__ = ( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(A ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(A , A ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _SCREAMING_SNAKE_CASE (A , A , A = None , A = None , A = None , A = None , A = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=A , remark=A , parents=A , parents_chain_index=A , )
2
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase : str = logging.get_logger(__name__) def _SCREAMING_SNAKE_CASE (A , A=False ) -> Optional[Any]: """simple docstring""" lowercase__ = [] # fmt: off # stem: rename_keys.append(('''cls_token''', '''vit.embeddings.cls_token''') ) rename_keys.append(('''pos_embed''', '''vit.embeddings.position_embeddings''') ) rename_keys.append(('''patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias''') ) # backbone rename_keys.append(('''patch_embed.backbone.stem.conv.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.weight''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight''') ) rename_keys.append(('''patch_embed.backbone.stem.norm.bias''', '''vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias''') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight") ) rename_keys.append((f"patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias", f"vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"blocks.{i}.norm1.weight", f"vit.encoder.layer.{i}.layernorm_before.weight") ) rename_keys.append((f"blocks.{i}.norm1.bias", f"vit.encoder.layer.{i}.layernorm_before.bias") ) rename_keys.append((f"blocks.{i}.attn.proj.weight", f"vit.encoder.layer.{i}.attention.output.dense.weight") ) rename_keys.append((f"blocks.{i}.attn.proj.bias", f"vit.encoder.layer.{i}.attention.output.dense.bias") ) rename_keys.append((f"blocks.{i}.norm2.weight", f"vit.encoder.layer.{i}.layernorm_after.weight") ) rename_keys.append((f"blocks.{i}.norm2.bias", f"vit.encoder.layer.{i}.layernorm_after.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"vit.encoder.layer.{i}.intermediate.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"vit.encoder.layer.{i}.intermediate.dense.bias") ) rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"vit.encoder.layer.{i}.output.dense.weight") ) rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"vit.encoder.layer.{i}.output.dense.bias") ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" lowercase__ = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) # fmt: on return rename_keys def _SCREAMING_SNAKE_CASE (A , A , A=False ) -> Tuple: """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: lowercase__ = '''''' else: lowercase__ = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) lowercase__ = state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) lowercase__ = state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict lowercase__ = in_proj_weight[ : config.hidden_size, : ] lowercase__ = in_proj_bias[: config.hidden_size] lowercase__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] lowercase__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] lowercase__ = in_proj_weight[ -config.hidden_size :, : ] lowercase__ = in_proj_bias[-config.hidden_size :] def _SCREAMING_SNAKE_CASE (A ) -> List[Any]: """simple docstring""" lowercase__ = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" lowercase__ = dct.pop(A ) lowercase__ = val def _SCREAMING_SNAKE_CASE () -> Optional[Any]: """simple docstring""" lowercase__ = '''http://images.cocodataset.org/val2017/000000039769.jpg''' lowercase__ = Image.open(requests.get(A , stream=A ).raw ) return im @torch.no_grad() def _SCREAMING_SNAKE_CASE (A , A , A=False ) -> Dict: """simple docstring""" lowercase__ = BitConfig( global_padding='''same''' , layer_type='''bottleneck''' , depths=(3, 4, 9) , out_features=['''stage3'''] , embedding_dynamic_padding=A , ) lowercase__ = ViTHybridConfig(backbone_config=A , image_size=384 , num_labels=1_000 ) lowercase__ = False # load original model from timm lowercase__ = timm.create_model(A , pretrained=A ) timm_model.eval() # load state_dict of original model, remove and rename some keys lowercase__ = timm_model.state_dict() if base_model: remove_classification_head_(A ) lowercase__ = create_rename_keys(A , A ) for src, dest in rename_keys: rename_key(A , A , A ) read_in_q_k_v(A , A , A ) lowercase__ = '''huggingface/label-files''' lowercase__ = '''imagenet-1k-id2label.json''' lowercase__ = json.load(open(hf_hub_download(A , A , repo_type='''dataset''' ) , '''r''' ) ) lowercase__ = {int(A ): v for k, v in idalabel.items()} lowercase__ = idalabel lowercase__ = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": lowercase__ = ViTHybridModel(A ).eval() else: lowercase__ = ViTHybridForImageClassification(A ).eval() model.load_state_dict(A ) # create image processor lowercase__ = create_transform(**resolve_data_config({} , model=A ) ) lowercase__ = transform.transforms lowercase__ = { '''bilinear''': PILImageResampling.BILINEAR, '''bicubic''': PILImageResampling.BICUBIC, '''nearest''': PILImageResampling.NEAREST, } lowercase__ = ViTHybridImageProcessor( do_resize=A , size={'''shortest_edge''': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=A , crop_size={'''height''': timm_transforms[1].size[0], '''width''': timm_transforms[1].size[1]} , do_normalize=A , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowercase__ = prepare_img() lowercase__ = transform(A ).unsqueeze(0 ) lowercase__ = processor(A , return_tensors='''pt''' ).pixel_values # verify pixel values assert torch.allclose(A , A ) # verify logits with torch.no_grad(): lowercase__ = model(A ) lowercase__ = outputs.logits print('''Predicted class:''' , logits.argmax(-1 ).item() ) if base_model: lowercase__ = timm_model.forward_features(A ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(A , outputs.pooler_output , atol=1E-3 ) else: lowercase__ = timm_model(A ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(A , outputs.logits , atol=1E-3 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: Path(A ).mkdir(exist_ok=A ) print(f"Saving model {vit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(A ) print(f"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(A ) if push_to_hub: print(f"Pushing model and processor to the hub {vit_name}" ) model.push_to_hub(f"ybelkada/{vit_name}" ) processor.push_to_hub(f"ybelkada/{vit_name}" ) if __name__ == "__main__": lowerCamelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) lowerCamelCase : Optional[Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> None: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(A , total_number - level + 2 ): current_list.append(A ) create_all_state(i + 1 , A , level - 1 , A , A ) current_list.pop() def _SCREAMING_SNAKE_CASE (A ) -> None: """simple docstring""" for i in total_list: print(*A ) if __name__ == "__main__": lowerCamelCase : Tuple = 4 lowerCamelCase : Union[str, Any] = 2 lowerCamelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
2
1
'''simple docstring''' import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : str = LayoutLMTokenizer lowerCAmelCase__ : Optional[int] = LayoutLMTokenizerFast lowerCAmelCase__ : Optional[int] = True lowerCAmelCase__ : int = True def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().setUp() lowercase__ = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def UpperCamelCase__ (self : List[Any] , **UpperCamelCase : List[Any] ): '''simple docstring''' return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = '''UNwant\u00E9d,running''' lowercase__ = '''unwanted, running''' return input_text, output_text def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = self.tokenizer_class(self.vocab_file ) lowercase__ = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(UpperCamelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , [7, 4, 5, 10, 8, 9] ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' pass
2
'''simple docstring''' import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCamelCase : Optional[Any] = ( '4S 3H 2C 7S 5H', '9D 8H 2C 6S 7H', '2D 6D 9D TH 7D', 'TC 8C 2S JH 6C', 'JH 8S TH AH QH', 'TS KS 5S 9S AC', 'KD 6S 9D TH AD', 'KS 8D 4D 9S 4S', # pair '8C 4S KH JS 4D', # pair 'QH 8H KD JH 8S', # pair 'KC 4H KS 2H 8D', # pair 'KD 4S KC 3H 8S', # pair 'AH 8S AS KC JH', # pair '3H 4C 4H 3S 2H', # 2 pairs '5S 5D 2C KH KH', # 2 pairs '3C KH 5D 5S KH', # 2 pairs 'AS 3C KH AD KH', # 2 pairs '7C 7S 3S 7H 5S', # 3 of a kind '7C 7S KH 2H 7H', # 3 of a kind 'AC KH QH AH AS', # 3 of a kind '2H 4D 3C AS 5S', # straight (low ace) '3C 5C 4C 2C 6H', # straight '6S 8S 7S 5H 9H', # straight 'JS QS 9H TS KH', # straight 'QC KH TS JS AH', # straight (high ace) '8C 9C 5C 3C TC', # flush '3S 8S 9S 5S KS', # flush '4C 5C 9C 8C KC', # flush 'JH 8H AH KH QH', # flush '3D 2H 3H 2C 2D', # full house '2H 2C 3S 3H 3D', # full house 'KH KC 3S 3H 3D', # full house 'JC 6H JS JD JH', # 4 of a kind 'JC 7H JS JD JH', # 4 of a kind 'JC KH JS JD JH', # 4 of a kind '2S AS 4S 5S 3S', # straight flush (low ace) '2D 6D 3D 4D 5D', # straight flush '5C 6C 3C 7C 4C', # straight flush 'JH 9H TH KH QH', # straight flush 'JH AH TH KH QH', # royal flush (high ace straight flush) ) lowerCamelCase : Tuple = ( ('2H 3H 4H 5H 6H', 'KS AS TS QS JS', 'Loss'), ('2H 3H 4H 5H 6H', 'AS AD AC AH JD', 'Win'), ('AS AH 2H AD AC', 'JS JD JC JH 3D', 'Win'), ('2S AH 2H AS AC', 'JS JD JC JH AD', 'Loss'), ('2S AH 2H AS AC', '2H 3H 5H 6H 7H', 'Win'), ('AS 3S 4S 8S 2S', '2H 3H 5H 6H 7H', 'Win'), ('2H 3H 5H 6H 7H', '2S 3H 4H 5S 6C', 'Win'), ('2S 3H 4H 5S 6C', '3D 4C 5H 6H 2S', 'Tie'), ('2S 3H 4H 5S 6C', 'AH AC 5H 6H AS', 'Win'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H AS', 'Loss'), ('2S 2H 4H 5S 4C', 'AH AC 5H 6H 7S', 'Win'), ('6S AD 7H 4S AS', 'AH AC 5H 6H 7S', 'Loss'), ('2S AH 4H 5S KC', 'AH AC 5H 6H 7S', 'Loss'), ('2S 3H 6H 7S 9C', '7H 3C TH 6H 9S', 'Loss'), ('4S 5H 6H TS AC', '3S 5H 6H TS AC', 'Win'), ('2S AH 4H 5S 6C', 'AD 4C 5H 6H 2C', 'Tie'), ('AS AH 3H AD AC', 'AS AH 2H AD AC', 'Win'), ('AH AC 5H 5C QS', 'AH AC 5H 5C KS', 'Loss'), ('AH AC 5H 5C QS', 'KH KC 5H 5C QS', 'Win'), ('7C 7S KH 2H 7H', '3C 3S AH 2H 3H', 'Win'), ('3C 3S AH 2H 3H', '7C 7S KH 2H 7H', 'Loss'), ('6H 5H 4H 3H 2H', '5H 4H 3H 2H AH', 'Win'), ('5H 4H 3H 2H AH', '5H 4H 3H 2H AH', 'Tie'), ('5H 4H 3H 2H AH', '6H 5H 4H 3H 2H', 'Loss'), ('AH AD KS KC AC', 'AH KD KH AC KC', 'Win'), ('2H 4D 3C AS 5S', '2H 4D 3C 6S 5S', 'Loss'), ('2H 3S 3C 3H 2S', '3S 3C 2S 2H 2D', 'Win'), ('4D 6D 5D 2D JH', '3S 8S 3H TC KH', 'Loss'), ('4S 6C 8S 3S 7S', 'AD KS 2D 7D 7C', 'Loss'), ('6S 4C 7H 8C 3H', '5H JC AH 9D 9C', 'Loss'), ('9D 9H JH TC QH', '3C 2S JS 5C 7H', 'Win'), ('2H TC 8S AD 9S', '4H TS 7H 2C 5C', 'Win'), ('9D 3S 2C 7S 7C', 'JC TD 3C TC 9H', 'Loss'), ) lowerCamelCase : Dict = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', True), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', False), ('AS 3S 4S 8S 2S', True), ) lowerCamelCase : Any = ( ('2H 3H 4H 5H 6H', True), ('AS AH 2H AD AC', False), ('2H 3H 5H 6H 7H', False), ('KS AS TS QS JS', True), ('8H 9H QS JS TH', True), ) lowerCamelCase : Tuple = ( ('2H 4D 3C AS 5S', True, [5, 4, 3, 2, 14]), ('2H 5D 3C AS 5S', False, [14, 5, 5, 3, 2]), ('JH QD KC AS TS', False, [14, 13, 12, 11, 10]), ('9D 3S 2C 7S 7C', False, [9, 7, 7, 3, 2]), ) lowerCamelCase : Optional[int] = ( ('JH AH TH KH QH', 0), ('JH 9H TH KH QH', 0), ('JC KH JS JD JH', 7), ('KH KC 3S 3H 3D', 6), ('8C 9C 5C 3C TC', 0), ('JS QS 9H TS KH', 0), ('7C 7S KH 2H 7H', 3), ('3C KH 5D 5S KH', 2), ('QH 8H KD JH 8S', 1), ('2D 6D 9D TH 7D', 0), ) lowerCamelCase : Dict = ( ('JH AH TH KH QH', 23), ('JH 9H TH KH QH', 22), ('JC KH JS JD JH', 21), ('KH KC 3S 3H 3D', 20), ('8C 9C 5C 3C TC', 19), ('JS QS 9H TS KH', 18), ('7C 7S KH 2H 7H', 17), ('3C KH 5D 5S KH', 16), ('QH 8H KD JH 8S', 15), ('2D 6D 9D TH 7D', 14), ) def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ ,lowercase__ = randrange(len(A ) ), randrange(len(A ) ) lowercase__ = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] lowercase__ ,lowercase__ = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _SCREAMING_SNAKE_CASE (A = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(A )) @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" assert PokerHand(A )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Any: """simple docstring""" lowercase__ = PokerHand(A ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Tuple: """simple docstring""" assert PokerHand(A )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , A ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> Optional[Any]: """simple docstring""" assert PokerHand(A ).compare_with(PokerHand(A ) ) == expected def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" lowercase__ = [PokerHand(A ) for hand in SORTED_HANDS] lowercase__ = poker_hands.copy() shuffle(A ) lowercase__ = chain(sorted(A ) ) for index, hand in enumerate(A ): assert hand == poker_hands[index] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=A ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def _SCREAMING_SNAKE_CASE () -> int: """simple docstring""" lowercase__ = PokerHand('''2C 4S AS 3D 5C''' ) lowercase__ = True lowercase__ = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = 0 lowercase__ = os.path.abspath(os.path.dirname(A ) ) lowercase__ = os.path.join(A , '''poker_hands.txt''' ) with open(A ) as file_hand: for line in file_hand: lowercase__ = line[:14].strip() lowercase__ = line[15:].strip() lowercase__ ,lowercase__ = PokerHand(A ), PokerHand(A ) lowercase__ = player.compare_with(A ) if output == "Win": answer += 1 assert answer == 376
2
1
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": lowerCamelCase : List[str] = argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') lowerCamelCase : str = parser.parse_args() if args.model_type == "bert": lowerCamelCase : List[Any] = BertForMaskedLM.from_pretrained(args.model_name) lowerCamelCase : Any = 'bert' else: raise ValueError('args.model_type should be "bert".') lowerCamelCase : int = model.state_dict() lowerCamelCase : int = {} for w in ["word_embeddings", "position_embeddings"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: lowerCamelCase : Any = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] lowerCamelCase : Tuple = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] lowerCamelCase : List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] lowerCamelCase : Tuple = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] lowerCamelCase : Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] lowerCamelCase : Optional[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] lowerCamelCase : Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] lowerCamelCase : Any = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 lowerCamelCase : Optional[int] = state_dict['cls.predictions.decoder.weight'] lowerCamelCase : str = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: lowerCamelCase : str = state_dict[f"""cls.predictions.transform.dense.{w}"""] lowerCamelCase : Any = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
2
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A , A ) -> list[list[int]]: """simple docstring""" lowercase__ = [] create_all_state(1 , A , A , [] , A ) return result def _SCREAMING_SNAKE_CASE (A , A , A , A , A , ) -> None: """simple docstring""" if level == 0: total_list.append(current_list[:] ) return for i in range(A , total_number - level + 2 ): current_list.append(A ) create_all_state(i + 1 , A , level - 1 , A , A ) current_list.pop() def _SCREAMING_SNAKE_CASE (A ) -> None: """simple docstring""" for i in total_list: print(*A ) if __name__ == "__main__": lowerCamelCase : Tuple = 4 lowerCamelCase : Union[str, Any] = 2 lowerCamelCase : Dict = generate_all_combinations(n, k) print_all_state(total_list)
2
'''simple docstring''' from ....utils import logging lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[int] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any]=None , UpperCamelCase : int=2048 ): '''simple docstring''' lowercase__ = config.__dict__ lowercase__ = modal_hidden_size if num_labels: lowercase__ = num_labels
2
1
'''simple docstring''' import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class __lowerCAmelCase : '''simple docstring''' def __init__(self : int , UpperCamelCase : Optional[int] , UpperCamelCase : Any=13 , UpperCamelCase : List[Any]=7 , UpperCamelCase : Optional[int]=True , UpperCamelCase : List[str]=True , UpperCamelCase : List[Any]=True , UpperCamelCase : Optional[Any]=True , UpperCamelCase : Union[str, Any]=99 , UpperCamelCase : List[str]=64 , UpperCamelCase : List[str]=32 , UpperCamelCase : Optional[int]=5 , UpperCamelCase : Any=4 , UpperCamelCase : Union[str, Any]=37 , UpperCamelCase : Dict="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : List[Any]=0.1 , UpperCamelCase : List[Any]=512 , UpperCamelCase : Union[str, Any]=16 , UpperCamelCase : int=2 , UpperCamelCase : Tuple=0.02 , UpperCamelCase : Optional[int]=3 , UpperCamelCase : Optional[Any]=4 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_input_mask lowercase__ = use_token_type_ids lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = embedding_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__ = type_vocab_size lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = num_labels lowercase__ = num_choices lowercase__ = scope def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = None if self.use_input_mask: lowercase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ = None if self.use_token_type_ids: lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase__ = None lowercase__ = None lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase__ = ids_tensor([self.batch_size] , self.num_choices ) lowercase__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ (self : Dict ): '''simple docstring''' return MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase , initializer_range=self.initializer_range , ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : Any , UpperCamelCase : Optional[int] , UpperCamelCase : List[str] , UpperCamelCase : int , UpperCamelCase : Dict , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' lowercase__ = MobileBertModel(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase ) lowercase__ = model(UpperCamelCase , token_type_ids=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCamelCase__ (self : str , UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : str , UpperCamelCase : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : List[str] , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = MobileBertForMaskedLM(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : str , UpperCamelCase : Any , UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = MobileBertForNextSentencePrediction(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model( UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : List[str] , UpperCamelCase : List[str] , UpperCamelCase : Any , UpperCamelCase : Any , UpperCamelCase : Union[str, Any] , UpperCamelCase : Union[str, Any] ): '''simple docstring''' lowercase__ = MobileBertForPreTraining(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model( UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase , next_sentence_label=UpperCamelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCamelCase__ (self : str , UpperCamelCase : List[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : Tuple , UpperCamelCase : Optional[int] , UpperCamelCase : Tuple , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' lowercase__ = MobileBertForQuestionAnswering(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model( UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , start_positions=UpperCamelCase , end_positions=UpperCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Dict , UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Dict , UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : Any ): '''simple docstring''' lowercase__ = self.num_labels lowercase__ = MobileBertForSequenceClassification(UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[str] , UpperCamelCase : Optional[Any] , UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : Dict , UpperCamelCase : Tuple , UpperCamelCase : List[str] ): '''simple docstring''' lowercase__ = self.num_labels lowercase__ = MobileBertForTokenClassification(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : Union[str, Any] , UpperCamelCase : int , UpperCamelCase : List[str] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Any , UpperCamelCase : Any , UpperCamelCase : Dict ): '''simple docstring''' lowercase__ = self.num_choices lowercase__ = MobileBertForMultipleChoice(config=UpperCamelCase ) model.to(UpperCamelCase ) model.eval() lowercase__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowercase__ = model( UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() ( ( lowercase__ ) ,( lowercase__ ) ,( lowercase__ ) ,( lowercase__ ) ,( lowercase__ ) ,( lowercase__ ) ,( lowercase__ ) , ) = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Tuple = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) lowerCAmelCase__ : Tuple = ( { """feature-extraction""": MobileBertModel, """fill-mask""": MobileBertForMaskedLM, """question-answering""": MobileBertForQuestionAnswering, """text-classification""": MobileBertForSequenceClassification, """token-classification""": MobileBertForTokenClassification, """zero-shot""": MobileBertForSequenceClassification, } if is_torch_available() else {} ) lowerCAmelCase__ : str = True def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[str] , UpperCamelCase : Any , UpperCamelCase : Any=False ): '''simple docstring''' lowercase__ = super()._prepare_for_class(UpperCamelCase , UpperCamelCase , return_labels=UpperCamelCase ) if return_labels: if model_class in get_values(UpperCamelCase ): lowercase__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase ) lowercase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase ) return inputs_dict def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = MobileBertModelTester(self ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase , hidden_size=37 ) def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCamelCase ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCamelCase ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCamelCase ) def _SCREAMING_SNAKE_CASE (A ) -> Optional[int]: """simple docstring""" return torch.tensor( A , dtype=torch.long , device=A , ) lowerCamelCase : str = 1e-3 @require_torch @require_sentencepiece @require_tokenizers class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = MobileBertModel.from_pretrained('''google/mobilebert-uncased''' ).to(UpperCamelCase ) lowercase__ = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): lowercase__ = model(UpperCamelCase )[0] lowercase__ = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , UpperCamelCase ) lowercase__ = torch.tensor( [ [ [-2.4_73_65_26E07, 8.2_69_16_56E04, 1.6_52_18_38E05], [-5.7_54_17_04E-01, 3.9_05_60_22E00, 4.4_01_15_07E00], [2.6_04_73_59E00, 1.5_67_76_52E00, -1.7_32_41_88E-01], ] ] , device=UpperCamelCase , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE lowercase__ = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) lowercase__ = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Tuple = logging.get_logger(__name__) lowerCamelCase : Dict = { 'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json', # See all Cvt models at https://huggingface.co/models?filter=cvt } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Tuple = """cvt""" def __init__(self : int , UpperCamelCase : List[Any]=3 , UpperCamelCase : int=[7, 3, 3] , UpperCamelCase : str=[4, 2, 2] , UpperCamelCase : Dict=[2, 1, 1] , UpperCamelCase : Dict=[64, 192, 384] , UpperCamelCase : Dict=[1, 3, 6] , UpperCamelCase : Dict=[1, 2, 10] , UpperCamelCase : Any=[4.0, 4.0, 4.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : Optional[int]=[0.0, 0.0, 0.0] , UpperCamelCase : int=[0.0, 0.0, 0.1] , UpperCamelCase : Any=[True, True, True] , UpperCamelCase : int=[False, False, True] , UpperCamelCase : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase : Optional[int]=[3, 3, 3] , UpperCamelCase : Tuple=[1, 1, 1] , UpperCamelCase : Any=[2, 2, 2] , UpperCamelCase : Dict=[1, 1, 1] , UpperCamelCase : List[str]=[1, 1, 1] , UpperCamelCase : str=0.02 , UpperCamelCase : int=1E-12 , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' super().__init__(**UpperCamelCase ) lowercase__ = num_channels lowercase__ = patch_sizes lowercase__ = patch_stride lowercase__ = patch_padding lowercase__ = embed_dim lowercase__ = num_heads lowercase__ = depth lowercase__ = mlp_ratio lowercase__ = attention_drop_rate lowercase__ = drop_rate lowercase__ = drop_path_rate lowercase__ = qkv_bias lowercase__ = cls_token lowercase__ = qkv_projection_method lowercase__ = kernel_qkv lowercase__ = padding_kv lowercase__ = stride_kv lowercase__ = padding_q lowercase__ = stride_q lowercase__ = initializer_range lowercase__ = layer_norm_eps
2
1
'''simple docstring''' import unittest from datasets import load_dataset from transformers import BloomTokenizerFast from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : str = None lowerCAmelCase__ : Optional[int] = BloomTokenizerFast lowerCAmelCase__ : Tuple = BloomTokenizerFast lowerCAmelCase__ : Dict = True lowerCAmelCase__ : List[str] = False lowerCAmelCase__ : Union[str, Any] = """tokenizer_file""" lowerCAmelCase__ : Dict = {"""bos_token""": """<s>""", """eos_token""": """</s>""", """unk_token""": """<unk>""", """pad_token""": """<pad>"""} def UpperCamelCase__ (self : int ): '''simple docstring''' super().setUp() lowercase__ = BloomTokenizerFast.from_pretrained('''bigscience/tokenizer''' ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ (self : str , **UpperCamelCase : int ): '''simple docstring''' kwargs.update(self.special_tokens_map ) return BloomTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.get_rust_tokenizer() lowercase__ = ['''The quick brown fox</s>''', '''jumps over the lazy dog</s>'''] lowercase__ = [[2175, 23714, 73173, 144252, 2], [77, 132619, 3478, 368, 109586, 35433, 2]] lowercase__ = tokenizer.batch_encode_plus(UpperCamelCase )['''input_ids'''] self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.batch_decode(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any]=6 ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})" ): lowercase__ = self.rust_tokenizer_class.from_pretrained(UpperCamelCase , **UpperCamelCase ) # tokenizer_r.pad_token = None # Hotfixing padding = None # Simple input lowercase__ = '''This is a simple input''' lowercase__ = ['''This is a simple input 1''', '''This is a simple input 2'''] lowercase__ = ('''This is a simple input''', '''This is a pair''') lowercase__ = [ ('''This is a simple input 1''', '''This is a simple input 2'''), ('''This is a simple pair 1''', '''This is a simple pair 2'''), ] # Simple input tests try: tokenizer_r.encode(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.encode_plus(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.batch_encode_plus(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.encode(UpperCamelCase , max_length=UpperCamelCase ) tokenizer_r.batch_encode_plus(UpperCamelCase , max_length=UpperCamelCase ) except ValueError: self.fail('''Bloom Tokenizer should be able to deal with padding''' ) lowercase__ = None # Hotfixing padding = None self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' ) # Simple input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' ) # Simple input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' , ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' ) # Pair input self.assertRaises(UpperCamelCase , tokenizer_r.encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' ) # Pair input self.assertRaises( UpperCamelCase , tokenizer_r.batch_encode_plus , UpperCamelCase , max_length=UpperCamelCase , padding='''max_length''' , ) def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = self.get_rust_tokenizer() lowercase__ = load_dataset('''xnli''' , '''all_languages''' , split='''test''' , streaming=UpperCamelCase ) lowercase__ = next(iter(UpperCamelCase ) )['''premise'''] # pick up one data lowercase__ = list(sample_data.values() ) lowercase__ = list(map(tokenizer.encode , UpperCamelCase ) ) lowercase__ = [tokenizer.decode(UpperCamelCase , clean_up_tokenization_spaces=UpperCamelCase ) for x in output_tokens] self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self.assertGreaterEqual(len(self.tokenizer_class.pretrained_vocab_files_map ) , 1 ) self.assertGreaterEqual(len(list(self.tokenizer_class.pretrained_vocab_files_map.values() )[0] ) , 1 )
2
'''simple docstring''' import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCamelCase : Any = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(32, (3, 3), input_shape=(64, 64, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(32, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=128, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCamelCase : Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCamelCase : Any = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 255) lowerCamelCase : List[Any] = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) lowerCamelCase : List[str] = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(64, 64), batch_size=32, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=30, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions lowerCamelCase : List[str] = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(64, 64) ) lowerCamelCase : Optional[int] = tf.keras.preprocessing.image.img_to_array(test_image) lowerCamelCase : str = np.expand_dims(test_image, axis=0) lowerCamelCase : List[str] = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCamelCase : Any = 'Normal' if result[0][0] == 1: lowerCamelCase : Any = 'Abnormality detected'
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE () -> Any: """simple docstring""" for n in range(1 , 1_000_000 ): yield n * (n + 1) // 2 def _SCREAMING_SNAKE_CASE (A ) -> List[Any]: """simple docstring""" lowercase__ = 1 lowercase__ = 2 while i * i <= n: lowercase__ = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _SCREAMING_SNAKE_CASE () -> Tuple: """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(A ) > 500 ) if __name__ == "__main__": print(solution())
2
'''simple docstring''' class __lowerCAmelCase : # Public class to implement a graph '''simple docstring''' def __init__(self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = row lowercase__ = col lowercase__ = graph def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' return ( 0 <= i < self.ROW and 0 <= j < self.COL and not visited[i][j] and self.graph[i][j] ) def UpperCamelCase__ (self : int , UpperCamelCase : int , UpperCamelCase : int , UpperCamelCase : list[list[bool]] ): '''simple docstring''' lowercase__ = [-1, -1, -1, 0, 0, 1, 1, 1] # Coordinate order lowercase__ = [-1, 0, 1, -1, 1, -1, 0, 1] lowercase__ = True # Make those cells visited for k in range(8 ): if self.is_safe(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ): self.diffs(i + row_nbr[k] , j + col_nbr[k] , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): # And finally, count all islands. '''simple docstring''' lowercase__ = [[False for j in range(self.COL )] for i in range(self.ROW )] lowercase__ = 0 for i in range(self.ROW ): for j in range(self.COL ): if visited[i][j] is False and self.graph[i][j] == 1: self.diffs(UpperCamelCase , UpperCamelCase , UpperCamelCase ) count += 1 return count
2
1
'''simple docstring''' import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[Any] = TransfoXLTokenizer lowerCAmelCase__ : int = False lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Dict ): '''simple docstring''' super().setUp() lowercase__ = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] lowercase__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def UpperCamelCase__ (self : List[str] , **UpperCamelCase : int ): '''simple docstring''' lowercase__ = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase ) def UpperCamelCase__ (self : int , UpperCamelCase : int ): '''simple docstring''' lowercase__ = '''<unk> UNwanted , running''' lowercase__ = '''<unk> unwanted, running''' return input_text, output_text def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=UpperCamelCase ) lowercase__ = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(UpperCamelCase , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase ) , [0, 4, 8, 7] ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = TransfoXLTokenizer(lower_case=UpperCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' lowercase__ = TransfoXLTokenizer(lower_case=UpperCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = TransfoXLTokenizer(lower_case=UpperCamelCase ) lowercase__ = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' lowercase__ = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(UpperCamelCase ) , UpperCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(UpperCamelCase ) , UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = self.get_tokenizer() lowercase__ = len(UpperCamelCase ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(UpperCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
2
'''simple docstring''' import unittest from transformers import DonutProcessor lowerCamelCase : Tuple = 'naver-clova-ix/donut-base' class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = DonutProcessor.from_pretrained(UpperCamelCase ) def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = { '''name''': '''John Doe''', '''age''': '''99''', '''city''': '''Atlanta''', '''state''': '''GA''', '''zip''': '''30301''', '''phone''': '''123-4567''', '''nicknames''': [{'''nickname''': '''Johnny'''}, {'''nickname''': '''JD'''}], } lowercase__ = ( '''<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>''' '''<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>''' '''<s_nicknames><s_nickname>Johnny</s_nickname>''' '''<sep/><s_nickname>JD</s_nickname></s_nicknames>''' ) lowercase__ = self.processor.tokenajson(UpperCamelCase ) self.assertDictEqual(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys lowerCamelCase : Any = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') lowerCamelCase : Dict = subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() lowerCamelCase : Optional[int] = '|'.join(sys.argv[1:]) lowerCamelCase : Dict = re.compile(Rf"""^({joined_dirs}).*?\.py$""") lowerCamelCase : Dict = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
2
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return len(set(A ) ) == len(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
1
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE (A ) -> bool: """simple docstring""" return len(set(A ) ) == len(A ) if __name__ == "__main__": import doctest doctest.testmod()
2
'''simple docstring''' import os import re import warnings from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_ta import TaTokenizer else: lowerCamelCase : Any = None lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Optional[int] = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} lowerCamelCase : List[str] = { 'vocab_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/spiece.model', 't5-base': 'https://huggingface.co/t5-base/resolve/main/spiece.model', 't5-large': 'https://huggingface.co/t5-large/resolve/main/spiece.model', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/spiece.model', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/spiece.model', }, 'tokenizer_file': { 't5-small': 'https://huggingface.co/t5-small/resolve/main/tokenizer.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/tokenizer.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/tokenizer.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/tokenizer.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/tokenizer.json', }, } # TODO(PVP) - this should be removed in Transformers v5 lowerCamelCase : Any = { 't5-small': 512, 't5-base': 512, 't5-large': 512, 't5-3b': 512, 't5-11b': 512, } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = VOCAB_FILES_NAMES lowerCAmelCase__ : str = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : int = ["""input_ids""", """attention_mask"""] lowerCAmelCase__ : Optional[int] = TaTokenizer lowerCAmelCase__ : List[int] = [] def __init__(self : Dict , UpperCamelCase : str=None , UpperCamelCase : Optional[Any]=None , UpperCamelCase : Any="</s>" , UpperCamelCase : str="<unk>" , UpperCamelCase : List[str]="<pad>" , UpperCamelCase : List[str]=100 , UpperCamelCase : Tuple=None , **UpperCamelCase : List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: lowercase__ = [f"<extra_id_{i}>" for i in range(UpperCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra special tokens lowercase__ = len(set(filter(lambda UpperCamelCase : bool('''extra_id_''' in str(UpperCamelCase ) ) , UpperCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) super().__init__( UpperCamelCase , tokenizer_file=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , pad_token=UpperCamelCase , extra_ids=UpperCamelCase , additional_special_tokens=UpperCamelCase , **UpperCamelCase , ) lowercase__ = vocab_file lowercase__ = False if not self.vocab_file else True lowercase__ = extra_ids @staticmethod def UpperCamelCase__ (UpperCamelCase : List[Any] , UpperCamelCase : Union[str, Any] , UpperCamelCase : Optional[Any] ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes: lowercase__ = TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this" ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f" {pretrained_model_name_or_path} automatically truncating your input to" f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences" f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with" ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , UpperCamelCase , ) return max_model_length def UpperCamelCase__ (self : Any , UpperCamelCase : str , UpperCamelCase : Optional[str] = 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(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ): copyfile(self.vocab_file , UpperCamelCase ) logger.info(f"Copy vocab file to {out_vocab_file}" ) return (out_vocab_file,) def UpperCamelCase__ (self : Any , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = token_ids_a + [self.eos_token_id] if token_ids_a is None: return self.prefix_tokens + token_ids_a else: lowercase__ = token_ids_a + [self.eos_token_id] return self.prefix_tokens + token_ids_a + token_ids_a def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return list( set(filter(lambda UpperCamelCase : bool(re.search(R'''<extra_id_\d+>''' , UpperCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return [self.convert_tokens_to_ids(UpperCamelCase ) for token in self.get_sentinel_tokens()]
2
1
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer lowerCamelCase : int = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase : Dict = '\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n >>> repo = "openai/shap-e-img2img"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n >>> image = load_image(image_url).convert("RGB")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n ```\n' @dataclass class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[PIL.Image.Image, np.ndarray] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Union[str, Any] , UpperCamelCase : PriorTransformer , UpperCamelCase : CLIPVisionModel , UpperCamelCase : CLIPImageProcessor , UpperCamelCase : HeunDiscreteScheduler , UpperCamelCase : ShapERenderer , ): '''simple docstring''' super().__init__() self.register_modules( prior=UpperCamelCase , image_encoder=UpperCamelCase , image_processor=UpperCamelCase , scheduler=UpperCamelCase , renderer=UpperCamelCase , ) def UpperCamelCase__ (self : str , UpperCamelCase : str , UpperCamelCase : Dict , UpperCamelCase : int , UpperCamelCase : Tuple , UpperCamelCase : str , UpperCamelCase : Any ): '''simple docstring''' if latents is None: lowercase__ = randn_tensor(UpperCamelCase , generator=UpperCamelCase , device=UpperCamelCase , dtype=UpperCamelCase ) else: if latents.shape != shape: raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}" ) lowercase__ = latents.to(UpperCamelCase ) lowercase__ = latents * scheduler.init_noise_sigma return latents def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Any=0 ): '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) lowercase__ = torch.device(f"cuda:{gpu_id}" ) lowercase__ = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(UpperCamelCase , UpperCamelCase ) @property def UpperCamelCase__ (self : str ): '''simple docstring''' if self.device != torch.device('''meta''' ) or not hasattr(self.image_encoder , '''_hf_hook''' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(UpperCamelCase , '''_hf_hook''' ) and hasattr(module._hf_hook , '''execution_device''' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def UpperCamelCase__ (self : Tuple , UpperCamelCase : str , UpperCamelCase : str , UpperCamelCase : Union[str, Any] , UpperCamelCase : Any , ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(image[0] , torch.Tensor ): lowercase__ = torch.cat(UpperCamelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(UpperCamelCase , axis=0 ) if not isinstance(UpperCamelCase , torch.Tensor ): lowercase__ = self.image_processor(UpperCamelCase , return_tensors='''pt''' ).pixel_values[0].unsqueeze(0 ) lowercase__ = image.to(dtype=self.image_encoder.dtype , device=UpperCamelCase ) lowercase__ = self.image_encoder(UpperCamelCase )['''last_hidden_state'''] lowercase__ = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 lowercase__ = image_embeds.repeat_interleave(UpperCamelCase , dim=0 ) if do_classifier_free_guidance: lowercase__ = torch.zeros_like(UpperCamelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes lowercase__ = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(UpperCamelCase ) def __call__(self : str , UpperCamelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , UpperCamelCase : int = 1 , UpperCamelCase : int = 25 , UpperCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase : Optional[torch.FloatTensor] = None , UpperCamelCase : float = 4.0 , UpperCamelCase : int = 64 , UpperCamelCase : Optional[str] = "pil" , UpperCamelCase : bool = True , ): '''simple docstring''' if isinstance(UpperCamelCase , PIL.Image.Image ): lowercase__ = 1 elif isinstance(UpperCamelCase , torch.Tensor ): lowercase__ = image.shape[0] elif isinstance(UpperCamelCase , UpperCamelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): lowercase__ = len(UpperCamelCase ) else: raise ValueError( f"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(UpperCamelCase )}" ) lowercase__ = self._execution_device lowercase__ = batch_size * num_images_per_prompt lowercase__ = guidance_scale > 1.0 lowercase__ = self._encode_image(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) # prior self.scheduler.set_timesteps(UpperCamelCase , device=UpperCamelCase ) lowercase__ = self.scheduler.timesteps lowercase__ = self.prior.config.num_embeddings lowercase__ = self.prior.config.embedding_dim lowercase__ = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , UpperCamelCase , UpperCamelCase , UpperCamelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim lowercase__ = latents.reshape(latents.shape[0] , UpperCamelCase , UpperCamelCase ) for i, t in enumerate(self.progress_bar(UpperCamelCase ) ): # expand the latents if we are doing classifier free guidance lowercase__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents lowercase__ = self.scheduler.scale_model_input(UpperCamelCase , UpperCamelCase ) lowercase__ = self.prior( UpperCamelCase , timestep=UpperCamelCase , proj_embedding=UpperCamelCase , ).predicted_image_embedding # remove the variance lowercase__ ,lowercase__ = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: lowercase__ ,lowercase__ = noise_pred.chunk(2 ) lowercase__ = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) lowercase__ = self.scheduler.step( UpperCamelCase , timestep=UpperCamelCase , sample=UpperCamelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=UpperCamelCase ) lowercase__ = [] for i, latent in enumerate(UpperCamelCase ): print() lowercase__ = self.renderer.decode( latent[None, :] , UpperCamelCase , size=UpperCamelCase , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(UpperCamelCase ) lowercase__ = torch.stack(UpperCamelCase ) if output_type not in ["np", "pil"]: raise ValueError(f"Only the output types `pil` and `np` are supported not output_type={output_type}" ) lowercase__ = images.cpu().numpy() if output_type == "pil": lowercase__ = [self.numpy_to_pil(UpperCamelCase ) for image in images] # Offload last model to CPU if hasattr(self , '''final_offload_hook''' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=UpperCamelCase )
2
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : Dict = ShapEImgaImgPipeline lowerCAmelCase__ : List[str] = ["""image"""] lowerCAmelCase__ : Any = ["""image"""] lowerCAmelCase__ : Any = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] lowerCAmelCase__ : Tuple = False @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : str ): '''simple docstring''' return 32 @property def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' return self.time_input_dim * 4 @property def UpperCamelCase__ (self : int ): '''simple docstring''' return 8 @property def UpperCamelCase__ (self : Any ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowercase__ = CLIPVisionModel(UpperCamelCase ) return model @property def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' lowercase__ = CLIPImageProcessor( crop_size=224 , do_center_crop=UpperCamelCase , do_normalize=UpperCamelCase , do_resize=UpperCamelCase , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , ) return image_processor @property def UpperCamelCase__ (self : str ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''num_attention_heads''': 2, '''attention_head_dim''': 16, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 32, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowercase__ = PriorTransformer(**UpperCamelCase ) return model @property def UpperCamelCase__ (self : int ): '''simple docstring''' torch.manual_seed(0 ) lowercase__ = { '''param_shapes''': ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 12, '''background''': ( 0.1, 0.1, 0.1, ), } lowercase__ = ShapERenderer(**UpperCamelCase ) return model def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.dummy_prior lowercase__ = self.dummy_image_encoder lowercase__ = self.dummy_image_processor lowercase__ = self.dummy_renderer lowercase__ = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1024 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase , clip_sample=UpperCamelCase , clip_sample_range=1.0 , ) lowercase__ = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : Optional[int] , UpperCamelCase : str=0 ): '''simple docstring''' lowercase__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(UpperCamelCase ) ).to(UpperCamelCase ) if str(UpperCamelCase ).startswith('''mps''' ): lowercase__ = torch.manual_seed(UpperCamelCase ) else: lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(UpperCamelCase ) lowercase__ = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 32, '''output_type''': '''np''', } return inputs def UpperCamelCase__ (self : Tuple ): '''simple docstring''' lowercase__ = '''cpu''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = pipe(**self.get_dummy_inputs(UpperCamelCase ) ) lowercase__ = output.images[0] lowercase__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) lowercase__ = np.array( [ 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, 0.00_03_92_16, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = torch_device == '''cpu''' lowercase__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase , relax_max_difference=UpperCamelCase , ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = self.get_dummy_components() lowercase__ = self.pipeline_class(**UpperCamelCase ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = 1 lowercase__ = 2 lowercase__ = self.get_dummy_inputs(UpperCamelCase ) for key in inputs.keys(): if key in self.batch_params: lowercase__ = batch_size * [inputs[key]] lowercase__ = pipe(**UpperCamelCase , num_images_per_prompt=UpperCamelCase )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class __lowerCAmelCase (unittest.TestCase ): '''simple docstring''' def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowercase__ = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowercase__ = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowercase__ = pipe.to(UpperCamelCase ) pipe.set_progress_bar_config(disable=UpperCamelCase ) lowercase__ = torch.Generator(device=UpperCamelCase ).manual_seed(0 ) lowercase__ = pipe( UpperCamelCase , generator=UpperCamelCase , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type='''np''' , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(UpperCamelCase , UpperCamelCase )
2
1
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[str] = {'vocab_file': 'spiece.model'} lowerCamelCase : Optional[Any] = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } lowerCamelCase : Any = { 'albert-base-v1': 512, 'albert-large-v1': 512, 'albert-xlarge-v1': 512, 'albert-xxlarge-v1': 512, 'albert-base-v2': 512, 'albert-large-v2': 512, 'albert-xlarge-v2': 512, 'albert-xxlarge-v2': 512, } lowerCamelCase : Optional[Any] = '▁' class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : int = VOCAB_FILES_NAMES lowerCAmelCase__ : Optional[int] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self : Optional[Any] , UpperCamelCase : Any , UpperCamelCase : List[str]=True , UpperCamelCase : Any=True , UpperCamelCase : Optional[int]=False , UpperCamelCase : List[str]="[CLS]" , UpperCamelCase : List[str]="[SEP]" , UpperCamelCase : int="<unk>" , UpperCamelCase : Optional[Any]="[SEP]" , UpperCamelCase : Optional[Any]="<pad>" , UpperCamelCase : List[str]="[CLS]" , UpperCamelCase : Tuple="[MASK]" , UpperCamelCase : Optional[Dict[str, Any]] = None , **UpperCamelCase : Dict , ): '''simple docstring''' lowercase__ = ( AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase , normalized=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else mask_token ) lowercase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=UpperCamelCase , remove_space=UpperCamelCase , keep_accents=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , sep_token=UpperCamelCase , pad_token=UpperCamelCase , cls_token=UpperCamelCase , mask_token=UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase , ) lowercase__ = do_lower_case lowercase__ = remove_space lowercase__ = keep_accents lowercase__ = vocab_file lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCamelCase ) @property def UpperCamelCase__ (self : Dict ): '''simple docstring''' return len(self.sp_model ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = {self.convert_ids_to_tokens(UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self : int ): '''simple docstring''' lowercase__ = self.__dict__.copy() lowercase__ = None return state def __setstate__(self : Tuple , UpperCamelCase : List[Any] ): '''simple docstring''' lowercase__ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): lowercase__ = {} lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase__ (self : Tuple , UpperCamelCase : Dict ): '''simple docstring''' if self.remove_space: lowercase__ = ''' '''.join(inputs.strip().split() ) else: lowercase__ = inputs lowercase__ = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: lowercase__ = unicodedata.normalize('''NFKD''' , UpperCamelCase ) lowercase__ = ''''''.join([c for c in outputs if not unicodedata.combining(UpperCamelCase )] ) if self.do_lower_case: lowercase__ = outputs.lower() return outputs def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = self.preprocess_text(UpperCamelCase ) lowercase__ = self.sp_model.encode(UpperCamelCase , out_type=UpperCamelCase ) lowercase__ = [] for piece in pieces: if len(UpperCamelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): lowercase__ = self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase__ = cur_pieces[1:] else: lowercase__ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(UpperCamelCase ) else: new_pieces.append(UpperCamelCase ) return new_pieces def UpperCamelCase__ (self : str , UpperCamelCase : Optional[int] ): '''simple docstring''' return self.sp_model.PieceToId(UpperCamelCase ) def UpperCamelCase__ (self : List[str] , UpperCamelCase : List[str] ): '''simple docstring''' return self.sp_model.IdToPiece(UpperCamelCase ) def UpperCamelCase__ (self : str , UpperCamelCase : str ): '''simple docstring''' lowercase__ = [] lowercase__ = '''''' lowercase__ = 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(UpperCamelCase ) + token lowercase__ = True lowercase__ = [] else: current_sub_tokens.append(UpperCamelCase ) lowercase__ = False out_string += self.sp_model.decode(UpperCamelCase ) return out_string.strip() def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase__ (self : int , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None , UpperCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase , token_ids_a=UpperCamelCase , already_has_special_tokens=UpperCamelCase ) if token_ids_a is not None: return [1] + ([0] * len(UpperCamelCase )) + [1] + ([0] * len(UpperCamelCase )) + [1] return [1] + ([0] * len(UpperCamelCase )) + [1] def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(UpperCamelCase , '''wb''' ) as fi: lowercase__ = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase ) return (out_vocab_file,)
2
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCamelCase : str = { 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Dict = [ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Optional[int] = [ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCamelCase : Any = { 'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'], 'processing_mgp_str': ['MgpstrProcessor'], 'tokenization_mgp_str': ['MgpstrTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase : Union[str, Any] = [ 'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST', 'MgpstrModel', 'MgpstrPreTrainedModel', 'MgpstrForSceneTextRecognition', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCamelCase : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : int = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json', # See all REALM models at https://huggingface.co/models?filter=realm } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = """realm""" def __init__(self : str , UpperCamelCase : List[Any]=30522 , UpperCamelCase : List[Any]=768 , UpperCamelCase : int=128 , UpperCamelCase : Any=12 , UpperCamelCase : Tuple=12 , UpperCamelCase : List[Any]=8 , UpperCamelCase : Union[str, Any]=3072 , UpperCamelCase : List[str]="gelu_new" , UpperCamelCase : Any=0.1 , UpperCamelCase : List[str]=0.1 , UpperCamelCase : Dict=512 , UpperCamelCase : Dict=2 , UpperCamelCase : List[Any]=0.02 , UpperCamelCase : List[Any]=1E-12 , UpperCamelCase : Dict=256 , UpperCamelCase : Union[str, Any]=10 , UpperCamelCase : Optional[int]=1E-3 , UpperCamelCase : Tuple=5 , UpperCamelCase : Optional[int]=320 , UpperCamelCase : List[str]=13353718 , UpperCamelCase : Optional[Any]=5000 , UpperCamelCase : str=1 , UpperCamelCase : Union[str, Any]=0 , UpperCamelCase : List[Any]=2 , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , **UpperCamelCase ) # Common config lowercase__ = vocab_size lowercase__ = max_position_embeddings lowercase__ = hidden_size lowercase__ = retriever_proj_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = num_candidates lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = initializer_range lowercase__ = type_vocab_size lowercase__ = layer_norm_eps # Reader config lowercase__ = span_hidden_size lowercase__ = max_span_width lowercase__ = reader_layer_norm_eps lowercase__ = reader_beam_size lowercase__ = reader_seq_len # Retrieval config lowercase__ = num_block_records lowercase__ = searcher_beam_size
2
1
'''simple docstring''' import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: lowercase__ = 4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: lowercase__ = 4 lowercase__ = 48 lowercase__ = '''pixelshuffle_aux''' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: lowercase__ = [6, 6, 6, 6] lowercase__ = 60 lowercase__ = [6, 6, 6, 6] lowercase__ = '''pixelshuffledirect''' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: lowercase__ = 4 lowercase__ = '''nearest+conv''' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: lowercase__ = 1 lowercase__ = 1 lowercase__ = 126 lowercase__ = 7 lowercase__ = 255.0 lowercase__ = '''''' return config def _SCREAMING_SNAKE_CASE (A , A ) -> Dict: """simple docstring""" if "patch_embed.proj" in name and "layers" not in name: lowercase__ = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: lowercase__ = name.replace('''patch_embed.norm''' , '''embeddings.patch_embeddings.layernorm''' ) if "layers" in name: lowercase__ = name.replace('''layers''' , '''encoder.stages''' ) if "residual_group.blocks" in name: lowercase__ = name.replace('''residual_group.blocks''' , '''layers''' ) if "attn.proj" in name: lowercase__ = name.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in name: lowercase__ = name.replace('''attn''' , '''attention.self''' ) if "norm1" in name: lowercase__ = name.replace('''norm1''' , '''layernorm_before''' ) if "norm2" in name: lowercase__ = name.replace('''norm2''' , '''layernorm_after''' ) if "mlp.fc1" in name: lowercase__ = name.replace('''mlp.fc1''' , '''intermediate.dense''' ) if "mlp.fc2" in name: lowercase__ = name.replace('''mlp.fc2''' , '''output.dense''' ) if "q_bias" in name: lowercase__ = name.replace('''q_bias''' , '''query.bias''' ) if "k_bias" in name: lowercase__ = name.replace('''k_bias''' , '''key.bias''' ) if "v_bias" in name: lowercase__ = name.replace('''v_bias''' , '''value.bias''' ) if "cpb_mlp" in name: lowercase__ = name.replace('''cpb_mlp''' , '''continuous_position_bias_mlp''' ) if "patch_embed.proj" in name: lowercase__ = name.replace('''patch_embed.proj''' , '''patch_embed.projection''' ) if name == "norm.weight": lowercase__ = '''layernorm.weight''' if name == "norm.bias": lowercase__ = '''layernorm.bias''' if "conv_first" in name: lowercase__ = name.replace('''conv_first''' , '''first_convolution''' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: lowercase__ = name.replace('''conv_last''' , '''final_convolution''' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: lowercase__ = name.replace('''conv_before_upsample.0''' , '''conv_before_upsample''' ) if "upsample.0" in name: lowercase__ = name.replace('''upsample.0''' , '''upsample.convolution_0''' ) if "upsample.2" in name: lowercase__ = name.replace('''upsample.2''' , '''upsample.convolution_1''' ) lowercase__ = '''upsample.''' + name elif config.upsampler == "pixelshuffledirect": lowercase__ = name.replace('''upsample.0.weight''' , '''upsample.conv.weight''' ) lowercase__ = name.replace('''upsample.0.bias''' , '''upsample.conv.bias''' ) else: pass else: lowercase__ = '''swin2sr.''' + name return name def _SCREAMING_SNAKE_CASE (A , A ) -> Dict: """simple docstring""" for key in orig_state_dict.copy().keys(): lowercase__ = orig_state_dict.pop(A ) if "qkv" in key: lowercase__ = key.split('''.''' ) lowercase__ = int(key_split[1] ) lowercase__ = int(key_split[4] ) lowercase__ = config.embed_dim if "weight" in key: lowercase__ = val[:dim, :] lowercase__ = val[dim : dim * 2, :] lowercase__ = val[-dim:, :] else: lowercase__ = val[:dim] lowercase__ = val[dim : dim * 2] lowercase__ = val[-dim:] pass else: lowercase__ = val return orig_state_dict def _SCREAMING_SNAKE_CASE (A , A , A ) -> Tuple: """simple docstring""" lowercase__ = get_config(A ) lowercase__ = SwinaSRForImageSuperResolution(A ) model.eval() lowercase__ = torch.hub.load_state_dict_from_url(A , map_location='''cpu''' ) lowercase__ = convert_state_dict(A , A ) lowercase__ ,lowercase__ = model.load_state_dict(A , strict=A ) if len(A ) > 0: raise ValueError('''Missing keys when converting: {}'''.format(A ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(f"Unexpected key {key} in state_dict" ) # verify values lowercase__ = '''https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true''' lowercase__ = Image.open(requests.get(A , stream=A ).raw ).convert('''RGB''' ) lowercase__ = SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values lowercase__ = 126 if '''Jpeg''' in checkpoint_url else 256 lowercase__ = Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) lowercase__ = transforms(A ).unsqueeze(0 ) if config.num_channels == 1: lowercase__ = pixel_values[:, 0, :, :].unsqueeze(1 ) lowercase__ = model(A ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: lowercase__ = torch.Size([1, 3, 512, 512] ) lowercase__ = torch.tensor( [[-0.7_087, -0.7_138, -0.6_721], [-0.8_340, -0.8_095, -0.7_298], [-0.9_149, -0.8_414, -0.7_940]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: lowercase__ = torch.Size([1, 3, 1_024, 1_024] ) lowercase__ = torch.tensor( [[-0.7_775, -0.8_105, -0.8_933], [-0.7_764, -0.8_356, -0.9_225], [-0.7_976, -0.8_686, -0.9_579]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here lowercase__ = torch.Size([1, 3, 1_024, 1_024] ) lowercase__ = torch.tensor( [[-0.8_035, -0.7_504, -0.7_491], [-0.8_538, -0.8_124, -0.7_782], [-0.8_804, -0.8_651, -0.8_493]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: lowercase__ = torch.Size([1, 3, 512, 512] ) lowercase__ = torch.tensor( [[-0.7_669, -0.8_662, -0.8_767], [-0.8_810, -0.9_962, -0.9_820], [-0.9_340, -1.0_322, -1.1_149]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: lowercase__ = torch.Size([1, 3, 1_024, 1_024] ) lowercase__ = torch.tensor( [[-0.5_238, -0.5_557, -0.6_321], [-0.6_016, -0.5_903, -0.6_391], [-0.6_244, -0.6_334, -0.6_889]] ) assert ( outputs.reconstruction.shape == expected_shape ), f"Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}" assert torch.allclose(outputs.reconstruction[0, 0, :3, :3] , A , atol=1E-3 ) print('''Looks ok!''' ) lowercase__ = { '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''': ( '''swin2SR-classical-sr-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth''': ( '''swin2SR-classical-sr-x4-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth''': ( '''swin2SR-compressed-sr-x4-48''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth''': ( '''swin2SR-lightweight-x2-64''' ), '''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth''': ( '''swin2SR-realworld-sr-x4-64-bsrgan-psnr''' ), } lowercase__ = url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(f"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(A ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(A ) if push_to_hub: model.push_to_hub(f"caidas/{model_name}" ) processor.push_to_hub(f"caidas/{model_name}" ) if __name__ == "__main__": lowerCamelCase : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth', type=str, help='URL of the original Swin2SR checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the converted model to the hub.') lowerCamelCase : Dict = parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
2
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : str = logging.get_logger(__name__) lowerCamelCase : int = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = """mvp""" lowerCAmelCase__ : Optional[Any] = ["""past_key_values"""] lowerCAmelCase__ : List[str] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__(self : Any , UpperCamelCase : Optional[int]=50267 , UpperCamelCase : Tuple=1024 , UpperCamelCase : int=12 , UpperCamelCase : Tuple=4096 , UpperCamelCase : Dict=16 , UpperCamelCase : int=12 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : Optional[int]=16 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : Tuple=0.0 , UpperCamelCase : List[Any]="gelu" , UpperCamelCase : Union[str, Any]=1024 , UpperCamelCase : Optional[Any]=0.1 , UpperCamelCase : str=0.0 , UpperCamelCase : str=0.0 , UpperCamelCase : Optional[Any]=0.02 , UpperCamelCase : List[str]=0.0 , UpperCamelCase : List[str]=False , UpperCamelCase : Optional[int]=True , UpperCamelCase : Any=1 , UpperCamelCase : int=0 , UpperCamelCase : int=2 , UpperCamelCase : Any=True , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Optional[Any]=2 , UpperCamelCase : Tuple=False , UpperCamelCase : int=100 , UpperCamelCase : Optional[Any]=800 , **UpperCamelCase : str , ): '''simple docstring''' lowercase__ = vocab_size lowercase__ = max_position_embeddings 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__ = encoder_layerdrop lowercase__ = decoder_layerdrop lowercase__ = classifier_dropout lowercase__ = use_cache lowercase__ = encoder_layers lowercase__ = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ = use_prompt lowercase__ = prompt_length lowercase__ = prompt_mid_dim super().__init__( pad_token_id=UpperCamelCase , bos_token_id=UpperCamelCase , eos_token_id=UpperCamelCase , is_encoder_decoder=UpperCamelCase , decoder_start_token_id=UpperCamelCase , forced_eos_token_id=UpperCamelCase , **UpperCamelCase , ) if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated''' , UpperCamelCase ): lowercase__ = self.bos_token_id warnings.warn( f"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. " '''The config can simply be saved and uploaded again to be fixed.''' )
2
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''' import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def _SCREAMING_SNAKE_CASE () -> Union[str, Any]: """simple docstring""" lowercase__ = '''https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png''' lowercase__ = Image.open(requests.get(A , stream=A ).raw ).convert('''RGB''' ) return image def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = [] # fmt: off # vision encoder rename_keys.append(('''visual_encoder.cls_token''', '''vision_model.embeddings.class_embedding''') ) rename_keys.append(('''visual_encoder.pos_embed''', '''vision_model.embeddings.position_embedding''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.weight''', '''vision_model.embeddings.patch_embedding.weight''') ) rename_keys.append(('''visual_encoder.patch_embed.proj.bias''', '''vision_model.embeddings.patch_embedding.bias''') ) rename_keys.append(('''ln_vision.weight''', '''vision_model.post_layernorm.weight''') ) rename_keys.append(('''ln_vision.bias''', '''vision_model.post_layernorm.bias''') ) for i in range(config.vision_config.num_hidden_layers ): rename_keys.append((f"visual_encoder.blocks.{i}.norm1.weight", f"vision_model.encoder.layers.{i}.layer_norm1.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm1.bias", f"vision_model.encoder.layers.{i}.layer_norm1.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.weight", f"vision_model.encoder.layers.{i}.layer_norm2.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.bias", f"vision_model.encoder.layers.{i}.layer_norm2.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.qkv.weight", f"vision_model.encoder.layers.{i}.self_attn.qkv.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.weight", f"vision_model.encoder.layers.{i}.self_attn.projection.weight",) ) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.bias", f"vision_model.encoder.layers.{i}.self_attn.projection.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.weight", f"vision_model.encoder.layers.{i}.mlp.fc1.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.bias", f"vision_model.encoder.layers.{i}.mlp.fc1.bias") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.weight", f"vision_model.encoder.layers.{i}.mlp.fc2.weight") ) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.bias", f"vision_model.encoder.layers.{i}.mlp.fc2.bias") ) # QFormer rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.weight''', '''qformer.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') ) # fmt: on return rename_keys def _SCREAMING_SNAKE_CASE (A , A , A ) -> Union[str, Any]: """simple docstring""" lowercase__ = dct.pop(A ) lowercase__ = val def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases lowercase__ = state_dict.pop(f"visual_encoder.blocks.{i}.attn.q_bias" ) lowercase__ = state_dict.pop(f"visual_encoder.blocks.{i}.attn.v_bias" ) # next, set bias in the state dict lowercase__ = torch.cat((q_bias, torch.zeros_like(A , requires_grad=A ), v_bias) ) lowercase__ = qkv_bias def _SCREAMING_SNAKE_CASE (A , A ) -> List[str]: """simple docstring""" lowercase__ = 364 if '''coco''' in model_name else 224 lowercase__ = BlipaVisionConfig(image_size=A ).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "opt-2.7b" in model_name: lowercase__ = OPTConfig.from_pretrained('''facebook/opt-2.7b''' , eos_token_id=A ).to_dict() elif "opt-6.7b" in model_name: lowercase__ = OPTConfig.from_pretrained('''facebook/opt-6.7b''' , eos_token_id=A ).to_dict() elif "t5-xl" in model_name: lowercase__ = TaConfig.from_pretrained('''google/flan-t5-xl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: lowercase__ = TaConfig.from_pretrained('''google/flan-t5-xxl''' , dense_act_fn='''gelu''' , bos_token_id=1 ).to_dict() lowercase__ = BlipaConfig(vision_config=A , text_config=A ) return config, image_size @torch.no_grad() def _SCREAMING_SNAKE_CASE (A , A=None , A=False ) -> int: """simple docstring""" lowercase__ = ( AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' ) if '''opt''' in model_name else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' ) ) lowercase__ = tokenizer('''\n''' , add_special_tokens=A ).input_ids[0] lowercase__ ,lowercase__ = get_blipa_config(A , eos_token_id=A ) lowercase__ = BlipaForConditionalGeneration(A ).eval() lowercase__ = { '''blip2-opt-2.7b''': ('''blip2_opt''', '''pretrain_opt2.7b'''), '''blip2-opt-6.7b''': ('''blip2_opt''', '''pretrain_opt6.7b'''), '''blip2-opt-2.7b-coco''': ('''blip2_opt''', '''caption_coco_opt2.7b'''), '''blip2-opt-6.7b-coco''': ('''blip2_opt''', '''caption_coco_opt6.7b'''), '''blip2-flan-t5-xl''': ('''blip2_t5''', '''pretrain_flant5xl'''), '''blip2-flan-t5-xl-coco''': ('''blip2_t5''', '''caption_coco_flant5xl'''), '''blip2-flan-t5-xxl''': ('''blip2_t5''', '''pretrain_flant5xxl'''), } lowercase__ ,lowercase__ = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) lowercase__ = '''cuda''' if torch.cuda.is_available() else '''cpu''' lowercase__ ,lowercase__ ,lowercase__ = load_model_and_preprocess( name=A , model_type=A , is_eval=A , device=A ) original_model.eval() print('''Done!''' ) # update state dict keys lowercase__ = original_model.state_dict() lowercase__ = create_rename_keys(A ) for src, dest in rename_keys: rename_key(A , A , A ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): lowercase__ = state_dict.pop(A ) if key.startswith('''Qformer.bert''' ): lowercase__ = key.replace('''Qformer.bert''' , '''qformer''' ) if "attention.self" in key: lowercase__ = key.replace('''self''' , '''attention''' ) if "opt_proj" in key: lowercase__ = key.replace('''opt_proj''' , '''language_projection''' ) if "t5_proj" in key: lowercase__ = key.replace('''t5_proj''' , '''language_projection''' ) if key.startswith('''opt''' ): lowercase__ = key.replace('''opt''' , '''language''' ) if key.startswith('''t5''' ): lowercase__ = key.replace('''t5''' , '''language''' ) lowercase__ = val # read in qv biases read_in_q_v_bias(A , A ) lowercase__ ,lowercase__ = hf_model.load_state_dict(A , strict=A ) assert len(A ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] lowercase__ = load_demo_image() lowercase__ = vis_processors['''eval'''](A ).unsqueeze(0 ).to(A ) lowercase__ = tokenizer(['''\n'''] , return_tensors='''pt''' ).input_ids.to(A ) # create processor lowercase__ = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size} , image_mean=A , image_std=A ) lowercase__ = BlipaProcessor(image_processor=A , tokenizer=A ) lowercase__ = processor(images=A , return_tensors='''pt''' ).pixel_values.to(A ) # make sure processor creates exact same pixel values assert torch.allclose(A , A ) original_model.to(A ) hf_model.to(A ) with torch.no_grad(): if "opt" in model_name: lowercase__ = original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits lowercase__ = hf_model(A , A ).logits else: lowercase__ = original_model( {'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits lowercase__ = input_ids.masked_fill(input_ids == tokenizer.pad_token_id , -100 ) lowercase__ = hf_model(A , A , labels=A ).logits assert original_logits.shape == logits.shape print('''First values of original logits:''' , original_logits[0, :3, :3] ) print('''First values of HF logits:''' , logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": lowercase__ = torch.tensor( [[-41.5_850, -4.4_440, -8.9_922], [-47.4_322, -5.9_143, -1.7_340]] , device=A ) assert torch.allclose(logits[0, :3, :3] , A , atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": lowercase__ = torch.tensor( [[-57.0_109, -9.8_967, -12.6_280], [-68.6_578, -12.7_191, -10.5_065]] , device=A ) else: # cast to same type lowercase__ = logits.dtype assert torch.allclose(original_logits.to(A ) , A , atol=1E-2 ) print('''Looks ok!''' ) print('''Generating a caption...''' ) lowercase__ = '''''' lowercase__ = tokenizer(A , return_tensors='''pt''' ).input_ids.to(A ) lowercase__ = original_model.generate({'''image''': original_pixel_values} ) lowercase__ = hf_model.generate( A , A , do_sample=A , num_beams=5 , max_length=30 , min_length=1 , top_p=0.9 , repetition_penalty=1.0 , length_penalty=1.0 , temperature=1 , ) print('''Original generation:''' , A ) lowercase__ = input_ids.shape[1] lowercase__ = processor.batch_decode(outputs[:, prompt_length:] , skip_special_tokens=A ) lowercase__ = [text.strip() for text in output_text] print('''HF generation:''' , A ) if pytorch_dump_folder_path is not None: processor.save_pretrained(A ) hf_model.save_pretrained(A ) if push_to_hub: processor.push_to_hub(f"nielsr/{model_name}" ) hf_model.push_to_hub(f"nielsr/{model_name}" ) if __name__ == "__main__": lowerCamelCase : List[Any] = argparse.ArgumentParser() lowerCamelCase : Optional[int] = [ 'blip2-opt-2.7b', 'blip2-opt-6.7b', 'blip2-opt-2.7b-coco', 'blip2-opt-6.7b-coco', 'blip2-flan-t5-xl', 'blip2-flan-t5-xl-coco', 'blip2-flan-t5-xxl', ] parser.add_argument( '--model_name', default='blip2-opt-2.7b', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) lowerCamelCase : List[Any] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
2
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def _SCREAMING_SNAKE_CASE (A ) -> Optional[Any]: """simple docstring""" lowercase__ = [ '''encoder.version''', '''decoder.version''', '''model.encoder.version''', '''model.decoder.version''', '''_float_tensor''', '''decoder.output_projection.weight''', ] for k in ignore_keys: state_dict.pop(A , A ) def _SCREAMING_SNAKE_CASE (A ) -> List[str]: """simple docstring""" lowercase__ ,lowercase__ = emb.weight.shape lowercase__ = nn.Linear(A , A , bias=A ) lowercase__ = emb.weight.data return lin_layer def _SCREAMING_SNAKE_CASE (A , A="facebook/mbart-large-en-ro" , A=False , A=False ) -> Union[str, Any]: """simple docstring""" lowercase__ = torch.load(A , map_location='''cpu''' )['''model'''] remove_ignore_keys_(A ) lowercase__ = state_dict['''encoder.embed_tokens.weight'''].shape[0] lowercase__ = MBartConfig.from_pretrained(A , vocab_size=A ) if mbart_aa and finetuned: lowercase__ = '''relu''' lowercase__ = state_dict['''decoder.embed_tokens.weight'''] lowercase__ = MBartForConditionalGeneration(A ) model.model.load_state_dict(A ) if finetuned: lowercase__ = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCamelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( 'fairseq_path', type=str, help='bart.large, bart.large.cnn or a path to a model.pt on local filesystem.' ) parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--hf_config', default='facebook/mbart-large-cc25', type=str, help='Which huggingface architecture to use: mbart-large', ) parser.add_argument('--mbart_50', action='store_true', help='whether the model is mMART-50 checkpoint') parser.add_argument('--finetuned', action='store_true', help='whether the model is a fine-tuned checkpoint') lowerCamelCase : Any = parser.parse_args() lowerCamelCase : List[str] = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
2
1
'''simple docstring''' lowerCamelCase : List[str] = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '&': '.-...', '@': '.--.-.', ':': '---...', ',': '--..--', '.': '.-.-.-', '\'': '.----.', '"': '.-..-.', '?': '..--..', '/': '-..-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '(': '-.--.', ')': '-.--.-', '!': '-.-.--', ' ': '/' } # Exclamation mark is not in ITU-R recommendation # fmt: on lowerCamelCase : Any = {value: key for key, value in MORSE_CODE_DICT.items()} def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" return "".join(REVERSE_DICT[char] for char in message.split() ) def _SCREAMING_SNAKE_CASE () -> None: """simple docstring""" lowercase__ = '''Morse code here!''' print(A ) lowercase__ = encrypt(A ) print(A ) lowercase__ = decrypt(A ) print(A ) if __name__ == "__main__": main()
2
'''simple docstring''' import logging import os from typing import List, TextIO, Union from conllu import parse_incr from utils_ner import InputExample, Split, TokenClassificationTask lowerCamelCase : List[Any] = logging.getLogger(__name__) class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : Optional[Any] , UpperCamelCase : Any=-1 ): '''simple docstring''' lowercase__ = label_idx def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: lowercase__ = [] lowercase__ = [] for line in f: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 lowercase__ = [] lowercase__ = [] else: lowercase__ = line.split(''' ''' ) words.append(splits[0] ) if len(UpperCamelCase ) > 1: labels.append(splits[self.label_idx].replace('''\n''' , '''''' ) ) else: # Examples could have no label for mode = "test" labels.append('''O''' ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) return examples def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for line in test_input_reader: if line.startswith('''-DOCSTART-''' ) or line == "" or line == "\n": writer.write(UpperCamelCase ) if not preds_list[example_id]: example_id += 1 elif preds_list[example_id]: lowercase__ = line.split()[0] + ''' ''' + preds_list[example_id].pop(0 ) + '''\n''' writer.write(UpperCamelCase ) else: logger.warning('''Maximum sequence length exceeded: No prediction for \'%s\'.''' , line.split()[0] ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return ["O", "B-MISC", "I-MISC", "B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC"] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def __init__(self : List[Any] ): '''simple docstring''' super().__init__(label_idx=-2 ) def UpperCamelCase__ (self : List[Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: lowercase__ = f.read().splitlines() if "O" not in labels: lowercase__ = ['''O'''] + labels return labels else: return [ "O", "B-ADVP", "B-INTJ", "B-LST", "B-PRT", "B-NP", "B-SBAR", "B-VP", "B-ADJP", "B-CONJP", "B-PP", "I-ADVP", "I-INTJ", "I-LST", "I-PRT", "I-NP", "I-SBAR", "I-VP", "I-ADJP", "I-CONJP", "I-PP", ] class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Tuple , UpperCamelCase : int , UpperCamelCase : Union[Split, str] ): '''simple docstring''' if isinstance(UpperCamelCase , UpperCamelCase ): lowercase__ = mode.value lowercase__ = os.path.join(UpperCamelCase , f"{mode}.txt" ) lowercase__ = 1 lowercase__ = [] with open(UpperCamelCase , encoding='''utf-8''' ) as f: for sentence in parse_incr(UpperCamelCase ): lowercase__ = [] lowercase__ = [] for token in sentence: words.append(token['''form'''] ) labels.append(token['''upos'''] ) assert len(UpperCamelCase ) == len(UpperCamelCase ) if words: examples.append(InputExample(guid=f"{mode}-{guid_index}" , words=UpperCamelCase , labels=UpperCamelCase ) ) guid_index += 1 return examples def UpperCamelCase__ (self : Tuple , UpperCamelCase : TextIO , UpperCamelCase : TextIO , UpperCamelCase : List ): '''simple docstring''' lowercase__ = 0 for sentence in parse_incr(UpperCamelCase ): lowercase__ = preds_list[example_id] lowercase__ = '''''' for token in sentence: out += f"{token['form']} ({token['upos']}|{s_p.pop(0 )}) " out += "\n" writer.write(UpperCamelCase ) example_id += 1 def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' if path: with open(UpperCamelCase , '''r''' ) as f: return f.read().splitlines() else: return [ "ADJ", "ADP", "ADV", "AUX", "CCONJ", "DET", "INTJ", "NOUN", "NUM", "PART", "PRON", "PROPN", "PUNCT", "SCONJ", "SYM", "VERB", "X", ]
2
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = '''''' for word_or_phrase in separated: if not isinstance(A , A ): raise Exception('''join() accepts only strings to be joined''' ) joined += word_or_phrase + separator return joined.strip(A ) if __name__ == "__main__": from doctest import testmod testmod()
2
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase : Dict = logging.get_logger(__name__) lowerCamelCase : Union[str, Any] = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : List[str] = """megatron-bert""" def __init__(self : Tuple , UpperCamelCase : Optional[int]=29056 , UpperCamelCase : Optional[Any]=1024 , UpperCamelCase : Any=24 , UpperCamelCase : int=16 , UpperCamelCase : Optional[int]=4096 , UpperCamelCase : int="gelu" , UpperCamelCase : int=0.1 , UpperCamelCase : Tuple=0.1 , UpperCamelCase : Any=512 , UpperCamelCase : int=2 , UpperCamelCase : Dict=0.02 , UpperCamelCase : Dict=1E-12 , UpperCamelCase : List[Any]=0 , UpperCamelCase : Optional[int]="absolute" , UpperCamelCase : List[Any]=True , **UpperCamelCase : str , ): '''simple docstring''' super().__init__(pad_token_id=UpperCamelCase , **UpperCamelCase ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = hidden_act lowercase__ = intermediate_size lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = position_embedding_type lowercase__ = use_cache
2
1
'''simple docstring''' import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCamelCase : int = logging.getLogger(__name__) def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = argparse.ArgumentParser( description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' ) parser.add_argument( '''--dataset_name''' , type=A , default='''wikitext''' , help='''Name of the training. Explore datasets at: hf.co/datasets.''' , ) parser.add_argument( '''--dataset_config''' , type=A , default='''wikitext-103-raw-v1''' , help='''Configuration name of the dataset.''' ) parser.add_argument( '''--tokenizer_name_or_path''' , type=A , default='''sayakpaul/unigram-tokenizer-wikitext''' , help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' , ) parser.add_argument( '''--shard_size''' , type=A , default=1_000 , help='''Number of entries to go in a single shard.''' , ) parser.add_argument('''--split''' , type=A , default='''train''' , choices=['''train''', '''test''', '''validation'''] ) parser.add_argument( '''--limit''' , default=A , type=A , help='''Limit the number of shards (used for debugging).''' , ) parser.add_argument( '''--max_length''' , type=A , default=512 , help='''Maximum sequence length. For training on TPUs, it helps to have a maximum''' ''' sequence length that is a multiple of 8.''' , ) parser.add_argument( '''--output_dir''' , default='''tf-tpu''' , type=A , help='''Output directory where the TFRecord shards will be saved. If the''' ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord''' ''' shards will be directly saved to a Google Cloud Storage bucket.''' , ) lowercase__ = parser.parse_args() return args def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" def fn(A ): return tokenizer(examples['''text'''] ) return fn def _SCREAMING_SNAKE_CASE (A ) -> Union[str, Any]: """simple docstring""" lowercase__ = [] for i in range(len(tokenized_data['''input_ids'''] ) ): lowercase__ = { '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ), '''attention_mask''': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ), } lowercase__ = tf.train.Features(feature=A ) lowercase__ = tf.train.Example(features=A ) lowercase__ = example.SerializeToString() records.append(A ) return records def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: lowercase__ = min(len(A ) , args.limit ) lowercase__ = dataset.select(range(A ) ) print(f"Limiting the dataset to {args.limit} entries." ) lowercase__ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) lowercase__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(A ): os.makedirs(A ) else: lowercase__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. lowercase__ = tokenize_function(A ) lowercase__ = dataset.map(A , batched=A , num_proc=4 , remove_columns=['''text'''] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(A ): # Concatenate all texts. lowercase__ = {k: sum(examples[k] , [] ) for k in examples.keys()} lowercase__ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 lowercase__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. lowercase__ = { k: [t[i : i + args.max_length] for i in range(0 , A , args.max_length )] for k, t in concatenated_examples.items() } return result lowercase__ = dataset_tokenized.map(A , batched=A , batch_size=1_000 , num_proc=4 ) lowercase__ = 0 lowercase__ = 0 for shard in range(0 , len(A ) , args.shard_size ): lowercase__ = grouped_dataset[shard : shard + args.shard_size] lowercase__ = len(dataset_snapshot['''input_ids'''] ) lowercase__ = os.path.join(A , f"dataset-{shard_count}-{records_containing}.tfrecord" ) lowercase__ = get_serialized_examples(A ) with tf.io.TFRecordWriter(A ) as out_file: for i in range(len(A ) ): lowercase__ = serialized_examples[i] out_file.write(A ) print('''Wrote file {} containing {} records'''.format(A , A ) ) shard_count += 1 total_records += records_containing with open(f"split-{args.split}-records-count.txt" , '''w''' ) as f: print(f"Total {args.split} records: {total_records}" , file=A ) if __name__ == "__main__": lowerCamelCase : List[Any] = parse_args() main(args)
2
'''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
1
'''simple docstring''' import os from datetime import datetime as dt from github import Github lowerCamelCase : Optional[Any] = [ 'good first issue', 'feature request', 'wip', ] def _SCREAMING_SNAKE_CASE () -> List[Any]: """simple docstring""" lowercase__ = Github(os.environ['''GITHUB_TOKEN'''] ) lowercase__ = g.get_repo('''huggingface/accelerate''' ) lowercase__ = repo.get_issues(state='''open''' ) for issue in open_issues: lowercase__ = sorted([comment for comment in issue.get_comments()] , key=lambda A : i.created_at , reverse=A ) lowercase__ = comments[0] if len(A ) > 0 else None lowercase__ = dt.utcnow() lowercase__ = (current_time - issue.updated_at).days lowercase__ = (current_time - issue.created_at).days if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and days_since_updated > 7 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Close issue since it has been 7 days of inactivity since bot mention. issue.edit(state='''closed''' ) elif ( days_since_updated > 23 and days_since_creation >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels() ) ): # Add stale comment issue.create_comment( '''This issue has been automatically marked as stale because it has not had ''' '''recent activity. If you think this still needs to be addressed ''' '''please comment on this thread.\n\nPlease note that issues that do not follow the ''' '''[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) ''' '''are likely to be ignored.''' ) if __name__ == "__main__": main()
2
'''simple docstring''' import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class __lowerCAmelCase : '''simple docstring''' def __init__(self : str , UpperCamelCase : Tuple , UpperCamelCase : Optional[int]=99 , UpperCamelCase : Optional[int]=13 , UpperCamelCase : Tuple=16 , UpperCamelCase : Union[str, Any]=7 , UpperCamelCase : List[Any]=True , UpperCamelCase : List[str]=True , UpperCamelCase : str=True , UpperCamelCase : Tuple=False , UpperCamelCase : str=True , UpperCamelCase : Tuple=2 , UpperCamelCase : Optional[int]=32 , UpperCamelCase : Any=4 , UpperCamelCase : Optional[int]=4 , UpperCamelCase : Tuple=30 , UpperCamelCase : str=0 , UpperCamelCase : Tuple=1 , UpperCamelCase : List[Any]=2 , UpperCamelCase : str=None , ): '''simple docstring''' lowercase__ = parent lowercase__ = batch_size lowercase__ = decoder_seq_length # For common tests lowercase__ = self.decoder_seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = d_model lowercase__ = d_model lowercase__ = decoder_layers lowercase__ = decoder_layers lowercase__ = decoder_ffn_dim lowercase__ = decoder_attention_heads lowercase__ = decoder_attention_heads lowercase__ = eos_token_id lowercase__ = bos_token_id lowercase__ = pad_token_id lowercase__ = decoder_start_token_id lowercase__ = use_cache lowercase__ = max_position_embeddings lowercase__ = None lowercase__ = decoder_seq_length lowercase__ = 2 lowercase__ = 1 def UpperCamelCase__ (self : str ): '''simple docstring''' lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) lowercase__ = None if self.use_labels: lowercase__ = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) lowercase__ = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def UpperCamelCase__ (self : Tuple , UpperCamelCase : List[Any] , UpperCamelCase : Optional[Any] , UpperCamelCase : Tuple , UpperCamelCase : List[str] , ): '''simple docstring''' lowercase__ = True lowercase__ = TrOCRDecoder(config=UpperCamelCase ).to(UpperCamelCase ).eval() lowercase__ = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) lowercase__ = model(UpperCamelCase ) lowercase__ = model(UpperCamelCase , use_cache=UpperCamelCase ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) ) self.parent.assertTrue(len(UpperCamelCase ) == len(UpperCamelCase ) + 1 ) lowercase__ = outputs['''past_key_values'''] # create hypothetical next token and extent to next_input_ids lowercase__ = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and lowercase__ = torch.cat([input_ids, next_tokens] , dim=-1 ) lowercase__ = model(UpperCamelCase )['''last_hidden_state'''] lowercase__ = model(UpperCamelCase , past_key_values=UpperCamelCase )['''last_hidden_state'''] # select random slice lowercase__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowercase__ = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() lowercase__ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = self.prepare_config_and_inputs() lowercase__ ,lowercase__ ,lowercase__ ,lowercase__ = config_and_inputs lowercase__ = {'''input_ids''': input_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_torch class __lowerCAmelCase (lowercase_ , lowercase_ , lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : List[str] = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () lowerCAmelCase__ : List[Any] = (TrOCRForCausalLM,) if is_torch_available() else () lowerCAmelCase__ : Optional[Any] = {"""text-generation""": TrOCRForCausalLM} if is_torch_available() else {} lowerCAmelCase__ : Optional[Any] = True lowerCAmelCase__ : List[str] = False def UpperCamelCase__ (self : Any ): '''simple docstring''' lowercase__ = TrOCRStandaloneDecoderModelTester(self , is_training=UpperCamelCase ) lowercase__ = ConfigTester(self , config_class=UpperCamelCase ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' pass def UpperCamelCase__ (self : Any ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*UpperCamelCase ) def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' return @unittest.skip('''The model doesn\'t support left padding''' ) # and it's not used enough to be worth fixing :) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass
2
1
'''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. lowerCamelCase : 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 ) -> Optional[Any]: """simple docstring""" 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 ) -> Optional[Any]: """simple docstring""" from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(A ) def _SCREAMING_SNAKE_CASE (A ) -> List[Any]: """simple docstring""" from transformers.testing_utils import pytest_terminal_summary_main lowercase__ = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(A , id=A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" if exitstatus == 5: lowercase__ = 0 # Doctest custom flag to ignore output. lowerCamelCase : Optional[Any] = doctest.register_optionflag('IGNORE_RESULT') lowerCamelCase : Optional[Any] = doctest.OutputChecker class __lowerCAmelCase (lowercase_ ): '''simple docstring''' def UpperCamelCase__ (self : Any , UpperCamelCase : Union[str, Any] , UpperCamelCase : Tuple , UpperCamelCase : Optional[Any] ): '''simple docstring''' if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self , UpperCamelCase , UpperCamelCase , UpperCamelCase ) lowerCamelCase : int = CustomOutputChecker lowerCamelCase : List[Any] = HfDoctestModule lowerCamelCase : Any = HfDocTestParser
2
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A ) -> int: """simple docstring""" if not isinstance(A , A ): raise TypeError('''only integers accepted as input''' ) else: lowercase__ = str(abs(A ) ) lowercase__ = [list(A ) for char in range(len(A ) )] for index in range(len(A ) ): num_transpositions[index].pop(A ) return max( int(''''''.join(list(A ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__('doctest').testmod()
2
1
'''simple docstring''' import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCamelCase : List[str] = logging.get_logger(__name__) lowerCamelCase : List[Any] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } lowerCamelCase : List[str] = { 'vocab_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'}, 'merges_file': {'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'}, 'tokenizer_config_file': { 'facebook/blenderbot-3B': 'https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json' }, } lowerCamelCase : Optional[int] = {'facebook/blenderbot-3B': 128} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def _SCREAMING_SNAKE_CASE () -> Optional[int]: """simple docstring""" lowercase__ = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) lowercase__ = bs[:] lowercase__ = 0 for b in range(2**8 ): if b not in bs: bs.append(A ) cs.append(2**8 + n ) n += 1 lowercase__ = [chr(A ) for n in cs] return dict(zip(A , A ) ) def _SCREAMING_SNAKE_CASE (A ) -> Optional[int]: """simple docstring""" lowercase__ = set() lowercase__ = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowercase__ = char return pairs class __lowerCAmelCase (lowercase_ ): '''simple docstring''' lowerCAmelCase__ : int = VOCAB_FILES_NAMES lowerCAmelCase__ : List[str] = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase__ : Optional[int] = ["""input_ids""", """attention_mask"""] def __init__(self : Optional[int] , UpperCamelCase : List[Any] , UpperCamelCase : Any , UpperCamelCase : List[str]="replace" , UpperCamelCase : Any="<s>" , UpperCamelCase : Optional[int]="</s>" , UpperCamelCase : List[str]="</s>" , UpperCamelCase : Dict="<s>" , UpperCamelCase : Tuple="<unk>" , UpperCamelCase : Union[str, Any]="<pad>" , UpperCamelCase : Optional[Any]="<mask>" , UpperCamelCase : str=False , **UpperCamelCase : Union[str, Any] , ): '''simple docstring''' lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else bos_token lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else eos_token lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else sep_token lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else cls_token lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else unk_token lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowercase__ = AddedToken(UpperCamelCase , lstrip=UpperCamelCase , rstrip=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) else mask_token super().__init__( errors=UpperCamelCase , bos_token=UpperCamelCase , eos_token=UpperCamelCase , unk_token=UpperCamelCase , sep_token=UpperCamelCase , cls_token=UpperCamelCase , pad_token=UpperCamelCase , mask_token=UpperCamelCase , add_prefix_space=UpperCamelCase , **UpperCamelCase , ) with open(UpperCamelCase , encoding='''utf-8''' ) as vocab_handle: lowercase__ = json.load(UpperCamelCase ) lowercase__ = {v: k for k, v in self.encoder.items()} lowercase__ = errors # how to handle errors in decoding lowercase__ = bytes_to_unicode() lowercase__ = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase , encoding='''utf-8''' ) as merges_handle: lowercase__ = merges_handle.read().split('''\n''' )[1:-1] lowercase__ = [tuple(merge.split() ) for merge in bpe_merges] lowercase__ = dict(zip(UpperCamelCase , range(len(UpperCamelCase ) ) ) ) lowercase__ = {} lowercase__ = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowercase__ = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def UpperCamelCase__ (self : int ): '''simple docstring''' return len(self.encoder ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' return dict(self.encoder , **self.added_tokens_encoder ) def UpperCamelCase__ (self : str , UpperCamelCase : Tuple ): '''simple docstring''' if token in self.cache: return self.cache[token] lowercase__ = tuple(UpperCamelCase ) lowercase__ = get_pairs(UpperCamelCase ) if not pairs: return token while True: lowercase__ = min(UpperCamelCase , key=lambda UpperCamelCase : self.bpe_ranks.get(UpperCamelCase , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowercase__ ,lowercase__ = bigram lowercase__ = [] lowercase__ = 0 while i < len(UpperCamelCase ): try: lowercase__ = word.index(UpperCamelCase , UpperCamelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowercase__ = j if word[i] == first and i < len(UpperCamelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowercase__ = tuple(UpperCamelCase ) lowercase__ = new_word if len(UpperCamelCase ) == 1: break else: lowercase__ = get_pairs(UpperCamelCase ) lowercase__ = ''' '''.join(UpperCamelCase ) lowercase__ = word return word def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : Any ): '''simple docstring''' lowercase__ = [] for token in re.findall(self.pat , UpperCamelCase ): lowercase__ = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase ).split(''' ''' ) ) return bpe_tokens def UpperCamelCase__ (self : Dict , UpperCamelCase : Optional[int] ): '''simple docstring''' return self.encoder.get(UpperCamelCase , self.encoder.get(self.unk_token ) ) def UpperCamelCase__ (self : Dict , UpperCamelCase : Optional[Any] ): '''simple docstring''' return self.decoder.get(UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : int ): '''simple docstring''' lowercase__ = ''''''.join(UpperCamelCase ) lowercase__ = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def UpperCamelCase__ (self : Optional[int] , UpperCamelCase : str , UpperCamelCase : Optional[str] = None ): '''simple docstring''' if not os.path.isdir(UpperCamelCase ): logger.error(f"Vocabulary path ({save_directory}) should be a directory" ) return lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowercase__ = os.path.join( UpperCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(UpperCamelCase , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase , ensure_ascii=UpperCamelCase ) + '''\n''' ) lowercase__ = 0 with open(UpperCamelCase , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCamelCase : kv[1] ): if index != token_index: logger.warning( f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive." ''' Please check that the tokenizer is not corrupted!''' ) lowercase__ = token_index writer.write(''' '''.join(UpperCamelCase ) + '''\n''' ) index += 1 return vocab_file, merge_file def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None , UpperCamelCase : bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase , token_ids_a=UpperCamelCase , already_has_special_tokens=UpperCamelCase ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase )) + [1] return [1] + ([0] * len(UpperCamelCase )) + [1, 1] + ([0] * len(UpperCamelCase )) + [1] def UpperCamelCase__ (self : Optional[Any] , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [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 : List[Any] , UpperCamelCase : Optional[int] , UpperCamelCase : int=False , **UpperCamelCase : Any ): '''simple docstring''' lowercase__ = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase ) > 0 and not text[0].isspace()): lowercase__ = ''' ''' + text return (text, kwargs) def UpperCamelCase__ (self : str , UpperCamelCase : List[int] , UpperCamelCase : Optional[List[int]] = None ): '''simple docstring''' return token_ids_a + [self.eos_token_id] def UpperCamelCase__ (self : Dict , UpperCamelCase : "Conversation" ): '''simple docstring''' lowercase__ = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(UpperCamelCase ) lowercase__ = ''' '''.join(UpperCamelCase ) lowercase__ = self.encode(UpperCamelCase ) if len(UpperCamelCase ) > self.model_max_length: lowercase__ = input_ids[-self.model_max_length :] logger.warning(f"Trimmed input from conversation as it was longer than {self.model_max_length} tokens." ) return input_ids
2
'''simple docstring''' import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowerCamelCase : str = Mapping[str, np.ndarray] lowerCamelCase : List[Any] = Mapping[str, Any] # Is a nested dict. lowerCamelCase : Any = 0.0_1 @dataclasses.dataclass(frozen=lowercase_ ) class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. lowerCAmelCase__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. lowerCAmelCase__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. lowerCAmelCase__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions lowerCAmelCase__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files lowerCAmelCase__ : Optional[str] = None # Templates used to generate this protein (prediction-only) lowerCAmelCase__ : Optional[Sequence[str]] = None # Chain corresponding to each parent lowerCAmelCase__ : Optional[Sequence[int]] = None def _SCREAMING_SNAKE_CASE (A ) -> Protein: """simple docstring""" lowercase__ = R'''(\[[A-Z]+\]\n)''' lowercase__ = [tag.strip() for tag in re.split(A , A ) if len(A ) > 0] lowercase__ = zip(tags[0::2] , [l.split('''\n''' ) for l in tags[1::2]] ) lowercase__ = ["N", "CA", "C"] lowercase__ = None lowercase__ = None lowercase__ = None for g in groups: if "[PRIMARY]" == g[0]: lowercase__ = g[1][0].strip() for i in range(len(A ) ): if seq[i] not in residue_constants.restypes: lowercase__ = '''X''' # FIXME: strings are immutable lowercase__ = np.array( [residue_constants.restype_order.get(A , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: lowercase__ = [] for axis in range(3 ): tertiary.append(list(map(A , g[1][axis].split() ) ) ) lowercase__ = np.array(A ) lowercase__ = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: lowercase__ = np.array(list(map({'''-''': 0, '''+''': 1}.get , g[1][0].strip() ) ) ) lowercase__ = np.zeros( ( len(A ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(A ): lowercase__ = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=A , atom_mask=A , aatype=A , residue_index=np.arange(len(A ) ) , b_factors=A , ) def _SCREAMING_SNAKE_CASE (A , A = 0 ) -> List[str]: """simple docstring""" lowercase__ = [] lowercase__ = prot.remark if remark is not None: pdb_headers.append(f"REMARK {remark}" ) lowercase__ = prot.parents lowercase__ = prot.parents_chain_index if parents is not None and parents_chain_index is not None: lowercase__ = [p for i, p in zip(A , A ) if i == chain_id] if parents is None or len(A ) == 0: lowercase__ = ['''N/A'''] pdb_headers.append(f"PARENT {' '.join(A )}" ) return pdb_headers def _SCREAMING_SNAKE_CASE (A , A ) -> str: """simple docstring""" lowercase__ = [] lowercase__ = pdb_str.split('''\n''' ) lowercase__ = prot.remark if remark is not None: out_pdb_lines.append(f"REMARK {remark}" ) lowercase__ = 42 if prot.parents is not None and len(prot.parents ) > 0: lowercase__ = [] if prot.parents_chain_index is not None: lowercase__ = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(A ) , [] ) parent_dict[str(A )].append(A ) lowercase__ = max([int(A ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): lowercase__ = parent_dict.get(str(A ) , ['''N/A'''] ) parents_per_chain.append(A ) else: parents_per_chain.append(list(prot.parents ) ) else: lowercase__ = [['''N/A''']] def make_parent_line(A ) -> str: return f"PARENT {' '.join(A )}" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) lowercase__ = 0 for i, l in enumerate(A ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(A ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(A ): lowercase__ = parents_per_chain[chain_counter] else: lowercase__ = ['''N/A'''] out_pdb_lines.append(make_parent_line(A ) ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> str: """simple docstring""" lowercase__ = residue_constants.restypes + ['''X'''] def res_atoa(A ) -> str: return residue_constants.restype_atoa.get(restypes[r] , '''UNK''' ) lowercase__ = residue_constants.atom_types lowercase__ = [] lowercase__ = prot.atom_mask lowercase__ = prot.aatype lowercase__ = prot.atom_positions lowercase__ = prot.residue_index.astype(np.intaa ) lowercase__ = prot.b_factors lowercase__ = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('''Invalid aatypes.''' ) lowercase__ = get_pdb_headers(A ) if len(A ) > 0: pdb_lines.extend(A ) lowercase__ = aatype.shape[0] lowercase__ = 1 lowercase__ = 0 lowercase__ = string.ascii_uppercase lowercase__ = None # Add all atom sites. for i in range(A ): lowercase__ = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(A , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue lowercase__ = '''ATOM''' lowercase__ = atom_name if len(A ) == 4 else f" {atom_name}" lowercase__ = '''''' lowercase__ = '''''' lowercase__ = 1.00 lowercase__ = atom_name[0] # Protein supports only C, N, O, S, this works. lowercase__ = '''''' lowercase__ = '''A''' if chain_index is not None: lowercase__ = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! lowercase__ = ( f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}" f"{res_name_a:>3} {chain_tag:>1}" f"{residue_index[i]:>4}{insertion_code:>1} " f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}" f"{occupancy:>6.2f}{b_factor:>6.2f} " f"{element:>2}{charge:>2}" ) pdb_lines.append(A ) atom_index += 1 lowercase__ = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: lowercase__ = True lowercase__ = chain_index[i + 1] if should_terminate: # Close the chain. lowercase__ = '''TER''' lowercase__ = ( f"{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}" ) pdb_lines.append(A ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(A , A ) ) pdb_lines.append('''END''' ) pdb_lines.append('''''' ) return "\n".join(A ) def _SCREAMING_SNAKE_CASE (A ) -> np.ndarray: """simple docstring""" return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def _SCREAMING_SNAKE_CASE (A , A , A = None , A = None , A = None , A = None , A = None , ) -> Protein: """simple docstring""" return Protein( aatype=features['''aatype'''] , atom_positions=result['''final_atom_positions'''] , atom_mask=result['''final_atom_mask'''] , residue_index=features['''residue_index'''] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['''final_atom_mask'''] ) , chain_index=A , remark=A , parents=A , parents_chain_index=A , )
2
1