code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import unittest from transformers import DonutProcessor _lowerCamelCase = 'naver-clova-ix/donut-base' class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = DonutProcessor.from_pretrained(__A ) def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = { """name""": """John Doe""", """age""": """99""", """city""": """Atlanta""", """state""": """GA""", """zip""": """30301""", """phone""": """123-4567""", """nicknames""": [{"""nickname""": """Johnny"""}, {"""nickname""": """JD"""}], } SCREAMING_SNAKE_CASE__ = ( """<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>""" ) SCREAMING_SNAKE_CASE__ = self.processor.tokenajson(__A ) self.assertDictEqual(__A , __A )
59
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
1
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :Union[str, "sqlalchemy.sql.Selectable"] , __A :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __A :Optional[Features] = None , __A :str = None , __A :bool = False , **__A :Dict , ) -> Any: """simple docstring""" super().__init__(features=__A , cache_dir=__A , keep_in_memory=__A , **__A ) SCREAMING_SNAKE_CASE__ = Sql( cache_dir=__A , features=__A , sql=__A , con=__A , **__A , ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None self.builder.download_and_prepare( download_config=__A , download_mode=__A , verification_mode=__A , base_path=__A , ) # Build dataset for splits SCREAMING_SNAKE_CASE__ = self.builder.as_dataset( split="""train""" , verification_mode=__A , in_memory=self.keep_in_memory ) return dataset class UpperCamelCase_ : def __init__( self :List[Any] , __A :Dataset , __A :str , __A :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , __A :Optional[int] = None , __A :Optional[int] = None , **__A :List[str] , ) -> Optional[Any]: """simple docstring""" if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) SCREAMING_SNAKE_CASE__ = dataset SCREAMING_SNAKE_CASE__ = name SCREAMING_SNAKE_CASE__ = con SCREAMING_SNAKE_CASE__ = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE SCREAMING_SNAKE_CASE__ = num_proc SCREAMING_SNAKE_CASE__ = to_sql_kwargs def _snake_case ( self :Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.to_sql_kwargs.pop("""sql""" , __A ) SCREAMING_SNAKE_CASE__ = self.to_sql_kwargs.pop("""con""" , __A ) SCREAMING_SNAKE_CASE__ = self.to_sql_kwargs.pop("""index""" , __A ) SCREAMING_SNAKE_CASE__ = self._write(index=__A , **self.to_sql_kwargs ) return written def _snake_case ( self :Dict , __A :Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs SCREAMING_SNAKE_CASE__ = query_table( table=self.dataset.data , key=slice(__A , offset + self.batch_size ) , indices=self.dataset._indices , ) SCREAMING_SNAKE_CASE__ = batch.to_pandas() SCREAMING_SNAKE_CASE__ = df.to_sql(self.name , self.con , index=__A , **__A ) return num_rows or len(__A ) def _snake_case ( self :List[str] , __A :Optional[int] , **__A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , __A , __A )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ): written += num_rows return written
59
# 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 = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
1
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0, 0 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 for _ in range(1 , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ugly_nums.append(UpperCamelCase__ ) if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F'''{ugly_numbers(200) = }''')
59
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
1
import os import time import warnings from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import logging from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors from ..processors.utils import InputFeatures _lowerCamelCase = logging.get_logger(__name__) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field(metadata={"help": "The name of the task to train on: " + ", ".join(glue_processors.keys() )} ) lowerCamelCase_ = field( metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."} ) lowerCamelCase_ = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.task_name.lower() class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "train" lowerCamelCase_ = "dev" lowerCamelCase_ = "test" class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :GlueDataTrainingArguments , __A :PreTrainedTokenizerBase , __A :Optional[int] = None , __A :Union[str, Split] = Split.train , __A :Optional[str] = None , ) -> List[Any]: """simple docstring""" warnings.warn( """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """ """library. You can have a look at this example script for pointers: """ """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , __A , ) SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = glue_processors[args.task_name]() SCREAMING_SNAKE_CASE__ = glue_output_modes[args.task_name] if isinstance(__A , __A ): try: SCREAMING_SNAKE_CASE__ = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) # Load data features from cache or dataset file SCREAMING_SNAKE_CASE__ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}''' , ) SCREAMING_SNAKE_CASE__ = self.processor.get_labels() if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in ( "RobertaTokenizer", "RobertaTokenizerFast", "XLMRobertaTokenizer", "BartTokenizer", "BartTokenizerFast", ): # HACK(label indices are swapped in RoBERTa pretrained model) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = label_list[2], label_list[1] SCREAMING_SNAKE_CASE__ = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE__ = cached_features_file + """.lock""" with FileLock(__A ): if os.path.exists(__A ) and not args.overwrite_cache: SCREAMING_SNAKE_CASE__ = time.time() SCREAMING_SNAKE_CASE__ = torch.load(__A ) logger.info( f'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start ) else: logger.info(f'''Creating features from dataset file at {args.data_dir}''' ) if mode == Split.dev: SCREAMING_SNAKE_CASE__ = self.processor.get_dev_examples(args.data_dir ) elif mode == Split.test: SCREAMING_SNAKE_CASE__ = self.processor.get_test_examples(args.data_dir ) else: SCREAMING_SNAKE_CASE__ = self.processor.get_train_examples(args.data_dir ) if limit_length is not None: SCREAMING_SNAKE_CASE__ = examples[:limit_length] SCREAMING_SNAKE_CASE__ = glue_convert_examples_to_features( __A , __A , max_length=args.max_seq_length , label_list=__A , output_mode=self.output_mode , ) SCREAMING_SNAKE_CASE__ = time.time() torch.save(self.features , __A ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self :List[Any] ) -> str: """simple docstring""" return len(self.features ) def __getitem__( self :Union[str, Any] , __A :Union[str, Any] ) -> InputFeatures: """simple docstring""" return self.features[i] def _snake_case ( self :int ) -> Union[str, Any]: """simple docstring""" return self.label_list
59
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
1
import re from filelock import FileLock try: import nltk _lowerCamelCase = True except (ImportError, ModuleNotFoundError): _lowerCamelCase = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): re.sub("""<n>""" , """""" , UpperCamelCase__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(UpperCamelCase__ ) )
59
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
1
_lowerCamelCase = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict , UpperCamelCase__: Dict , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE__ = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE__ = queue.pop(0 ) # get the last node from the path SCREAMING_SNAKE_CASE__ = path[-1] if node not in explored: SCREAMING_SNAKE_CASE__ = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE__ = list(UpperCamelCase__ ) new_path.append(UpperCamelCase__ ) queue.append(UpperCamelCase__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(UpperCamelCase__ ) # in case there's no path between the 2 nodes return [] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict , UpperCamelCase__: List[Any] , UpperCamelCase__: Any ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE__ = [start] SCREAMING_SNAKE_CASE__ = set(UpperCamelCase__ ) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE__ = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE__ = queue.pop(0 ) if node == target: SCREAMING_SNAKE_CASE__ = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(UpperCamelCase__ ) queue.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
59
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict ): SCREAMING_SNAKE_CASE__ = set() # To detect a back edge, keep track of vertices currently in the recursion stack SCREAMING_SNAKE_CASE__ = set() return any( node not in visited and depth_first_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for node in graph ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict , UpperCamelCase__: int , UpperCamelCase__: set , UpperCamelCase__: set ): visited.add(UpperCamelCase__ ) rec_stk.add(UpperCamelCase__ ) for node in graph[vertex]: if node not in visited: if depth_first_search(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(UpperCamelCase__ ) return False if __name__ == "__main__": from doctest import testmod testmod()
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "facebook/bart-large-mnli" lowerCamelCase_ = ( "This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which " "should be the text to classify, and `labels`, which should be the list of labels to use for classification. " "It returns the most likely label in the list of provided `labels` for the input text." ) lowerCamelCase_ = "text_classifier" lowerCamelCase_ = AutoTokenizer lowerCamelCase_ = AutoModelForSequenceClassification lowerCamelCase_ = ["text", ["text"]] lowerCamelCase_ = ["text"] def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" super().setup() SCREAMING_SNAKE_CASE__ = self.model.config SCREAMING_SNAKE_CASE__ = -1 for idx, label in config.idalabel.items(): if label.lower().startswith("""entail""" ): SCREAMING_SNAKE_CASE__ = int(__A ) if self.entailment_id == -1: raise ValueError("""Could not determine the entailment ID from the model config, please pass it at init.""" ) def _snake_case ( self :Union[str, Any] , __A :Optional[int] , __A :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = labels return self.pre_processor( [text] * len(__A ) , [f'''This example is {label}''' for label in labels] , return_tensors="""pt""" , padding="""max_length""" , ) def _snake_case ( self :Tuple , __A :Optional[int] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = outputs.logits SCREAMING_SNAKE_CASE__ = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
59
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
1
import functools import logging import os import sys import threading from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional import huggingface_hub.utils as hf_hub_utils from tqdm import auto as tqdm_lib _lowerCamelCase = threading.Lock() _lowerCamelCase = None _lowerCamelCase = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } _lowerCamelCase = logging.WARNING _lowerCamelCase = True def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = os.getenv("""TRANSFORMERS_VERBOSITY""" , UpperCamelCase__ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( f'''Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, ''' f'''has to be one of: { ', '.join(log_levels.keys() ) }''' ) return _default_log_level def SCREAMING_SNAKE_CASE__ ( ): return __name__.split(""".""" )[0] def SCREAMING_SNAKE_CASE__ ( ): return logging.getLogger(_get_library_name() ) def SCREAMING_SNAKE_CASE__ ( ): global _default_handler with _lock: if _default_handler: # This library has already configured the library root logger. return SCREAMING_SNAKE_CASE__ = logging.StreamHandler() # Set sys.stderr as stream. SCREAMING_SNAKE_CASE__ = sys.stderr.flush # Apply our default configuration to the library root logger. SCREAMING_SNAKE_CASE__ = _get_library_root_logger() library_root_logger.addHandler(_default_handler ) library_root_logger.setLevel(_get_default_logging_level() ) SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( ): global _default_handler with _lock: if not _default_handler: return SCREAMING_SNAKE_CASE__ = _get_library_root_logger() library_root_logger.removeHandler(_default_handler ) library_root_logger.setLevel(logging.NOTSET ) SCREAMING_SNAKE_CASE__ = None def SCREAMING_SNAKE_CASE__ ( ): return log_levels def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[str] = None ): if name is None: SCREAMING_SNAKE_CASE__ = _get_library_name() _configure_library_root_logger() return logging.getLogger(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): _configure_library_root_logger() return _get_library_root_logger().getEffectiveLevel() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): _configure_library_root_logger() _get_library_root_logger().setLevel(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): return set_verbosity(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): return set_verbosity(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): return set_verbosity(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): return set_verbosity(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().removeHandler(_default_handler ) def SCREAMING_SNAKE_CASE__ ( ): _configure_library_root_logger() assert _default_handler is not None _get_library_root_logger().addHandler(_default_handler ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: logging.Handler ): _configure_library_root_logger() assert handler is not None _get_library_root_logger().addHandler(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: logging.Handler ): _configure_library_root_logger() assert handler is not None and handler not in _get_library_root_logger().handlers _get_library_root_logger().removeHandler(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE__ = False def SCREAMING_SNAKE_CASE__ ( ): _configure_library_root_logger() SCREAMING_SNAKE_CASE__ = True def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = _get_library_root_logger().handlers for handler in handlers: SCREAMING_SNAKE_CASE__ = logging.Formatter("""[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s""" ) handler.setFormatter(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = _get_library_root_logger().handlers for handler in handlers: handler.setFormatter(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self: str , *UpperCamelCase__: Any , **UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = os.getenv("""TRANSFORMERS_NO_ADVISORY_WARNINGS""" , UpperCamelCase__ ) if no_advisory_warnings: return self.warning(*UpperCamelCase__ , **UpperCamelCase__ ) _lowerCamelCase = warning_advice @functools.lru_cache(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self: Dict , *UpperCamelCase__: str , **UpperCamelCase__: Optional[int] ): self.warning(*UpperCamelCase__ , **UpperCamelCase__ ) _lowerCamelCase = warning_once class UpperCamelCase_ : def __init__( self :List[str] , *__A :Optional[Any] , **__A :Tuple ) -> str: # pylint: disable=unused-argument """simple docstring""" SCREAMING_SNAKE_CASE__ = args[0] if args else None def __iter__( self :Any ) -> List[str]: """simple docstring""" return iter(self._iterator ) def __getattr__( self :Union[str, Any] , __A :Union[str, Any] ) -> List[Any]: """simple docstring""" def empty_fn(*__A :Optional[Any] , **__A :Optional[Any] ): # pylint: disable=unused-argument return return empty_fn def __enter__( self :Any ) -> str: """simple docstring""" return self def __exit__( self :List[str] , __A :Optional[int] , __A :List[str] , __A :str ) -> Any: """simple docstring""" return class UpperCamelCase_ : def __call__( self :List[Any] , *__A :Tuple , **__A :Any ) -> List[Any]: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm(*__A , **__A ) else: return EmptyTqdm(*__A , **__A ) def _snake_case ( self :Tuple , *__A :List[Any] , **__A :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*__A , **__A ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() _lowerCamelCase = _tqdm_cls() def SCREAMING_SNAKE_CASE__ ( ): global _tqdm_active return bool(_tqdm_active ) def SCREAMING_SNAKE_CASE__ ( ): global _tqdm_active SCREAMING_SNAKE_CASE__ = True hf_hub_utils.enable_progress_bars() def SCREAMING_SNAKE_CASE__ ( ): global _tqdm_active SCREAMING_SNAKE_CASE__ = False hf_hub_utils.disable_progress_bars()
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
1
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__A , """tf_padding""" ) ) self.parent.assertTrue(hasattr(__A , """depth_multiplier""" ) ) class UpperCamelCase_ : def __init__( self :List[str] , __A :Optional[int] , __A :int=13 , __A :Union[str, Any]=3 , __A :Tuple=32 , __A :Union[str, Any]=0.2_5 , __A :List[Any]=8 , __A :Dict=True , __A :List[Any]=1024 , __A :Dict=32 , __A :Optional[int]="relu6" , __A :Optional[Any]=0.1 , __A :Any=0.0_2 , __A :Tuple=True , __A :int=True , __A :Optional[int]=10 , __A :List[Any]=None , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = depth_multiplier SCREAMING_SNAKE_CASE__ = min_depth SCREAMING_SNAKE_CASE__ = tf_padding SCREAMING_SNAKE_CASE__ = int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE__ = output_stride SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = classifier_dropout_prob SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values, labels, pixel_labels def _snake_case ( self :Dict ) -> int: """simple docstring""" return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _snake_case ( self :Optional[int] , __A :Any , __A :Optional[int] , __A :int , __A :Dict ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileNetVaModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _snake_case ( self :List[str] , __A :Optional[int] , __A :int , __A :Optional[int] , __A :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = MobileNetVaForImageClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowerCamelCase_ = ( {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE__ = MobileNetVaConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds""" ) def _snake_case ( self :Dict ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings""" ) def _snake_case ( self :Optional[int] ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""MobileNetV1 does not output attentions""" ) def _snake_case ( self :Any ) -> int: """simple docstring""" pass def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _snake_case ( self :int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" def check_hidden_states_output(__A :Optional[Any] , __A :Optional[int] , __A :List[str] ): SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.hidden_states SCREAMING_SNAKE_CASE__ = 26 self.assertEqual(len(__A ) , __A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @slow def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = MobileNetVaModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" return ( MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224""" ) if is_vision_available() else None ) @slow def _snake_case ( self :Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224""" ).to(__A ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ).to(__A ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**__A ) # verify the logits SCREAMING_SNAKE_CASE__ = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
59
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int] , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) # Initialize Result SCREAMING_SNAKE_CASE__ = [] # Traverse through all denomination for denomination in reversed(UpperCamelCase__ ): # Find denominations while int(UpperCamelCase__ ) >= int(UpperCamelCase__ ): total_value -= int(UpperCamelCase__ ) answer.append(UpperCamelCase__ ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": _lowerCamelCase = [] _lowerCamelCase = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): _lowerCamelCase = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(F'''Denomination {i}: ''').strip())) _lowerCamelCase = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter _lowerCamelCase = [1, 2, 5, 10, 20, 50, 100, 500, 2000] _lowerCamelCase = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(F'''Following is minimal change for {value}: ''') _lowerCamelCase = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
59
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
1
import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = AutoencoderKL lowerCamelCase_ = "sample" lowerCamelCase_ = 1e-2 @property def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = (32, 32) SCREAMING_SNAKE_CASE__ = floats_tensor((batch_size, num_channels) + sizes ).to(__A ) return {"sample": image} @property def _snake_case ( self :Any ) -> List[Any]: """simple docstring""" return (3, 32, 32) @property def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" return (3, 32, 32) def _snake_case ( self :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = { """block_out_channels""": [32, 64], """in_channels""": 3, """out_channels""": 3, """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""], """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""], """latent_channels""": 4, } SCREAMING_SNAKE_CASE__ = self.dummy_input return init_dict, inputs_dict def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> List[Any]: """simple docstring""" pass @unittest.skipIf(torch_device == """mps""" , """Gradient checkpointing skipped on MPS""" ) def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = self.model_class(**__A ) model.to(__A ) assert not model.is_gradient_checkpointing and model.training SCREAMING_SNAKE_CASE__ = model(**__A ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() SCREAMING_SNAKE_CASE__ = torch.randn_like(__A ) SCREAMING_SNAKE_CASE__ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing SCREAMING_SNAKE_CASE__ = self.model_class(**__A ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__A ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training SCREAMING_SNAKE_CASE__ = model_a(**__A ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() SCREAMING_SNAKE_CASE__ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) SCREAMING_SNAKE_CASE__ = dict(model.named_parameters() ) SCREAMING_SNAKE_CASE__ = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def _snake_case ( self :Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" , output_loading_info=__A ) self.assertIsNotNone(__A ) self.assertEqual(len(loading_info["""missing_keys"""] ) , 0 ) model.to(__A ) SCREAMING_SNAKE_CASE__ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained("""fusing/autoencoder-kl-dummy""" ) SCREAMING_SNAKE_CASE__ = model.to(__A ) model.eval() if torch_device == "mps": SCREAMING_SNAKE_CASE__ = torch.manual_seed(0 ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) SCREAMING_SNAKE_CASE__ = image.to(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , sample_posterior=__A , generator=__A ).sample SCREAMING_SNAKE_CASE__ = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": SCREAMING_SNAKE_CASE__ = torch.tensor( [ -4.0_078E-01, -3.8_323E-04, -1.2_681E-01, -1.1_462E-01, 2.0_095E-01, 1.0_893E-01, -8.8_247E-02, -3.0_361E-01, -9.8_644E-03, ] ) elif torch_device == "cpu": SCREAMING_SNAKE_CASE__ = torch.tensor( [-0.1_3_5_2, 0.0_8_7_8, 0.0_4_1_9, -0.0_8_1_8, -0.1_0_6_9, 0.0_6_8_8, -0.1_4_5_8, -0.4_4_4_6, -0.0_0_2_6] ) else: SCREAMING_SNAKE_CASE__ = torch.tensor( [-0.2_4_2_1, 0.4_6_4_2, 0.2_5_0_7, -0.0_4_3_8, 0.0_6_8_2, 0.3_1_6_0, -0.2_0_1_8, -0.0_7_2_7, 0.2_4_8_5] ) self.assertTrue(torch_all_close(__A , __A , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[int] , __A :int , __A :Optional[Any] ) -> Tuple: """simple docstring""" return f'''gaussian_noise_s={seed}_shape={'_'.join([str(__A ) for s in shape] )}.npy''' def _snake_case ( self :List[str] ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :int , __A :Any=0 , __A :List[str]=(4, 3, 512, 512) , __A :int=False ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.floataa if fpaa else torch.floataa SCREAMING_SNAKE_CASE__ = torch.from_numpy(load_hf_numpy(self.get_file_format(__A , __A ) ) ).to(__A ).to(__A ) return image def _snake_case ( self :Tuple , __A :int="CompVis/stable-diffusion-v1-4" , __A :Any=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """fp16""" if fpaa else None SCREAMING_SNAKE_CASE__ = torch.floataa if fpaa else torch.floataa SCREAMING_SNAKE_CASE__ = AutoencoderKL.from_pretrained( __A , subfolder="""vae""" , torch_dtype=__A , revision=__A , ) model.to(__A ).eval() return model def _snake_case ( self :Optional[int] , __A :Optional[Any]=0 ) -> Optional[int]: """simple docstring""" if torch_device == "mps": return torch.manual_seed(__A ) return torch.Generator(device=__A ).manual_seed(__A ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_3, 0.9_8_7_8, -0.0_4_9_5, -0.0_7_9_0, -0.2_7_0_9, 0.8_3_7_5, -0.2_0_6_0, -0.0_8_2_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_6, 0.1_1_6_8, 0.1_3_3_2, -0.4_8_4_0, -0.2_5_0_8, -0.0_7_9_1, -0.0_4_9_3, -0.4_0_8_9], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _snake_case ( self :List[Any] , __A :int , __A :str , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , generator=__A , sample_posterior=__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(__A , __A , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.0_5_1_3, 0.0_2_8_9, 1.3_7_9_9, 0.2_1_6_6, -0.2_5_7_3, -0.0_8_7_1, 0.5_1_0_3, -0.0_9_9_9]], [47, [-0.4_1_2_8, -0.1_3_2_0, -0.3_7_0_4, 0.1_9_6_5, -0.4_1_1_6, -0.2_3_3_2, -0.3_3_4_0, 0.2_2_4_7]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :str , __A :Optional[Any] , __A :Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A , generator=__A , sample_posterior=__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.1_6_0_9, 0.9_8_6_6, -0.0_4_8_7, -0.0_7_7_7, -0.2_7_1_6, 0.8_3_6_8, -0.2_0_5_5, -0.0_8_1_4], [-0.2_3_9_5, 0.0_0_9_8, 0.0_1_0_2, -0.0_7_0_9, -0.2_8_4_0, -0.0_2_7_4, -0.0_7_1_8, -0.1_8_2_4]], [47, [-0.2_3_7_7, 0.1_1_4_7, 0.1_3_3_3, -0.4_8_4_1, -0.2_5_0_6, -0.0_8_0_5, -0.0_4_9_1, -0.4_0_8_5], [0.0_3_5_0, 0.0_8_4_7, 0.0_4_6_7, 0.0_3_4_4, -0.0_8_4_2, -0.0_5_4_7, -0.0_6_3_3, -0.1_1_3_1]], # fmt: on ] ) def _snake_case ( self :Any , __A :Tuple , __A :List[str] , __A :str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A ).sample assert sample.shape == image.shape SCREAMING_SNAKE_CASE__ = sample[-1, -2:, -2:, :2].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(expected_slice_mps if torch_device == """mps""" else expected_slice ) assert torch_all_close(__A , __A , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.2_0_5_1, -0.1_8_0_3, -0.2_3_1_1, -0.2_1_1_4, -0.3_2_9_2, -0.3_5_7_4, -0.2_9_5_3, -0.3_3_2_3]], [37, [-0.2_6_3_2, -0.2_6_2_5, -0.2_1_9_9, -0.2_7_4_1, -0.4_5_3_9, -0.4_9_9_0, -0.3_7_2_0, -0.4_9_2_5]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :Dict , __A :Any , __A :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.0_3_6_9, 0.0_2_0_7, -0.0_7_7_6, -0.0_6_8_2, -0.1_7_4_7, -0.1_9_3_0, -0.1_4_6_5, -0.2_0_3_9]], [16, [-0.1_6_2_8, -0.2_1_3_4, -0.2_7_4_7, -0.2_6_4_2, -0.3_7_7_4, -0.4_4_0_4, -0.3_6_8_7, -0.4_2_7_7]], # fmt: on ] ) @require_torch_gpu def _snake_case ( self :int , __A :Any , __A :Optional[int] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] SCREAMING_SNAKE_CASE__ = sample[-1, -2:, :2, -2:].flatten().float().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) assert torch_all_close(__A , __A , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def _snake_case ( self :Optional[int] , __A :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model(fpaa=__A ) SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) , fpaa=__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__A , __A , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="""xformers is not required when using PyTorch 2.0.""" ) def _snake_case ( self :str , __A :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A , shape=(3, 4, 64, 64) ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.decode(__A ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__A , __A , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.3_0_0_1, 0.0_9_1_8, -2.6_9_8_4, -3.9_7_2_0, -3.2_0_9_9, -5.0_3_5_3, 1.7_3_3_8, -0.2_0_6_5, 3.4_2_6_7]], [47, [-1.5_0_3_0, -4.3_8_7_1, -6.0_3_5_5, -9.1_1_5_7, -1.6_6_6_1, -2.7_8_5_3, 2.1_6_0_7, -5.0_8_2_3, 2.5_6_3_3]], # fmt: on ] ) def _snake_case ( self :Tuple , __A :Union[str, Any] , __A :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_sd_vae_model() SCREAMING_SNAKE_CASE__ = self.get_sd_image(__A ) SCREAMING_SNAKE_CASE__ = self.get_generator(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model.encode(__A ).latent_dist SCREAMING_SNAKE_CASE__ = dist.sample(generator=__A ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] SCREAMING_SNAKE_CASE__ = sample[0, -1, -3:, -3:].flatten().cpu() SCREAMING_SNAKE_CASE__ = torch.tensor(__A ) SCREAMING_SNAKE_CASE__ = 3E-3 if torch_device != """mps""" else 1E-2 assert torch_all_close(__A , __A , atol=__A )
59
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _snake_case ( self :int ) -> str: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "Salesforce/blip-image-captioning-base" lowerCamelCase_ = ( "This is a tool that generates a description of an image. It takes an input named `image` which should be the " "image to caption, and returns a text that contains the description in English." ) lowerCamelCase_ = "image_captioner" lowerCamelCase_ = AutoModelForVisionaSeq lowerCamelCase_ = ["image"] lowerCamelCase_ = ["text"] def __init__( self :Tuple , *__A :str , **__A :Tuple ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["""vision"""] ) super().__init__(*__A , **__A ) def _snake_case ( self :Optional[int] , __A :"Image" ) -> List[Any]: """simple docstring""" return self.pre_processor(images=__A , return_tensors="""pt""" ) def _snake_case ( self :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.model.generate(**__A ) def _snake_case ( self :Tuple , __A :List[str] ) -> Dict: """simple docstring""" return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0].strip()
59
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'facebook/deit-base-distilled-patch16-224': ( 'https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "deit" def __init__( self :List[Any] , __A :Dict=768 , __A :List[Any]=12 , __A :Tuple=12 , __A :Union[str, Any]=3072 , __A :str="gelu" , __A :str=0.0 , __A :Dict=0.0 , __A :List[str]=0.0_2 , __A :int=1E-12 , __A :Tuple=224 , __A :Any=16 , __A :List[str]=3 , __A :List[Any]=True , __A :Optional[int]=16 , **__A :str , ) -> List[str]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = encoder_stride class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = version.parse("1.11" ) @property def _snake_case ( self :int ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _snake_case ( self :Dict ) -> float: """simple docstring""" return 1E-4
59
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
1
import numpy as np from transformers import Pipeline def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = np.max(UpperCamelCase__ , axis=-1 , keepdims=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :List[Any] , **__A :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = {} if "second_text" in kwargs: SCREAMING_SNAKE_CASE__ = kwargs["""second_text"""] return preprocess_kwargs, {}, {} def _snake_case ( self :Union[str, Any] , __A :Any , __A :Optional[int]=None ) -> Optional[Any]: """simple docstring""" return self.tokenizer(__A , text_pair=__A , return_tensors=self.framework ) def _snake_case ( self :Any , __A :Optional[int] ) -> Any: """simple docstring""" return self.model(**__A ) def _snake_case ( self :int , __A :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = model_outputs.logits[0].numpy() SCREAMING_SNAKE_CASE__ = softmax(__A ) SCREAMING_SNAKE_CASE__ = np.argmax(__A ) SCREAMING_SNAKE_CASE__ = self.model.config.idalabel[best_class] SCREAMING_SNAKE_CASE__ = probabilities[best_class].item() SCREAMING_SNAKE_CASE__ = logits.tolist() return {"label": label, "score": score, "logits": logits}
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoImageProcessor, ViTImageProcessor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / 'utils')) from test_module.custom_image_processing import CustomImageProcessor # noqa E402 _lowerCamelCase = get_tests_dir('fixtures') class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = mock.Mock() SCREAMING_SNAKE_CASE__ = 500 SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = HTTPError SCREAMING_SNAKE_CASE__ = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("""requests.Session.request""" , return_value=__A ) as mock_head: SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""hf-internal-testing/tiny-random-vit""" ) # This check we did call the fake head request mock_head.assert_called() def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained( """https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json""" ) def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" with self.assertRaises(__A ): # config is in subfolder, the following should not work without specifying the subfolder SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained("""hf-internal-testing/stable-diffusion-all-variants""" ) SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained( """hf-internal-testing/stable-diffusion-all-variants""" , subfolder="""feature_extractor""" ) self.assertIsNotNone(__A ) @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): @classmethod def _snake_case ( cls :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls :Optional[int] ) -> Optional[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-image-processor""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-image-processor-org""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""test-dynamic-image-processor""" ) except HTTPError: pass def _snake_case ( self :Tuple ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""test-image-processor""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __A , repo_id="""test-image-processor""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(f'''{USER}/test-image-processor''' ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""valid_org/test-image-processor""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-image-processor""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained( __A , repo_id="""valid_org/test-image-processor-org""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor.from_pretrained("""valid_org/test-image-processor-org""" ) for k, v in image_processor.__dict__.items(): self.assertEqual(__A , getattr(__A , __A ) ) def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" CustomImageProcessor.register_for_auto_class() SCREAMING_SNAKE_CASE__ = CustomImageProcessor.from_pretrained(__A ) image_processor.push_to_hub("""test-dynamic-image-processor""" , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( image_processor.auto_map , {"""AutoImageProcessor""": """custom_image_processing.CustomImageProcessor"""} , ) SCREAMING_SNAKE_CASE__ = AutoImageProcessor.from_pretrained( f'''{USER}/test-dynamic-image-processor''' , trust_remote_code=__A ) # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module self.assertEqual(new_image_processor.__class__.__name__ , """CustomImageProcessor""" )
59
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Tuple ): return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Any=0 ): return sorted(UpperCamelCase__ , key=lambda UpperCamelCase__ : x[column] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict , UpperCamelCase__: Tuple=float("""inf""" ) ): for i in range(points_counts - 1 ): for j in range(i + 1 , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: SCREAMING_SNAKE_CASE__ = current_dis return min_dis def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: int=float("""inf""" ) ): for i in range(min(6 , points_counts - 1 ) , UpperCamelCase__ ): for j in range(max(0 , i - 6 ) , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: SCREAMING_SNAKE_CASE__ = current_dis return min_dis def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: int , UpperCamelCase__: Any ): # base case if points_counts <= 3: return dis_between_closest_pair(UpperCamelCase__ , UpperCamelCase__ ) # recursion SCREAMING_SNAKE_CASE__ = points_counts // 2 SCREAMING_SNAKE_CASE__ = closest_pair_of_points_sqr( UpperCamelCase__ , points_sorted_on_y[:mid] , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = closest_pair_of_points_sqr( UpperCamelCase__ , points_sorted_on_y[mid:] , points_counts - mid ) SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dis_between_closest_in_strip( UpperCamelCase__ , len(UpperCamelCase__ ) , UpperCamelCase__ ) return min(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = column_based_sort(UpperCamelCase__ , column=0 ) SCREAMING_SNAKE_CASE__ = column_based_sort(UpperCamelCase__ , column=1 ) return ( closest_pair_of_points_sqr( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ) ** 0.5 if __name__ == "__main__": _lowerCamelCase = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print('Distance:', closest_pair_of_points(points, len(points)))
59
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
1
from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
59
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
1
import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__A , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(__A , """num_attention_heads""" ) ) self.parent.assertTrue(hasattr(__A , """num_encoder_blocks""" ) ) class UpperCamelCase_ : def __init__( self :List[str] , __A :Optional[Any] , __A :Tuple=13 , __A :List[Any]=64 , __A :int=3 , __A :Dict=4 , __A :str=[2, 2, 2, 2] , __A :Optional[Any]=[8, 4, 2, 1] , __A :str=[16, 32, 64, 128] , __A :Any=[1, 4, 8, 16] , __A :Tuple=[1, 2, 4, 8] , __A :List[Any]=True , __A :List[str]=True , __A :str="gelu" , __A :str=0.1 , __A :Dict=0.1 , __A :Optional[Any]=0.0_2 , __A :Union[str, Any]=3 , __A :Any=None , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = num_encoder_blocks SCREAMING_SNAKE_CASE__ = sr_ratios SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = downsampling_rates SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values, labels def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def _snake_case ( self :Optional[int] , __A :Tuple , __A :Optional[int] , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = SegformerModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def _snake_case ( self :Tuple , __A :Optional[Any] , __A :Any , __A :Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = SegformerForSemanticSegmentation(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def _snake_case ( self :Optional[int] , __A :List[Any] , __A :int , __A :List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = SegformerForSemanticSegmentation(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(__A ) SCREAMING_SNAKE_CASE__ = model(__A , labels=__A ) self.parent.assertGreater(result.loss , 0.0 ) def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) lowerCamelCase_ = ( { "feature-extraction": SegformerModel, "image-classification": SegformerForImageClassification, "image-segmentation": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = SegformerModelTester(self ) SCREAMING_SNAKE_CASE__ = SegformerConfigTester(self , config_class=__A ) def _snake_case ( self :Any ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*__A ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*__A ) @unittest.skip("""SegFormer does not use inputs_embeds""" ) def _snake_case ( self :List[str] ) -> Optional[Any]: """simple docstring""" pass @unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods""" ) def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" pass def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _snake_case ( self :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.attentions SCREAMING_SNAKE_CASE__ = sum(self.model_tester.depths ) self.assertEqual(len(__A ) , __A ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.attentions self.assertEqual(len(__A ) , __A ) # verify the first attentions (first block, first layer) SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // 4) ** 2 SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // 32) ** 2 SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) SCREAMING_SNAKE_CASE__ = len(__A ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) self.assertEqual(out_len + 1 , len(__A ) ) SCREAMING_SNAKE_CASE__ = outputs.attentions self.assertEqual(len(__A ) , __A ) # verify the first attentions (first block, first layer) SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // 4) ** 2 SCREAMING_SNAKE_CASE__ = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" def check_hidden_states_output(__A :Optional[Any] , __A :str , __A :List[str] ): SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.hidden_states SCREAMING_SNAKE_CASE__ = self.model_tester.num_encoder_blocks self.assertEqual(len(__A ) , __A ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = True for model_class in self.all_model_classes: if model_class in get_values(__A ): continue SCREAMING_SNAKE_CASE__ = model_class(__A ) model.to(__A ) model.train() SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A , return_labels=__A ) SCREAMING_SNAKE_CASE__ = model(**__A ).loss loss.backward() @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _snake_case ( self :str ) -> int: """simple docstring""" pass @slow def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ = SegformerModel.from_pretrained(__A ) self.assertIsNotNone(__A ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__A , align=__A , do_random_crop=__A ) SCREAMING_SNAKE_CASE__ = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __A ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = encoded_inputs.pixel_values.to(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [ [[-4.6_3_1_0, -5.5_2_3_2, -6.2_3_5_6], [-5.1_9_2_1, -6.1_4_4_4, -6.5_9_9_6], [-5.4_4_2_4, -6.2_7_9_0, -6.7_5_7_4]], [[-1_2.1_3_9_1, -1_3.3_1_2_2, -1_3.9_5_5_4], [-1_2.8_7_3_2, -1_3.9_3_5_2, -1_4.3_5_6_3], [-1_2.9_4_3_8, -1_3.8_2_2_6, -1_4.2_5_1_3]], [[-1_2.5_1_3_4, -1_3.4_6_8_6, -1_4.4_9_1_5], [-1_2.8_6_6_9, -1_4.4_3_4_3, -1_4.7_7_5_8], [-1_3.2_5_2_3, -1_4.5_8_1_9, -1_5.0_6_9_4]], ] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __A , atol=1E-4 ) ) @slow def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__A , align=__A , do_random_crop=__A ) SCREAMING_SNAKE_CASE__ = SegformerForSemanticSegmentation.from_pretrained( """nvidia/segformer-b1-finetuned-cityscapes-1024-1024""" ).to(__A ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = encoded_inputs.pixel_values.to(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = torch.tensor( [ [[-1_3.5_7_4_8, -1_3.9_1_1_1, -1_2.6_5_0_0], [-1_4.3_5_0_0, -1_5.3_6_8_3, -1_4.2_3_2_8], [-1_4.7_5_3_2, -1_6.0_4_2_4, -1_5.6_0_8_7]], [[-1_7.1_6_5_1, -1_5.8_7_2_5, -1_2.9_6_5_3], [-1_7.2_5_8_0, -1_7.3_7_1_8, -1_4.8_2_2_3], [-1_6.6_0_5_8, -1_6.8_7_8_3, -1_6.7_4_5_2]], [[-3.6_4_5_6, -3.0_2_0_9, -1.4_2_0_3], [-3.0_7_9_7, -3.1_9_5_9, -2.0_0_0_0], [-1.8_7_5_7, -1.9_2_1_7, -1.6_9_9_7]], ] ).to(__A ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , __A , atol=1E-1 ) ) @slow def _snake_case ( self :Optional[int] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__A , align=__A , do_random_crop=__A ) SCREAMING_SNAKE_CASE__ = SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512""" ).to( __A ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = encoded_inputs.pixel_values.to(__A ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ = image_processor.post_process_semantic_segmentation(outputs=__A , target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE__ = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , __A ) SCREAMING_SNAKE_CASE__ = image_processor.post_process_semantic_segmentation(outputs=__A ) SCREAMING_SNAKE_CASE__ = torch.Size((128, 128) ) self.assertEqual(segmentation[0].shape , __A )
59
# 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 = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } _lowerCamelCase = { 'distilbert-base-uncased': 512, 'distilbert-base-uncased-distilled-squad': 512, 'distilbert-base-cased': 512, 'distilbert-base-cased-distilled-squad': 512, 'distilbert-base-german-cased': 512, 'distilbert-base-multilingual-cased': 512, } _lowerCamelCase = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = DistilBertTokenizer def __init__( self :Any , __A :Dict=None , __A :Any=None , __A :List[Any]=True , __A :str="[UNK]" , __A :Dict="[SEP]" , __A :Tuple="[PAD]" , __A :Any="[CLS]" , __A :Union[str, Any]="[MASK]" , __A :Any=True , __A :Tuple=None , **__A :Optional[Any] , ) -> Tuple: """simple docstring""" super().__init__( __A , tokenizer_file=__A , do_lower_case=__A , unk_token=__A , sep_token=__A , pad_token=__A , cls_token=__A , mask_token=__A , tokenize_chinese_chars=__A , strip_accents=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , __A ) != do_lower_case or normalizer_state.get("""strip_accents""" , __A ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , __A ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE__ = getattr(__A , normalizer_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = do_lower_case SCREAMING_SNAKE_CASE__ = strip_accents SCREAMING_SNAKE_CASE__ = tokenize_chinese_chars SCREAMING_SNAKE_CASE__ = normalizer_class(**__A ) SCREAMING_SNAKE_CASE__ = do_lower_case def _snake_case ( self :Any , __A :Tuple , __A :str=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case ( self :Union[str, Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A )
59
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
1
import unittest from transformers import SPIECE_UNDERLINE from transformers.models.speechta import SpeechTaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.tokenization_utils import AddedToken from ...test_tokenization_common import TokenizerTesterMixin _lowerCamelCase = get_tests_dir('fixtures/test_sentencepiece_bpe_char.model') @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = SpeechTaTokenizer lowerCamelCase_ = False lowerCamelCase_ = True def _snake_case ( self :Tuple ) -> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ = SpeechTaTokenizer(__A ) SCREAMING_SNAKE_CASE__ = AddedToken("""<mask>""" , lstrip=__A , rstrip=__A ) SCREAMING_SNAKE_CASE__ = mask_token tokenizer.add_special_tokens({"""mask_token""": mask_token} ) tokenizer.add_tokens(["""<ctc_blank>"""] ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self :int , __A :int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """this is a test""" SCREAMING_SNAKE_CASE__ = """this is a test""" return input_text, output_text def _snake_case ( self :Tuple , __A :Optional[Any] , __A :Union[str, Any]=False , __A :List[str]=20 , __A :List[str]=5 ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.get_input_output_texts(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.decode(__A , clean_up_tokenization_spaces=__A ) return text, ids def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """<pad>""" SCREAMING_SNAKE_CASE__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__A ) , __A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__A ) , __A ) def _snake_case ( self :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-4] , """œ""" ) self.assertEqual(vocab_keys[-2] , """<mask>""" ) self.assertEqual(vocab_keys[-1] , """<ctc_blank>""" ) self.assertEqual(len(__A ) , 81 ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 79 ) def _snake_case ( self :Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = tokenizer.vocab_size SCREAMING_SNAKE_CASE__ = len(__A ) self.assertNotEqual(__A , 0 ) # We usually have added tokens from the start in tests because our vocab fixtures are # smaller than the original vocabs - let's not assert this # self.assertEqual(vocab_size, all_size) SCREAMING_SNAKE_CASE__ = ["""aaaaa bbbbbb""", """cccccccccdddddddd"""] SCREAMING_SNAKE_CASE__ = tokenizer.add_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.vocab_size SCREAMING_SNAKE_CASE__ = len(__A ) self.assertNotEqual(__A , 0 ) self.assertEqual(__A , __A ) self.assertEqual(__A , len(__A ) ) self.assertEqual(__A , all_size + len(__A ) ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""aaaaa bbbbbb low cccccccccdddddddd l""" , add_special_tokens=__A ) self.assertGreaterEqual(len(__A ) , 4 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) SCREAMING_SNAKE_CASE__ = {"""eos_token""": """>>>>|||<||<<|<<""", """pad_token""": """<<<<<|||>|>>>>|>"""} SCREAMING_SNAKE_CASE__ = tokenizer.add_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.vocab_size SCREAMING_SNAKE_CASE__ = len(__A ) self.assertNotEqual(__A , 0 ) self.assertEqual(__A , __A ) self.assertEqual(__A , len(__A ) ) self.assertEqual(__A , all_size_a + len(__A ) ) SCREAMING_SNAKE_CASE__ = tokenizer.encode( """>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l""" , add_special_tokens=__A ) self.assertGreaterEqual(len(__A ) , 6 ) self.assertGreater(tokens[0] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[0] , tokens[1] ) self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1 ) self.assertGreater(tokens[-3] , tokens[-4] ) self.assertEqual(tokens[0] , tokenizer.eos_token_id ) self.assertEqual(tokens[-3] , tokenizer.pad_token_id ) def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" pass def _snake_case ( self :Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""This is a test""" ) # fmt: off self.assertListEqual(__A , [SPIECE_UNDERLINE, """T""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """a""", SPIECE_UNDERLINE, """t""", """e""", """s""", """t"""] ) # fmt: on self.assertListEqual( tokenizer.convert_tokens_to_ids(__A ) , [4, 32, 11, 10, 12, 4, 10, 12, 4, 7, 4, 6, 5, 12, 6] , ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( __A , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """92000""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) # fmt: off self.assertListEqual(__A , [4, 30, 4, 20, 7, 12, 4, 25, 8, 13, 9, 4, 10, 9, 4, 3, 23, 4, 7, 9, 14, 4, 6, 11, 10, 12, 4, 10, 12, 4, 19, 7, 15, 12, 73, 26] ) # fmt: on SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(__A ) self.assertListEqual( __A , [SPIECE_UNDERLINE, """I""", SPIECE_UNDERLINE, """w""", """a""", """s""", SPIECE_UNDERLINE, """b""", """o""", """r""", """n""", SPIECE_UNDERLINE, """i""", """n""", SPIECE_UNDERLINE, """<unk>""", """,""", SPIECE_UNDERLINE, """a""", """n""", """d""", SPIECE_UNDERLINE, """t""", """h""", """i""", """s""", SPIECE_UNDERLINE, """i""", """s""", SPIECE_UNDERLINE, """f""", """a""", """l""", """s""", """é""", """."""] ) @slow def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [ """Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides """ """general-purpose architectures (BERT, GPT, RoBERTa, XLM, DistilBert, XLNet...) for Natural """ """Language Understanding (NLU) and Natural Language Generation (NLG) with over thirty-two pretrained """ """models in one hundred plus languages and deep interoperability between Jax, PyTorch and TensorFlow.""", """BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly """ """conditioning on both left and right context in all layers.""", """The quick brown fox jumps over the lazy dog.""", ] # fmt: off SCREAMING_SNAKE_CASE__ = { """input_ids""": [ [4, 32, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 64, 19, 8, 13, 18, 5, 13, 15, 22, 4, 28, 9, 8, 20, 9, 4, 7, 12, 4, 24, 22, 6, 8, 13, 17, 11, 39, 6, 13, 7, 9, 12, 19, 8, 13, 18, 5, 13, 12, 4, 7, 9, 14, 4, 24, 22, 6, 8, 13, 17, 11, 39, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 39, 25, 5, 13, 6, 63, 4, 24, 13, 8, 27, 10, 14, 5, 12, 4, 21, 5, 9, 5, 13, 7, 15, 39, 24, 16, 13, 24, 8, 12, 5, 4, 7, 13, 17, 11, 10, 6, 5, 17, 6, 16, 13, 5, 12, 4, 64, 40, 47, 54, 32, 23, 4, 53, 49, 32, 23, 4, 54, 8, 40, 47, 54, 32, 7, 23, 4, 69, 52, 43, 23, 4, 51, 10, 12, 6, 10, 15, 40, 5, 13, 6, 23, 4, 69, 52, 48, 5, 6, 26, 26, 26, 63, 4, 19, 8, 13, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 61, 9, 14, 5, 13, 12, 6, 7, 9, 14, 10, 9, 21, 4, 64, 48, 52, 61, 63, 4, 7, 9, 14, 4, 48, 7, 6, 16, 13, 7, 15, 4, 52, 7, 9, 21, 16, 7, 21, 5, 4, 53, 5, 9, 5, 13, 7, 6, 10, 8, 9, 4, 64, 48, 52, 53, 63, 4, 20, 10, 6, 11, 4, 8, 27, 5, 13, 4, 6, 11, 10, 13, 6, 22, 39, 6, 20, 8, 4, 24, 13, 5, 6, 13, 7, 10, 9, 5, 14, 4, 18, 8, 14, 5, 15, 12, 4, 10, 9, 4, 8, 9, 5, 4, 11, 16, 9, 14, 13, 5, 14, 4, 24, 15, 16, 12, 4, 15, 7, 9, 21, 16, 7, 21, 5, 12, 4, 7, 9, 14, 4, 14, 5, 5, 24, 4, 10, 9, 6, 5, 13, 8, 24, 5, 13, 7, 25, 10, 15, 10, 6, 22, 4, 25, 5, 6, 20, 5, 5, 9, 4, 58, 7, 37, 23, 4, 49, 22, 32, 8, 13, 17, 11, 4, 7, 9, 14, 4, 32, 5, 9, 12, 8, 13, 55, 15, 8, 20, 26, 2], [4, 40, 47, 54, 32, 4, 10, 12, 4, 14, 5, 12, 10, 21, 9, 5, 14, 4, 6, 8, 4, 24, 13, 5, 39, 6, 13, 7, 10, 9, 4, 14, 5, 5, 24, 4, 25, 10, 14, 10, 13, 5, 17, 6, 10, 8, 9, 7, 15, 4, 13, 5, 24, 13, 5, 12, 5, 9, 6, 7, 6, 10, 8, 9, 12, 4, 19, 13, 8, 18, 4, 16, 9, 15, 7, 25, 5, 15, 5, 14, 4, 6, 5, 37, 6, 4, 25, 22, 4, 46, 8, 10, 9, 6, 15, 22, 4, 17, 8, 9, 14, 10, 6, 10, 8, 9, 10, 9, 21, 4, 8, 9, 4, 25, 8, 6, 11, 4, 15, 5, 19, 6, 4, 7, 9, 14, 4, 13, 10, 21, 11, 6, 4, 17, 8, 9, 6, 5, 37, 6, 4, 10, 9, 4, 7, 15, 15, 4, 15, 7, 22, 5, 13, 12, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [4, 32, 11, 5, 4, 45, 16, 10, 17, 28, 4, 25, 13, 8, 20, 9, 4, 19, 8, 37, 4, 46, 16, 18, 24, 12, 4, 8, 27, 5, 13, 4, 6, 11, 5, 4, 15, 7, 57, 22, 4, 14, 8, 21, 26, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ], """attention_mask""": [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ] } # fmt: on self.tokenizer_integration_test_util( expected_encoding=__A , model_name="""microsoft/speecht5_asr""" , revision="""c5ef64c71905caeccde0e4462ef3f9077224c524""" , sequences=__A , )
59
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
1
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 = logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase = 256 class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["melgan"] def __init__( self :str , __A :SpectrogramNotesEncoder , __A :SpectrogramContEncoder , __A :TaFilmDecoder , __A :DDPMScheduler , __A :OnnxRuntimeModel if is_onnx_available() else Any , ) -> None: """simple docstring""" super().__init__() # From MELGAN SCREAMING_SNAKE_CASE__ = math.log(1E-5 ) # Matches MelGAN training. SCREAMING_SNAKE_CASE__ = 4.0 # Largest value for most examples SCREAMING_SNAKE_CASE__ = 128 self.register_modules( notes_encoder=__A , continuous_encoder=__A , decoder=__A , scheduler=__A , melgan=__A , ) def _snake_case ( self :Any , __A :Tuple , __A :Tuple=(-1.0, 1.0) , __A :Tuple=False ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = output_range if clip: SCREAMING_SNAKE_CASE__ = torch.clip(__A , self.min_value , self.max_value ) # Scale to [0, 1]. SCREAMING_SNAKE_CASE__ = (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 _snake_case ( self :Any , __A :Union[str, Any] , __A :Any=(-1.0, 1.0) , __A :Optional[int]=False ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = input_range SCREAMING_SNAKE_CASE__ = torch.clip(__A , __A , __A ) if clip else outputs # Scale to [0, 1]. SCREAMING_SNAKE_CASE__ = (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 _snake_case ( self :Any , __A :Tuple , __A :List[Any] , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = input_tokens > 0 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.notes_encoder( encoder_input_tokens=__A , encoder_inputs_mask=__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.continuous_encoder( encoder_inputs=__A , encoder_inputs_mask=__A ) return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)] def _snake_case ( self :Union[str, Any] , __A :List[Any] , __A :Optional[Any] , __A :Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = noise_time if not torch.is_tensor(__A ): SCREAMING_SNAKE_CASE__ = torch.tensor([timesteps] , dtype=torch.long , device=input_tokens.device ) elif torch.is_tensor(__A ) and len(timesteps.shape ) == 0: SCREAMING_SNAKE_CASE__ = timesteps[None].to(input_tokens.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML SCREAMING_SNAKE_CASE__ = timesteps * torch.ones(input_tokens.shape[0] , dtype=timesteps.dtype , device=timesteps.device ) SCREAMING_SNAKE_CASE__ = self.decoder( encodings_and_masks=__A , decoder_input_tokens=__A , decoder_noise_time=__A ) return logits @torch.no_grad() def __call__( self :Tuple , __A :List[List[int]] , __A :Optional[torch.Generator] = None , __A :int = 100 , __A :bool = True , __A :str = "numpy" , __A :Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __A :int = 1 , ) -> Union[AudioPipelineOutput, Tuple]: """simple docstring""" if (callback_steps is None) or ( callback_steps is not None and (not isinstance(__A , __A ) or callback_steps <= 0) ): raise ValueError( f'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' f''' {type(__A )}.''' ) SCREAMING_SNAKE_CASE__ = np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ = np.zeros([1, 0, self.n_dims] , np.floataa ) SCREAMING_SNAKE_CASE__ = torch.ones((1, TARGET_FEATURE_LENGTH) , dtype=__A , device=self.device ) for i, encoder_input_tokens in enumerate(__A ): if i == 0: SCREAMING_SNAKE_CASE__ = torch.from_numpy(pred_mel[:1].copy() ).to( device=self.device , dtype=self.decoder.dtype ) # The first chunk has no previous context. SCREAMING_SNAKE_CASE__ = torch.zeros((1, TARGET_FEATURE_LENGTH) , dtype=__A , 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. SCREAMING_SNAKE_CASE__ = ones SCREAMING_SNAKE_CASE__ = self.scale_features( __A , output_range=[-1.0, 1.0] , clip=__A ) SCREAMING_SNAKE_CASE__ = self.encode( input_tokens=torch.IntTensor([encoder_input_tokens] ).to(device=self.device ) , continuous_inputs=__A , continuous_mask=__A , ) # Sample encoder_continuous_inputs shaped gaussian noise to begin loop SCREAMING_SNAKE_CASE__ = randn_tensor( shape=encoder_continuous_inputs.shape , generator=__A , device=self.device , dtype=self.decoder.dtype , ) # set step values self.scheduler.set_timesteps(__A ) # Denoising diffusion loop for j, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): SCREAMING_SNAKE_CASE__ = self.decode( encodings_and_masks=__A , input_tokens=__A , noise_time=t / self.scheduler.config.num_train_timesteps , ) # Compute previous output: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , generator=__A ).prev_sample SCREAMING_SNAKE_CASE__ = self.scale_to_features(__A , input_range=[-1.0, 1.0] ) SCREAMING_SNAKE_CASE__ = mel[:1] SCREAMING_SNAKE_CASE__ = mel.cpu().float().numpy() SCREAMING_SNAKE_CASE__ = 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(__A , __A ) logger.info("""Generated segment""" , __A ) 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": SCREAMING_SNAKE_CASE__ = self.melgan(input_features=full_pred_mel.astype(np.floataa ) ) else: SCREAMING_SNAKE_CASE__ = full_pred_mel if not return_dict: return (output,) return AudioPipelineOutput(audios=__A )
59
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
1
from __future__ import annotations import unittest from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel @require_tf class UpperCamelCase_ : lowerCamelCase_ = BlenderbotSmallConfig lowerCamelCase_ = {} lowerCamelCase_ = "gelu" def __init__( self :Optional[Any] , __A :Optional[int] , __A :Union[str, Any]=13 , __A :Tuple=7 , __A :Optional[int]=True , __A :int=False , __A :Optional[int]=99 , __A :List[Any]=32 , __A :Dict=2 , __A :List[str]=4 , __A :List[Any]=37 , __A :List[Any]=0.1 , __A :Union[str, Any]=0.1 , __A :Union[str, Any]=20 , __A :Optional[int]=2 , __A :Dict=1 , __A :Optional[Any]=0 , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = pad_token_id SCREAMING_SNAKE_CASE__ = bos_token_id def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) SCREAMING_SNAKE_CASE__ = tf.concat([input_ids, eos_tensor] , axis=1 ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = 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 , ) SCREAMING_SNAKE_CASE__ = prepare_blenderbot_small_inputs_dict(__A , __A , __A ) return config, inputs_dict def _snake_case ( self :Dict , __A :int , __A :Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFBlenderbotSmallModel(config=__A ).get_decoder() SCREAMING_SNAKE_CASE__ = inputs_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids[:1, :] SCREAMING_SNAKE_CASE__ = inputs_dict["""attention_mask"""][:1, :] SCREAMING_SNAKE_CASE__ = inputs_dict["""head_mask"""] SCREAMING_SNAKE_CASE__ = 1 # first forward pass SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , head_mask=__A , use_cache=__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and SCREAMING_SNAKE_CASE__ = tf.concat([input_ids, next_tokens] , axis=-1 ) SCREAMING_SNAKE_CASE__ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A )[0] SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , past_key_values=__A )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice SCREAMING_SNAKE_CASE__ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) SCREAMING_SNAKE_CASE__ = output_from_no_past[:, -3:, random_slice_idx] SCREAMING_SNAKE_CASE__ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__A , __A , rtol=1E-3 ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: int=None , UpperCamelCase__: Union[str, Any]=None , UpperCamelCase__: List[str]=None , UpperCamelCase__: Optional[int]=None , ): if attention_mask is None: SCREAMING_SNAKE_CASE__ = tf.cast(tf.math.not_equal(UpperCamelCase__ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__ = 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: SCREAMING_SNAKE_CASE__ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__ = 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 UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else () ) lowerCamelCase_ = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else () lowerCamelCase_ = ( { "conversational": TFBlenderbotSmallForConditionalGeneration, "feature-extraction": TFBlenderbotSmallModel, "summarization": TFBlenderbotSmallForConditionalGeneration, "text2text-generation": TFBlenderbotSmallForConditionalGeneration, "translation": TFBlenderbotSmallForConditionalGeneration, } if is_tf_available() else {} ) lowerCamelCase_ = True lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFBlenderbotSmallModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A ) def _snake_case ( self :Optional[Any] ) -> int: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__A ) @require_tokenizers @require_tf class UpperCamelCase_ ( unittest.TestCase ): lowerCamelCase_ = [ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like " " i'm going to throw up.\nand why is that?" ] lowerCamelCase_ = "facebook/blenderbot_small-90M" @cached_property def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" return BlenderbotSmallTokenizer.from_pretrained("""facebook/blenderbot-90M""" ) @cached_property def _snake_case ( self :Optional[int] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def _snake_case ( self :List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer(self.src_text , return_tensors="""tf""" ) SCREAMING_SNAKE_CASE__ = self.model.generate( model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , use_cache=__A , ) SCREAMING_SNAKE_CASE__ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__A )[0] assert generated_words in ( "i don't know. i just feel like i'm going to throw up. it's not fun.", "i'm not sure. i just feel like i've been feeling like i have to be in a certain place", "i'm not sure. i just feel like i've been in a bad situation.", )
59
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
1
import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} _lowerCamelCase = { 'tokenizer_file': { 'EleutherAI/gpt-neox-20b': 'https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json', }, } _lowerCamelCase = { 'gpt-neox-20b': 2048, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = ["input_ids", "attention_mask"] def __init__( self :str , __A :Dict=None , __A :Tuple=None , __A :Union[str, Any]=None , __A :List[Any]="<|endoftext|>" , __A :int="<|endoftext|>" , __A :Tuple="<|endoftext|>" , __A :Optional[int]=False , **__A :int , ) -> Tuple: """simple docstring""" super().__init__( __A , __A , tokenizer_file=__A , unk_token=__A , bos_token=__A , eos_token=__A , add_prefix_space=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(__A , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**__A ) SCREAMING_SNAKE_CASE__ = add_prefix_space def _snake_case ( self :Dict , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def _snake_case ( self :Optional[int] , __A :"Conversation" ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__A , add_special_tokens=__A ) + [self.eos_token_id] ) if len(__A ) > self.model_max_length: SCREAMING_SNAKE_CASE__ = input_ids[-self.model_max_length :] return input_ids
59
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
1
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: ndarray ): return np.dot(UpperCamelCase__ , UpperCamelCase__ ) class UpperCamelCase_ : def __init__( self :str , *, __A :float = np.inf , __A :str = "linear" , __A :float = 0.0 , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = regularization SCREAMING_SNAKE_CASE__ = gamma if kernel == "linear": SCREAMING_SNAKE_CASE__ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("""rbf kernel requires gamma""" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("""gamma must be float or int""" ) if not self.gamma > 0: raise ValueError("""gamma must be > 0""" ) SCREAMING_SNAKE_CASE__ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: SCREAMING_SNAKE_CASE__ = f'''Unknown kernel: {kernel}''' raise ValueError(__A ) def _snake_case ( self :Dict , __A :ndarray , __A :ndarray ) -> float: """simple docstring""" return np.dot(__A , __A ) def _snake_case ( self :List[Any] , __A :ndarray , __A :ndarray ) -> float: """simple docstring""" return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _snake_case ( self :Tuple , __A :list[ndarray] , __A :ndarray ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = observations SCREAMING_SNAKE_CASE__ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((SCREAMING_SNAKE_CASE__) , ) = np.shape(__A ) def to_minimize(__A :ndarray ) -> float: SCREAMING_SNAKE_CASE__ = 0 ((SCREAMING_SNAKE_CASE__) , ) = np.shape(__A ) for i in range(__A ): for j in range(__A ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__A ) SCREAMING_SNAKE_CASE__ = LinearConstraint(__A , 0 , 0 ) SCREAMING_SNAKE_CASE__ = Bounds(0 , self.regularization ) SCREAMING_SNAKE_CASE__ = minimize( __A , np.ones(__A ) , bounds=__A , constraints=[ly_contraint] ).x SCREAMING_SNAKE_CASE__ = l_star # calculating mean offset of separation plane to points SCREAMING_SNAKE_CASE__ = 0 for i in range(__A ): for j in range(__A ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) SCREAMING_SNAKE_CASE__ = s / n def _snake_case ( self :Optional[int] , __A :ndarray ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __A ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
59
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
1
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = None class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = 2 @register_to_config def __init__( self :Any , __A :float = 0.0_2 , __A :float = 100 , __A :float = 1.0_0_7 , __A :float = 80 , __A :float = 0.0_5 , __A :float = 50 , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sigma_max # setable values SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # sigma(t_i) def _snake_case ( self :Optional[int] , __A :torch.FloatTensor , __A :Optional[int] = None ) -> torch.FloatTensor: """simple docstring""" return sample def _snake_case ( self :Union[str, Any] , __A :int , __A :Union[str, torch.device] = None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = num_inference_steps SCREAMING_SNAKE_CASE__ = np.arange(0 , self.num_inference_steps )[::-1].copy() SCREAMING_SNAKE_CASE__ = torch.from_numpy(__A ).to(__A ) SCREAMING_SNAKE_CASE__ = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] SCREAMING_SNAKE_CASE__ = torch.tensor(__A , dtype=torch.floataa , device=__A ) def _snake_case ( self :List[Any] , __A :torch.FloatTensor , __A :float , __A :Optional[torch.Generator] = None ) -> Tuple[torch.FloatTensor, float]: """simple docstring""" if self.config.s_min <= sigma <= self.config.s_max: SCREAMING_SNAKE_CASE__ = min(self.config.s_churn / self.num_inference_steps , 2**0.5 - 1 ) else: SCREAMING_SNAKE_CASE__ = 0 # sample eps ~ N(0, S_noise^2 * I) SCREAMING_SNAKE_CASE__ = self.config.s_noise * randn_tensor(sample.shape , generator=__A ).to(sample.device ) SCREAMING_SNAKE_CASE__ = sigma + gamma * sigma SCREAMING_SNAKE_CASE__ = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def _snake_case ( self :Optional[int] , __A :torch.FloatTensor , __A :float , __A :float , __A :torch.FloatTensor , __A :bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample_hat + sigma_hat * model_output SCREAMING_SNAKE_CASE__ = (sample_hat - pred_original_sample) / sigma_hat SCREAMING_SNAKE_CASE__ = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__A , derivative=__A , pred_original_sample=__A ) def _snake_case ( self :List[Any] , __A :torch.FloatTensor , __A :float , __A :float , __A :torch.FloatTensor , __A :torch.FloatTensor , __A :torch.FloatTensor , __A :bool = True , ) -> Union[KarrasVeOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = sample_prev + sigma_prev * model_output SCREAMING_SNAKE_CASE__ = (sample_prev - pred_original_sample) / sigma_prev SCREAMING_SNAKE_CASE__ = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=__A , derivative=__A , pred_original_sample=__A ) def _snake_case ( self :str , __A :str , __A :Dict , __A :Tuple ) -> Any: """simple docstring""" raise NotImplementedError()
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = [int(UpperCamelCase__ ) for i in ip_va_address.split(""".""" ) if i.isdigit()] return len(UpperCamelCase__ ) == 4 and all(0 <= int(UpperCamelCase__ ) <= 254 for octet in octets ) if __name__ == "__main__": _lowerCamelCase = input().strip() _lowerCamelCase = 'valid' if is_ip_va_address_valid(ip) else 'invalid' print(F'''{ip} is a {valid_or_invalid} IP v4 address.''')
59
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
1
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) _lowerCamelCase = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) _lowerCamelCase = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) _lowerCamelCase = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) _lowerCamelCase = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) _lowerCamelCase = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) _lowerCamelCase = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) _lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) _lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) _lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) _lowerCamelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) _lowerCamelCase = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModel) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_PRETRAINING_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_MASKED_LM_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING _lowerCamelCase = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class UpperCamelCase_ ( _BaseAutoModelClass ): lowerCamelCase_ = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING _lowerCamelCase = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
1
from __future__ import annotations class UpperCamelCase_ : def __init__( self :List[str] , __A :int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = order # a_{0} ... a_{k} SCREAMING_SNAKE_CASE__ = [1.0] + [0.0] * order # b_{0} ... b_{k} SCREAMING_SNAKE_CASE__ = [1.0] + [0.0] * order # x[n-1] ... x[n-k] SCREAMING_SNAKE_CASE__ = [0.0] * self.order # y[n-1] ... y[n-k] SCREAMING_SNAKE_CASE__ = [0.0] * self.order def _snake_case ( self :Optional[int] , __A :list[float] , __A :list[float] ) -> None: """simple docstring""" if len(__A ) < self.order: SCREAMING_SNAKE_CASE__ = [1.0, *a_coeffs] if len(__A ) != self.order + 1: SCREAMING_SNAKE_CASE__ = ( f'''Expected a_coeffs to have {self.order + 1} elements ''' f'''for {self.order}-order filter, got {len(__A )}''' ) raise ValueError(__A ) if len(__A ) != self.order + 1: SCREAMING_SNAKE_CASE__ = ( f'''Expected b_coeffs to have {self.order + 1} elements ''' f'''for {self.order}-order filter, got {len(__A )}''' ) raise ValueError(__A ) SCREAMING_SNAKE_CASE__ = a_coeffs SCREAMING_SNAKE_CASE__ = b_coeffs def _snake_case ( self :List[Any] , __A :float ) -> float: """simple docstring""" SCREAMING_SNAKE_CASE__ = 0.0 # Start at index 1 and do index 0 at the end. for i in range(1 , self.order + 1 ): result += ( self.b_coeffs[i] * self.input_history[i - 1] - self.a_coeffs[i] * self.output_history[i - 1] ) SCREAMING_SNAKE_CASE__ = (result + self.b_coeffs[0] * sample) / self.a_coeffs[0] SCREAMING_SNAKE_CASE__ = self.input_history[:-1] SCREAMING_SNAKE_CASE__ = self.output_history[:-1] SCREAMING_SNAKE_CASE__ = sample SCREAMING_SNAKE_CASE__ = result return result
59
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
1
from collections.abc import Sequence def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Sequence[float] , UpperCamelCase__: bool = False ): if not arr: return 0 SCREAMING_SNAKE_CASE__ = 0 if allow_empty_subarrays else float("""-inf""" ) SCREAMING_SNAKE_CASE__ = 0.0 for num in arr: SCREAMING_SNAKE_CASE__ = max(0 if allow_empty_subarrays else num , curr_sum + num ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ , UpperCamelCase__ ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() _lowerCamelCase = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(F'''{max_subarray_sum(nums) = }''')
59
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
1
import numpy as np from nltk.translate import meteor_score import datasets from datasets.config import importlib_metadata, version _lowerCamelCase = version.parse(importlib_metadata.version('nltk')) if NLTK_VERSION >= version.Version('3.6.4'): from nltk import word_tokenize _lowerCamelCase = '\\n@inproceedings{banarjee2005,\n title = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},\n author = {Banerjee, Satanjeev and Lavie, Alon},\n booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},\n month = jun,\n year = {2005},\n address = {Ann Arbor, Michigan},\n publisher = {Association for Computational Linguistics},\n url = {https://www.aclweb.org/anthology/W05-0909},\n pages = {65--72},\n}\n' _lowerCamelCase = '\\nMETEOR, an automatic metric for machine translation evaluation\nthat is based on a generalized concept of unigram matching between the\nmachine-produced translation and human-produced reference translations.\nUnigrams can be matched based on their surface forms, stemmed forms,\nand meanings; furthermore, METEOR can be easily extended to include more\nadvanced matching strategies. Once all generalized unigram matches\nbetween the two strings have been found, METEOR computes a score for\nthis matching using a combination of unigram-precision, unigram-recall, and\na measure of fragmentation that is designed to directly capture how\nwell-ordered the matched words in the machine translation are in relation\nto the reference.\n\nMETEOR gets an R correlation value of 0.347 with human evaluation on the Arabic\ndata and 0.331 on the Chinese data. This is shown to be an improvement on\nusing simply unigram-precision, unigram-recall and their harmonic F1\ncombination.\n' _lowerCamelCase = '\nComputes METEOR score of translated segments against one or more references.\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n alpha: Parameter for controlling relative weights of precision and recall. default: 0.9\n beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3\n gamma: Relative weight assigned to fragmentation penalty. default: 0.5\nReturns:\n \'meteor\': meteor score.\nExamples:\n\n >>> meteor = datasets.load_metric(\'meteor\')\n >>> predictions = ["It is a guide to action which ensures that the military always obeys the commands of the party"]\n >>> references = ["It is a guide to action that ensures that the military will forever heed Party commands"]\n >>> results = meteor.compute(predictions=predictions, references=references)\n >>> print(round(results["meteor"], 4))\n 0.6944\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCamelCase_ ( datasets.Metric ): def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py"""] , reference_urls=[ """https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score""", """https://en.wikipedia.org/wiki/METEOR""", ] , ) def _snake_case ( self :Dict , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" import nltk nltk.download("""wordnet""" ) if NLTK_VERSION >= version.Version("""3.6.5""" ): nltk.download("""punkt""" ) if NLTK_VERSION >= version.Version("""3.6.6""" ): nltk.download("""omw-1.4""" ) def _snake_case ( self :int , __A :Any , __A :Optional[Any] , __A :Optional[int]=0.9 , __A :List[str]=3 , __A :Any=0.5 ) -> Optional[Any]: """simple docstring""" if NLTK_VERSION >= version.Version("""3.6.5""" ): SCREAMING_SNAKE_CASE__ = [ meteor_score.single_meteor_score( word_tokenize(__A ) , word_tokenize(__A ) , alpha=__A , beta=__A , gamma=__A ) for ref, pred in zip(__A , __A ) ] else: SCREAMING_SNAKE_CASE__ = [ meteor_score.single_meteor_score(__A , __A , alpha=__A , beta=__A , gamma=__A ) for ref, pred in zip(__A , __A ) ] return {"meteor": np.mean(__A )}
59
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] , UpperCamelCase__: List[Any]=False ): SCREAMING_SNAKE_CASE__ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''module.blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''module.blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ("""module.cls_token""", """vit.embeddings.cls_token"""), ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""), ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""), ("""module.pos_embed""", """vit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""module.norm.weight""", """layernorm.weight"""), ("""module.norm.bias""", """layernorm.bias"""), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE__ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("""norm.weight""", """vit.layernorm.weight"""), ("""norm.bias""", """vit.layernorm.bias"""), ("""head.weight""", """classifier.weight"""), ("""head.bias""", """classifier.bias"""), ] ) return rename_keys def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[Any]=False ): for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ = """""" else: SCREAMING_SNAKE_CASE__ = """vit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''module.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''module.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): # projection head is used in the self-supervised pre-training in MSN, # for downstream task it's not needed. SCREAMING_SNAKE_CASE__ = [ """module.fc.fc1.weight""", """module.fc.fc1.bias""", """module.fc.bn1.weight""", """module.fc.bn1.bias""", """module.fc.bn1.running_mean""", """module.fc.bn1.running_var""", """module.fc.bn1.num_batches_tracked""", """module.fc.fc2.weight""", """module.fc.fc2.bias""", """module.fc.bn2.weight""", """module.fc.bn2.bias""", """module.fc.bn2.running_mean""", """module.fc.bn2.running_var""", """module.fc.bn2.num_batches_tracked""", """module.fc.fc3.weight""", """module.fc.fc3.bias""", ] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = dct.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = ViTMSNConfig() SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """datasets/huggingface/label-files""" SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 384 SCREAMING_SNAKE_CASE__ = 1_536 SCREAMING_SNAKE_CASE__ = 6 elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 1_024 SCREAMING_SNAKE_CASE__ = 4_096 SCREAMING_SNAKE_CASE__ = 24 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = 0.1 elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 4 elif "l7" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 7 SCREAMING_SNAKE_CASE__ = 1_024 SCREAMING_SNAKE_CASE__ = 4_096 SCREAMING_SNAKE_CASE__ = 24 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = ViTMSNModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = torch.hub.load_state_dict_from_url(UpperCamelCase__ , map_location="""cpu""" )["""target_encoder"""] SCREAMING_SNAKE_CASE__ = ViTImageProcessor(size=config.image_size ) remove_projection_head(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = create_rename_keys(UpperCamelCase__ , base_model=UpperCamelCase__ ) for src, dest in rename_keys: rename_key(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) read_in_q_k_v(UpperCamelCase__ , UpperCamelCase__ , base_model=UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) SCREAMING_SNAKE_CASE__ = ViTImageProcessor( size=config.image_size , image_mean=UpperCamelCase__ , image_std=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[-1.0_9_1_5, -1.4_8_7_6, -1.1_8_0_9]] ) elif "b16" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[1_4.2_8_8_9, -1_8.9_0_4_5, 1_1.7_2_8_1]] ) elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[4_1.5_0_2_8, -2_2.8_6_8_1, 4_5.6_4_7_5]] ) elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[-4.3_8_6_8, 5.2_9_3_2, -0.4_1_3_7]] ) else: SCREAMING_SNAKE_CASE__ = torch.tensor([[-0.1_7_9_2, -0.6_4_6_5, 2.4_2_6_3]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , UpperCamelCase__ , atol=1e-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _lowerCamelCase = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
59
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _snake_case ( self :int ) -> str: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
1
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = analyze_text(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = list(""" """ + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE__ = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE__ = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE__ = single_char_strings[ch] SCREAMING_SNAKE_CASE__ = my_str / all_sum my_fir_sum += prob * math.loga(UpperCamelCase__ ) # entropy formula. # print entropy print(f'''{round(-1 * my_fir_sum ):.1f}''' ) # two len string SCREAMING_SNAKE_CASE__ = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE__ = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE__ = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE__ = two_char_strings[sequence] SCREAMING_SNAKE_CASE__ = int(UpperCamelCase__ ) / all_sum my_sec_sum += prob * math.loga(UpperCamelCase__ ) # print second entropy print(f'''{round(-1 * my_sec_sum ):.1f}''' ) # print the difference between them print(f'''{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = Counter() # type: ignore SCREAMING_SNAKE_CASE__ = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(UpperCamelCase__ ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def SCREAMING_SNAKE_CASE__ ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
59
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
1
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :int , __A :str ) -> Optional[Any]: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)""" ) SCREAMING_SNAKE_CASE__ = input_file.read() SCREAMING_SNAKE_CASE__ = regexp.search(__A ) return match def _snake_case ( self :Optional[int] , __A :str ) -> Dict: """simple docstring""" with open(__A , encoding="""utf-8""" ) as input_file: SCREAMING_SNAKE_CASE__ = re.compile(r"""#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()""" , re.DOTALL ) SCREAMING_SNAKE_CASE__ = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` SCREAMING_SNAKE_CASE__ = regexp.finditer(__A ) SCREAMING_SNAKE_CASE__ = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(__A ) ): raise AssertionError(f'''open(...) must use utf-8 encoding in {dataset}''' ) def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = Path("""./datasets""" ) SCREAMING_SNAKE_CASE__ = list(dataset_paths.absolute().glob("""**/*.py""" ) ) for dataset in dataset_files: if self._no_print_statements(str(__A ) ): raise AssertionError(f'''print statement found in {dataset}. Use datasets.logger/logging instead.''' )
59
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
1
import math def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if ( not isinstance(UpperCamelCase__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * power_factor def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): if ( not isinstance(UpperCamelCase__ , (int, float) ) or power_factor < -1 or power_factor > 1 ): raise ValueError("""power_factor must be a valid float value between -1 and 1.""" ) return apparent_power * math.sqrt(1 - power_factor**2 ) if __name__ == "__main__": import doctest doctest.testmod()
59
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser(add_help=UpperCamelCase__ , allow_abbrev=UpperCamelCase__ ) # The main config parser SCREAMING_SNAKE_CASE__ = config_command_parser(UpperCamelCase__ ) # The subparser to add commands to SCREAMING_SNAKE_CASE__ = config_parser.add_subparsers(title="""subcommands""" , dest="""subcommand""" ) # Then add other parsers with the parent parser default_command_parser(UpperCamelCase__ , parents=[parent_parser] ) update_command_parser(UpperCamelCase__ , parents=[parent_parser] ) return config_parser def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = get_config_parser() SCREAMING_SNAKE_CASE__ = config_parser.parse_args() if not hasattr(UpperCamelCase__ , """func""" ): config_parser.print_help() exit(1 ) # Run args.func(UpperCamelCase__ ) if __name__ == "__main__": main()
59
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[int | float] , UpperCamelCase__: int , UpperCamelCase__: int ): if len(UpperCamelCase__ ) == 0: raise ValueError("""find_max() arg is an empty sequence""" ) if ( left >= len(UpperCamelCase__ ) or left < -len(UpperCamelCase__ ) or right >= len(UpperCamelCase__ ) or right < -len(UpperCamelCase__ ) ): raise IndexError("""list index out of range""" ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ = find_max(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ = find_max(UpperCamelCase__ , mid + 1 , UpperCamelCase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
59
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
1
from collections import OrderedDict from typing import Any, List, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'EleutherAI/gpt-j-6B': 'https://huggingface.co/EleutherAI/gpt-j-6B/resolve/main/config.json', # See all GPT-J models at https://huggingface.co/models?filter=gpt_j } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "gptj" lowerCamelCase_ = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self :Dict , __A :Optional[int]=5_0400 , __A :List[str]=2048 , __A :List[str]=4096 , __A :Any=28 , __A :Tuple=16 , __A :Any=64 , __A :List[str]=None , __A :List[Any]="gelu_new" , __A :int=0.0 , __A :str=0.0 , __A :int=0.0 , __A :int=1E-5 , __A :str=0.0_2 , __A :Union[str, Any]=True , __A :Optional[Any]=5_0256 , __A :Dict=5_0256 , __A :Dict=False , **__A :Dict , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = n_positions SCREAMING_SNAKE_CASE__ = n_embd SCREAMING_SNAKE_CASE__ = n_layer SCREAMING_SNAKE_CASE__ = n_head SCREAMING_SNAKE_CASE__ = n_inner SCREAMING_SNAKE_CASE__ = rotary_dim SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = resid_pdrop SCREAMING_SNAKE_CASE__ = embd_pdrop SCREAMING_SNAKE_CASE__ = attn_pdrop SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = bos_token_id SCREAMING_SNAKE_CASE__ = eos_token_id super().__init__( bos_token_id=__A , eos_token_id=__A , tie_word_embeddings=__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :PretrainedConfig , __A :str = "default" , __A :List[PatchingSpec] = None , __A :bool = False , ) -> List[str]: """simple docstring""" super().__init__(__A , task=__A , patching_specs=__A , use_past=__A ) if not getattr(self._config , """pad_token_id""" , __A ): # TODO: how to do that better? SCREAMING_SNAKE_CASE__ = 0 @property def _snake_case ( self :Optional[Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: self.fill_with_past_key_values_(__A , direction="""inputs""" ) SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """past_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """sequence"""} return common_inputs @property def _snake_case ( self :Dict ) -> int: """simple docstring""" return self._config.n_layer @property def _snake_case ( self :str ) -> int: """simple docstring""" return self._config.n_head def _snake_case ( self :str , __A :PreTrainedTokenizer , __A :int = -1 , __A :int = -1 , __A :bool = False , __A :Optional[TensorType] = None , ) -> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = super(__A , self ).generate_dummy_inputs( __A , batch_size=__A , seq_length=__A , is_pair=__A , framework=__A ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE__ = 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 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ = seqlen + 2 SCREAMING_SNAKE_CASE__ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE__ = [ (torch.zeros(__A ), torch.zeros(__A )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ = common_inputs["""attention_mask"""] if self.use_past: SCREAMING_SNAKE_CASE__ = ordered_inputs["""attention_mask"""].dtype SCREAMING_SNAKE_CASE__ = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(__A , __A , dtype=__A )] , dim=1 ) return ordered_inputs @property def _snake_case ( self :List[Any] ) -> int: """simple docstring""" return 13
59
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
1
import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCamelCase_ : def __init__( self :List[Any] , __A :str = "cpu" , __A :str = "openai/clip-vit-large-patch14" ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = device SCREAMING_SNAKE_CASE__ = CLIPTokenizerFast.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3] SCREAMING_SNAKE_CASE__ = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1] SCREAMING_SNAKE_CASE__ = torchvision.transforms.Normalize(self.image_mean , self.image_std ) SCREAMING_SNAKE_CASE__ = torchvision.transforms.Resize(224 ) SCREAMING_SNAKE_CASE__ = torchvision.transforms.CenterCrop(224 ) def _snake_case ( self :Any , __A :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.resize(__A ) SCREAMING_SNAKE_CASE__ = self.center_crop(__A ) SCREAMING_SNAKE_CASE__ = self.normalize(__A ) return images def __call__( self :Optional[Any] , __A :Dict=None , __A :Optional[Any]=None , **__A :Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer(text=__A , **__A ) SCREAMING_SNAKE_CASE__ = self.preprocess_img(__A ) SCREAMING_SNAKE_CASE__ = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :Union[str, Any]=10 , __A :Tuple=0.0_1 , __A :List[str]=None , __A :int=None , __A :Optional[int]=None , __A :List[Any]=None , __A :Optional[Any]=None , __A :Any=None , __A :List[str]=False , __A :Optional[int]=True , __A :Dict="image" , __A :int=True , __A :Optional[Any]=False , __A :Dict=False , __A :str=False , ) -> None: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = device if device else get_device() if vqgan: SCREAMING_SNAKE_CASE__ = vqgan else: SCREAMING_SNAKE_CASE__ = load_vqgan(self.device , conf_path=__A , ckpt_path=__A ) self.vqgan.eval() if clip: SCREAMING_SNAKE_CASE__ = clip else: SCREAMING_SNAKE_CASE__ = CLIPModel.from_pretrained("""openai/clip-vit-base-patch32""" ) self.clip.to(self.device ) SCREAMING_SNAKE_CASE__ = ProcessorGradientFlow(device=self.device ) SCREAMING_SNAKE_CASE__ = iterations SCREAMING_SNAKE_CASE__ = lr SCREAMING_SNAKE_CASE__ = log SCREAMING_SNAKE_CASE__ = make_grid SCREAMING_SNAKE_CASE__ = return_val SCREAMING_SNAKE_CASE__ = quantize SCREAMING_SNAKE_CASE__ = self.vqgan.decoder.z_shape def _snake_case ( self :Tuple , __A :str=None , __A :int=None , __A :Union[str, Any]=5 , __A :List[str]=True ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [] if output_path is None: SCREAMING_SNAKE_CASE__ = """./animation.gif""" if input_path is None: SCREAMING_SNAKE_CASE__ = self.save_path SCREAMING_SNAKE_CASE__ = sorted(glob(input_path + """/*""" ) ) if not len(__A ): raise ValueError( """No images found in save path, aborting (did you pass save_intermediate=True to the generate""" """ function?)""" ) if len(__A ) == 1: print("""Only one image found in save path, (did you pass save_intermediate=True to the generate function?)""" ) SCREAMING_SNAKE_CASE__ = total_duration / len(__A ) SCREAMING_SNAKE_CASE__ = [frame_duration] * len(__A ) if extend_frames: SCREAMING_SNAKE_CASE__ = 1.5 SCREAMING_SNAKE_CASE__ = 3 for file_name in paths: if file_name.endswith(""".png""" ): images.append(imageio.imread(__A ) ) imageio.mimsave(__A , __A , duration=__A ) print(f'''gif saved to {output_path}''' ) def _snake_case ( self :Dict , __A :int=None , __A :Optional[Any]=None ) -> str: """simple docstring""" if not (path or img): raise ValueError("""Input either path or tensor""" ) if img is not None: raise NotImplementedError SCREAMING_SNAKE_CASE__ = preprocess(Image.open(__A ) , target_image_size=256 ).to(self.device ) SCREAMING_SNAKE_CASE__ = preprocess_vqgan(__A ) SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ = self.vqgan.encode(__A ) return z def _snake_case ( self :Any , __A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.latent.detach().requires_grad_() SCREAMING_SNAKE_CASE__ = base_latent + transform_vector if self.quantize: SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ = self.vqgan.quantize(__A ) else: SCREAMING_SNAKE_CASE__ = trans_latent return self.vqgan.decode(__A ) def _snake_case ( self :Any , __A :Optional[Any] , __A :Tuple , __A :Optional[Any]=None ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.clip_preprocessor(text=__A , images=__A , return_tensors="""pt""" , padding=__A ) SCREAMING_SNAKE_CASE__ = self.clip(**__A ) SCREAMING_SNAKE_CASE__ = clip_outputs.logits_per_image if weights is not None: SCREAMING_SNAKE_CASE__ = similarity_logits * weights return similarity_logits.sum() def _snake_case ( self :Dict , __A :Optional[Any] , __A :Dict , __A :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._get_clip_similarity(pos_prompts["""prompts"""] , __A , weights=(1 / pos_prompts["""weights"""]) ) if neg_prompts: SCREAMING_SNAKE_CASE__ = self._get_clip_similarity(neg_prompts["""prompts"""] , __A , weights=neg_prompts["""weights"""] ) else: SCREAMING_SNAKE_CASE__ = torch.tensor([1] , device=self.device ) SCREAMING_SNAKE_CASE__ = -torch.log(__A ) + torch.log(__A ) return loss def _snake_case ( self :Dict , __A :str , __A :int , __A :List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch.randn_like(self.latent , requires_grad=__A , device=self.device ) SCREAMING_SNAKE_CASE__ = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() SCREAMING_SNAKE_CASE__ = self._add_vector(__A ) SCREAMING_SNAKE_CASE__ = loop_post_process(__A ) SCREAMING_SNAKE_CASE__ = self._get_CLIP_loss(__A , __A , __A ) print("""CLIP loss""" , __A ) if self.log: wandb.log({"""CLIP Loss""": clip_loss} ) clip_loss.backward(retain_graph=__A ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def _snake_case ( self :List[str] , __A :List[Any] , __A :Optional[Any] , __A :Any ) -> Union[str, Any]: """simple docstring""" wandb.init(reinit=__A , project="""face-editor""" ) wandb.config.update({"""Positive Prompts""": positive_prompts} ) wandb.config.update({"""Negative Prompts""": negative_prompts} ) wandb.config.update({"""lr""": self.lr, """iterations""": self.iterations} ) if image_path: SCREAMING_SNAKE_CASE__ = Image.open(__A ) SCREAMING_SNAKE_CASE__ = image.resize((256, 256) ) wandb.log("""Original Image""" , wandb.Image(__A ) ) def _snake_case ( self :Union[str, Any] , __A :Optional[Any] ) -> Optional[int]: """simple docstring""" if not prompts: return [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [prompt.strip() for prompt in prompts.split("""|""" )] for prompt in prompts: if isinstance(__A , (tuple, list) ): SCREAMING_SNAKE_CASE__ = prompt[0] SCREAMING_SNAKE_CASE__ = float(prompt[1] ) elif ":" in prompt: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = prompt.split(""":""" ) SCREAMING_SNAKE_CASE__ = float(__A ) else: SCREAMING_SNAKE_CASE__ = prompt SCREAMING_SNAKE_CASE__ = 1.0 processed_prompts.append(__A ) weights.append(__A ) return { "prompts": processed_prompts, "weights": torch.tensor(__A , device=self.device ), } def _snake_case ( self :List[str] , __A :str , __A :Any=None , __A :List[Any]=None , __A :Any=True , __A :str=False , __A :int=True , __A :Tuple=True , __A :Union[str, Any]=None , ) -> Tuple: """simple docstring""" if image_path: SCREAMING_SNAKE_CASE__ = self._get_latent(__A ) else: SCREAMING_SNAKE_CASE__ = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(__A , __A , __A ) assert pos_prompts, "You must provide at least one positive prompt." SCREAMING_SNAKE_CASE__ = self.process_prompts(__A ) SCREAMING_SNAKE_CASE__ = self.process_prompts(__A ) if save_final and save_path is None: SCREAMING_SNAKE_CASE__ = os.path.join("""./outputs/""" , """_""".join(pos_prompts["""prompts"""] ) ) if not os.path.exists(__A ): os.makedirs(__A ) else: SCREAMING_SNAKE_CASE__ = save_path + """_""" + get_timestamp() os.makedirs(__A ) SCREAMING_SNAKE_CASE__ = save_path SCREAMING_SNAKE_CASE__ = self.vqgan.decode(self.latent )[0] if show_intermediate: print("""Original Image""" ) show_pil(custom_to_pil(__A ) ) SCREAMING_SNAKE_CASE__ = loop_post_process(__A ) for iter, transformed_img in enumerate(self._optimize_CLIP(__A , __A , __A ) ): if show_intermediate: show_pil(__A ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}.png''' ) ) if self.log: wandb.log({"""Image""": wandb.Image(__A )} ) if show_final: show_pil(__A ) if save_final: transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}_final.png''' ) )
59
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
1
from typing import List, Optional, Union import numpy as np from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ....feature_extraction_sequence_utils import SequenceFeatureExtractor from ....feature_extraction_utils import BatchFeature from ....file_utils import PaddingStrategy, TensorType from ....utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["input_features", "attention_mask"] def __init__( self :List[Any] , __A :int=80 , __A :Dict=1_6000 , __A :str=0.0 , __A :Dict=10 , __A :Optional[int]=25 , __A :Dict="hamming_window" , __A :List[str]=3_2_7_6_8.0 , __A :Dict=0.9_7 , __A :Union[str, Any]=1.0 , __A :List[str]=True , __A :Tuple=True , __A :List[Any]=False , **__A :Optional[int] , ) -> List[str]: """simple docstring""" super().__init__(feature_size=__A , sampling_rate=__A , padding_value=__A , **__A ) SCREAMING_SNAKE_CASE__ = feature_size SCREAMING_SNAKE_CASE__ = sampling_rate SCREAMING_SNAKE_CASE__ = padding_value SCREAMING_SNAKE_CASE__ = hop_length SCREAMING_SNAKE_CASE__ = win_length SCREAMING_SNAKE_CASE__ = frame_signal_scale SCREAMING_SNAKE_CASE__ = preemphasis_coeff SCREAMING_SNAKE_CASE__ = mel_floor SCREAMING_SNAKE_CASE__ = normalize_means SCREAMING_SNAKE_CASE__ = normalize_vars SCREAMING_SNAKE_CASE__ = win_function SCREAMING_SNAKE_CASE__ = return_attention_mask SCREAMING_SNAKE_CASE__ = win_length * sampling_rate // 1000 SCREAMING_SNAKE_CASE__ = hop_length * sampling_rate // 1000 SCREAMING_SNAKE_CASE__ = optimal_fft_length(self.sample_size ) SCREAMING_SNAKE_CASE__ = (self.n_fft // 2) + 1 def _snake_case ( self :Optional[int] , __A :np.array ) -> np.ndarray: """simple docstring""" if self.win_function == "hamming_window": SCREAMING_SNAKE_CASE__ = window_function(window_length=self.sample_size , name=self.win_function , periodic=__A ) else: SCREAMING_SNAKE_CASE__ = window_function(window_length=self.sample_size , name=self.win_function ) SCREAMING_SNAKE_CASE__ = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.feature_size , min_frequency=0.0 , max_frequency=self.sampling_rate / 2.0 , sampling_rate=self.sampling_rate , ) SCREAMING_SNAKE_CASE__ = spectrogram( one_waveform * self.frame_signal_scale , window=__A , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , center=__A , preemphasis=self.preemphasis_coeff , mel_filters=__A , mel_floor=self.mel_floor , log_mel="""log""" , ) return msfc_features.T def _snake_case ( self :Optional[int] , __A :Optional[int] , __A :Optional[Any] , __A :Optional[Any] ) -> List[str]: """simple docstring""" if self.normalize_means: SCREAMING_SNAKE_CASE__ = x[:input_length].mean(axis=0 ) SCREAMING_SNAKE_CASE__ = np.subtract(__A , __A ) if self.normalize_vars: SCREAMING_SNAKE_CASE__ = x[:input_length].std(axis=0 ) SCREAMING_SNAKE_CASE__ = np.divide(__A , __A ) if input_length < x.shape[0]: SCREAMING_SNAKE_CASE__ = padding_value # make sure array is in float32 SCREAMING_SNAKE_CASE__ = x.astype(np.floataa ) return x def _snake_case ( self :Tuple , __A :List[np.ndarray] , __A :Optional[np.ndarray] = None ) -> List[np.ndarray]: """simple docstring""" SCREAMING_SNAKE_CASE__ = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [self._normalize_one(__A , __A , self.padding_value ) for x, n in zip(__A , __A )] def __call__( self :Optional[int] , __A :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __A :Union[bool, str, PaddingStrategy] = False , __A :Optional[int] = None , __A :bool = False , __A :Optional[int] = None , __A :Optional[bool] = None , __A :Optional[Union[str, TensorType]] = None , __A :Optional[int] = None , **__A :List[str] , ) -> BatchFeature: """simple docstring""" if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( """It is strongly recommended to pass the ``sampling_rate`` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) SCREAMING_SNAKE_CASE__ = isinstance(__A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) SCREAMING_SNAKE_CASE__ = is_batched_numpy or ( isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__A , np.ndarray ): SCREAMING_SNAKE_CASE__ = np.asarray(__A , dtype=np.floataa ) elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE__ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE__ = [raw_speech] # extract fbank features SCREAMING_SNAKE_CASE__ = [self._extract_mfsc_features(__A ) for one_waveform in raw_speech] # convert into correct format for padding SCREAMING_SNAKE_CASE__ = BatchFeature({"""input_features""": features} ) SCREAMING_SNAKE_CASE__ = self.pad( __A , padding=__A , max_length=__A , truncation=__A , pad_to_multiple_of=__A , return_attention_mask=__A , **__A , ) # make sure list is in array format SCREAMING_SNAKE_CASE__ = padded_inputs.get("""input_features""" ) if isinstance(input_features[0] , __A ): SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for feature in input_features] SCREAMING_SNAKE_CASE__ = padded_inputs.get("""attention_mask""" ) if attention_mask is not None: SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.intaa ) for array in attention_mask] if self.normalize_means or self.normalize_vars: SCREAMING_SNAKE_CASE__ = ( np.array(__A , dtype=np.intaa ) if self._get_padding_strategies(__A , max_length=__A ) is not PaddingStrategy.DO_NOT_PAD and padding else None ) SCREAMING_SNAKE_CASE__ = self.normalize( padded_inputs["""input_features"""] , attention_mask=__A ) if return_tensors is not None: SCREAMING_SNAKE_CASE__ = padded_inputs.convert_to_tensors(__A ) return padded_inputs
59
# 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 = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
from math import factorial class UpperCamelCase_ : def __init__( self :Optional[Any] , __A :Any , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = real if isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [1] * rank else: SCREAMING_SNAKE_CASE__ = rank def __repr__( self :Tuple ) -> List[str]: """simple docstring""" return ( f'''{self.real}+''' f'''{'+'.join(str(__A )+'E'+str(n+1 )for n,dual in enumerate(self.duals ) )}''' ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real , __A ) def __add__( self :Optional[int] , __A :Tuple ) -> Optional[int]: """simple docstring""" if not isinstance(__A , __A ): return Dual(self.real + other , self.duals ) SCREAMING_SNAKE_CASE__ = self.duals.copy() SCREAMING_SNAKE_CASE__ = other.duals.copy() if len(__A ) > len(__A ): o_dual.extend([1] * (len(__A ) - len(__A )) ) elif len(__A ) < len(__A ): s_dual.extend([1] * (len(__A ) - len(__A )) ) SCREAMING_SNAKE_CASE__ = [] for i in range(len(__A ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real , __A ) lowerCamelCase_ = __add__ def __sub__( self :Tuple , __A :Tuple ) -> Dict: """simple docstring""" return self + other * -1 def __mul__( self :str , __A :Optional[int] ) -> List[str]: """simple docstring""" if not isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other , __A ) SCREAMING_SNAKE_CASE__ = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , __A ) lowerCamelCase_ = __mul__ def __truediv__( self :str , __A :Any ) -> Optional[Any]: """simple docstring""" if not isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other , __A ) raise ValueError def __floordiv__( self :Union[str, Any] , __A :Union[str, Any] ) -> Optional[int]: """simple docstring""" if not isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other , __A ) raise ValueError def __pow__( self :str , __A :List[Any] ) -> str: """simple docstring""" if n < 0 or isinstance(__A , __A ): raise ValueError("""power must be a positive integer""" ) if n == 0: return 1 if n == 1: return self SCREAMING_SNAKE_CASE__ = self for _ in range(n - 1 ): x *= self return x def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Dict , UpperCamelCase__: Optional[Any] ): if not callable(UpperCamelCase__ ): raise ValueError("""differentiate() requires a function as input for func""" ) if not isinstance(UpperCamelCase__ , (float, int) ): raise ValueError("""differentiate() requires a float as input for position""" ) if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): raise ValueError("""differentiate() requires an int as input for order""" ) SCREAMING_SNAKE_CASE__ = Dual(UpperCamelCase__ , 1 ) SCREAMING_SNAKE_CASE__ = func(UpperCamelCase__ ) if order == 0: return result.real return result.duals[order - 1] * factorial(UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): return y**2 * y**4 print(differentiate(f, 9, 2))
59
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int = 50_000_000 ): SCREAMING_SNAKE_CASE__ = set() SCREAMING_SNAKE_CASE__ = int((limit - 24) ** (1 / 2) ) SCREAMING_SNAKE_CASE__ = set(range(3 , prime_square_limit + 1 , 2 ) ) primes.add(2 ) for p in range(3 , prime_square_limit + 1 , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , prime_square_limit + 1 , UpperCamelCase__ ) ) ) for primea in primes: SCREAMING_SNAKE_CASE__ = primea * primea for primea in primes: SCREAMING_SNAKE_CASE__ = primea * primea * primea if square + cube >= limit - 16: break for primea in primes: SCREAMING_SNAKE_CASE__ = primea * primea * primea * primea SCREAMING_SNAKE_CASE__ = square + cube + tetr if total >= limit: break ret.add(UpperCamelCase__ ) return len(UpperCamelCase__ ) if __name__ == "__main__": print(F'''{solution() = }''')
59
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
1
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: bytes , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ = """1""" SCREAMING_SNAKE_CASE__ = """f32le""" SCREAMING_SNAKE_CASE__ = [ """ffmpeg""", """-i""", """pipe:0""", """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] try: with subprocess.Popen(UpperCamelCase__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: SCREAMING_SNAKE_CASE__ = ffmpeg_process.communicate(UpperCamelCase__ ) except FileNotFoundError as error: raise ValueError("""ffmpeg was not found but is required to load audio files from filename""" ) from error SCREAMING_SNAKE_CASE__ = output_stream[0] SCREAMING_SNAKE_CASE__ = np.frombuffer(UpperCamelCase__ , np.floataa ) if audio.shape[0] == 0: raise ValueError("""Malformed soundfile""" ) return audio def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: float , UpperCamelCase__: str = "f32le" , ): SCREAMING_SNAKE_CASE__ = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ = """1""" if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) SCREAMING_SNAKE_CASE__ = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE__ = """alsa""" SCREAMING_SNAKE_CASE__ = """default""" elif system == "Darwin": SCREAMING_SNAKE_CASE__ = """avfoundation""" SCREAMING_SNAKE_CASE__ = """:0""" elif system == "Windows": SCREAMING_SNAKE_CASE__ = """dshow""" SCREAMING_SNAKE_CASE__ = """default""" SCREAMING_SNAKE_CASE__ = [ """ffmpeg""", """-f""", format_, """-i""", input_, """-ac""", ac, """-ar""", ar, """-f""", format_for_conversion, """-fflags""", """nobuffer""", """-hide_banner""", """-loglevel""", """quiet""", """pipe:1""", ] SCREAMING_SNAKE_CASE__ = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample SCREAMING_SNAKE_CASE__ = _ffmpeg_stream(UpperCamelCase__ , UpperCamelCase__ ) for item in iterator: yield item def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: float , UpperCamelCase__: Optional[int] = None , UpperCamelCase__: Optional[Union[Tuple[float, float], float]] = None , UpperCamelCase__: str = "f32le" , ): if stream_chunk_s is not None: SCREAMING_SNAKE_CASE__ = stream_chunk_s else: SCREAMING_SNAKE_CASE__ = chunk_length_s SCREAMING_SNAKE_CASE__ = ffmpeg_microphone(UpperCamelCase__ , UpperCamelCase__ , format_for_conversion=UpperCamelCase__ ) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ = np.intaa SCREAMING_SNAKE_CASE__ = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ = np.floataa SCREAMING_SNAKE_CASE__ = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) if stride_length_s is None: SCREAMING_SNAKE_CASE__ = chunk_length_s / 6 SCREAMING_SNAKE_CASE__ = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(UpperCamelCase__ , (int, float) ): SCREAMING_SNAKE_CASE__ = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE__ = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ = datetime.datetime.now() SCREAMING_SNAKE_CASE__ = datetime.timedelta(seconds=UpperCamelCase__ ) for item in chunk_bytes_iter(UpperCamelCase__ , UpperCamelCase__ , stride=(stride_left, stride_right) , stream=UpperCamelCase__ ): # Put everything back in numpy scale SCREAMING_SNAKE_CASE__ = np.frombuffer(item["""raw"""] , dtype=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = ( item["""stride"""][0] // size_of_sample, item["""stride"""][1] // size_of_sample, ) SCREAMING_SNAKE_CASE__ = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: Tuple[int, int] , UpperCamelCase__: bool = False ): SCREAMING_SNAKE_CASE__ = B"""""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = stride if stride_left + stride_right >= chunk_len: raise ValueError( f'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''' ) SCREAMING_SNAKE_CASE__ = 0 for raw in iterator: acc += raw if stream and len(UpperCamelCase__ ) < chunk_len: SCREAMING_SNAKE_CASE__ = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(UpperCamelCase__ ) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE__ = (_stride_left, stride_right) SCREAMING_SNAKE_CASE__ = {"""raw""": acc[:chunk_len], """stride""": stride} if stream: SCREAMING_SNAKE_CASE__ = False yield item SCREAMING_SNAKE_CASE__ = stride_left SCREAMING_SNAKE_CASE__ = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(UpperCamelCase__ ) > stride_left: SCREAMING_SNAKE_CASE__ = {"""raw""": acc, """stride""": (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE__ = False yield item def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = 2**24 # 16Mo try: with subprocess.Popen(UpperCamelCase__ , stdout=subprocess.PIPE , bufsize=UpperCamelCase__ ) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE__ = ffmpeg_process.stdout.read(UpperCamelCase__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError("""ffmpeg was not found but is required to stream audio files from filename""" ) from error
59
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
1
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
1
from __future__ import annotations import requests _lowerCamelCase = set( 'approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'.split() ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: int = 1 , UpperCamelCase__: str = "new" , UpperCamelCase__: list | None = None ): SCREAMING_SNAKE_CASE__ = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(UpperCamelCase__ ) - valid_terms ) ): SCREAMING_SNAKE_CASE__ = f'''Invalid search term: {invalid_search_terms}''' raise ValueError(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = requests.get( f'''https://reddit.com/r/{subreddit}/{age}.json?limit={limit}''' , headers={"""User-agent""": """A random string"""} , ) if response.status_code == 429: raise requests.HTTPError SCREAMING_SNAKE_CASE__ = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(UpperCamelCase__ )} SCREAMING_SNAKE_CASE__ = {} for id_ in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = { item: data["""data"""]["""children"""][id_]["""data"""][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('learnpython', wanted_data=['title', 'url', 'selftext']))
59
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
1
import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": _lowerCamelCase = 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 = parser.parse_args() if args.model_type == "bert": _lowerCamelCase = BertForMaskedLM.from_pretrained(args.model_name) _lowerCamelCase = 'bert' else: raise ValueError('args.model_type should be "bert".') _lowerCamelCase = model.state_dict() _lowerCamelCase = {} for w in ["word_embeddings", "position_embeddings"]: _lowerCamelCase = state_dict[F'''{prefix}.embeddings.{w}.weight'''] for w in ["weight", "bias"]: _lowerCamelCase = state_dict[F'''{prefix}.embeddings.LayerNorm.{w}'''] _lowerCamelCase = 0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}''' ] _lowerCamelCase = state_dict[ F'''{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}''' ] std_idx += 1 _lowerCamelCase = state_dict['cls.predictions.decoder.weight'] _lowerCamelCase = state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: _lowerCamelCase = state_dict[F'''cls.predictions.transform.dense.{w}'''] _lowerCamelCase = 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)
59
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
1
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): return [ { 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], }, { 0: [6], 1: [9], 2: [4, 5], 3: [4], 4: [2, 3], 5: [2], 6: [0, 7], 7: [6], 8: [], 9: [1], }, { 0: [4], 1: [6], 2: [], 3: [5, 6, 7], 4: [0, 6], 5: [3, 8, 9], 6: [1, 3, 4, 7], 7: [3, 6, 8, 9], 8: [5, 7], 9: [5, 7], }, { 0: [1, 3], 1: [0, 2, 4], 2: [1, 3, 4], 3: [0, 2, 4], 4: [1, 2, 3], }, ][index] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: dict[int, list[int]] ): SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) # No of vertices in graph SCREAMING_SNAKE_CASE__ = [0] * n SCREAMING_SNAKE_CASE__ = [False] * n def dfs(UpperCamelCase__: List[Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: str , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = id_ id_ += 1 for to in graph[at]: if to == parent: pass elif not visited[to]: dfs(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , id_ ) SCREAMING_SNAKE_CASE__ = min(low[at] , low[to] ) if id_ <= low[to]: bridges.append((at, to) if at < to else (to, at) ) else: # This edge is a back edge and cannot be a bridge SCREAMING_SNAKE_CASE__ = min(low[at] , low[to] ) SCREAMING_SNAKE_CASE__ = [] for i in range(UpperCamelCase__ ): if not visited[i]: dfs(UpperCamelCase__ , -1 , UpperCamelCase__ , id_ ) return bridges if __name__ == "__main__": import doctest doctest.testmod()
59
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
1
import argparse from collections import defaultdict def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''{file}_{class_name}_{test_name}''' done_test[_id] += 1 with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = f.readlines() SCREAMING_SNAKE_CASE__ = f'''class {class_name}(''' SCREAMING_SNAKE_CASE__ = f'''{4 * ' '}def {test_name}(''' SCREAMING_SNAKE_CASE__ = f'''{8 * ' '}{correct_line.split()[0]}''' SCREAMING_SNAKE_CASE__ = f'''{16 * ' '}{correct_line.split()[0]}''' SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = [] for line in lines: if line.startswith(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = True elif in_class and line.startswith(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = True elif in_class and in_func and (line.startswith(UpperCamelCase__ ) or line.startswith(UpperCamelCase__ )): SCREAMING_SNAKE_CASE__ = len(line.split(correct_line.split()[0] )[0] ) count += 1 if count == done_test[_id]: SCREAMING_SNAKE_CASE__ = True if in_class and in_func and in_line: if ")" not in line: continue else: SCREAMING_SNAKE_CASE__ = True if in_class and in_func and in_line and insert_line: new_lines.append(f'''{spaces * ' '}{correct_line}''' ) SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = False else: new_lines.append(UpperCamelCase__ ) with open(UpperCamelCase__ , """w""" ) as f: for line in new_lines: f.write(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Union[str, Any]=None ): if fail is not None: with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = {l.strip() for l in f.readlines()} else: SCREAMING_SNAKE_CASE__ = None with open(UpperCamelCase__ , """r""" ) as f: SCREAMING_SNAKE_CASE__ = f.readlines() SCREAMING_SNAKE_CASE__ = defaultdict(UpperCamelCase__ ) for line in correct_lines: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = line.split(""";""" ) if test_failures is None or "::".join([file, class_name, test_name] ) in test_failures: overwrite_file(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument('--correct_filename', help='filename of tests with expected result') parser.add_argument('--fail_filename', help='filename of test failures', type=str, default=None) _lowerCamelCase = parser.parse_args() main(args.correct_filename, args.fail_filename)
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFCamembertModel @require_tf @require_sentencepiece @require_tokenizers class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFCamembertModel.from_pretrained("""jplu/tf-camembert-base""" ) SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor( [[5, 121, 11, 660, 16, 730, 2_5543, 110, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !" SCREAMING_SNAKE_CASE__ = model(__A )["""last_hidden_state"""] SCREAMING_SNAKE_CASE__ = tf.TensorShape((1, 10, 768) ) self.assertEqual(output.shape , __A ) # compare the actual values for a slice. SCREAMING_SNAKE_CASE__ = tf.convert_to_tensor( [[[-0.0_2_5_4, 0.0_2_3_5, 0.1_0_2_7], [0.0_6_0_6, -0.1_8_1_1, -0.0_4_1_8], [-0.1_5_6_1, -0.1_1_2_7, 0.2_6_8_7]]] , dtype=tf.floataa , ) # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0') # camembert.eval() # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach() self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
59
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all BART models at https://huggingface.co/models?filter=bart _lowerCamelCase = { 'vocab_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json', }, 'merges_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt', }, 'tokenizer_file': { 'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json', 'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json', 'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json', 'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json', 'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json', 'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json', }, } _lowerCamelCase = { 'facebook/bart-base': 1024, 'facebook/bart-large': 1024, 'facebook/bart-large-mnli': 1024, 'facebook/bart-large-cnn': 1024, 'facebook/bart-large-xsum': 1024, 'yjernite/bart_eli5': 1024, } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = BartTokenizer def __init__( self :str , __A :Optional[Any]=None , __A :List[Any]=None , __A :Optional[int]=None , __A :int="replace" , __A :str="<s>" , __A :Tuple="</s>" , __A :Dict="</s>" , __A :Union[str, Any]="<s>" , __A :int="<unk>" , __A :Tuple="<pad>" , __A :Union[str, Any]="<mask>" , __A :Any=False , __A :Optional[int]=True , **__A :List[str] , ) -> str: """simple docstring""" super().__init__( __A , __A , tokenizer_file=__A , errors=__A , bos_token=__A , eos_token=__A , sep_token=__A , cls_token=__A , unk_token=__A , pad_token=__A , mask_token=__A , add_prefix_space=__A , trim_offsets=__A , **__A , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(__A , pre_tok_state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**__A ) SCREAMING_SNAKE_CASE__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE__ = """post_processor""" SCREAMING_SNAKE_CASE__ = getattr(self.backend_tokenizer , __A , __A ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE__ = tuple(state["""sep"""] ) if "cls" in state: SCREAMING_SNAKE_CASE__ = tuple(state["""cls"""] ) SCREAMING_SNAKE_CASE__ = False if state.get("""add_prefix_space""" , __A ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = True if state.get("""trim_offsets""" , __A ) != trim_offsets: SCREAMING_SNAKE_CASE__ = trim_offsets SCREAMING_SNAKE_CASE__ = True if changes_to_apply: SCREAMING_SNAKE_CASE__ = getattr(__A , state.pop("""type""" ) ) SCREAMING_SNAKE_CASE__ = component_class(**__A ) setattr(self.backend_tokenizer , __A , __A ) @property def _snake_case ( self :int ) -> str: """simple docstring""" if self._mask_token is None: if self.verbose: logger.error("""Using mask_token, but it is not set yet.""" ) return None return str(self._mask_token ) @mask_token.setter def _snake_case ( self :List[Any] , __A :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else value SCREAMING_SNAKE_CASE__ = value def _snake_case ( self :Optional[Any] , *__A :Any , **__A :Tuple ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._batch_encode_plus(*__A , **__A ) def _snake_case ( self :str , *__A :List[Any] , **__A :str ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = kwargs.get("""is_split_into_words""" , __A ) if is_split_into_words and not self.add_prefix_space: raise ValueError( f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' """to use it with pretokenized inputs.""" ) return super()._encode_plus(*__A , **__A ) def _snake_case ( self :Optional[int] , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(__A , name=__A ) return tuple(__A ) def _snake_case ( self :List[Any] , __A :Dict , __A :int=None ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def _snake_case ( self :Any , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
59
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
1
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowerCamelCase = { 'configuration_pix2struct': [ 'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Pix2StructConfig', 'Pix2StructTextConfig', 'Pix2StructVisionConfig', ], 'processing_pix2struct': ['Pix2StructProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['Pix2StructImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Pix2StructPreTrainedModel', 'Pix2StructForConditionalGeneration', 'Pix2StructVisionModel', 'Pix2StructTextModel', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _snake_case ( self :int ) -> str: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
1
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class UpperCamelCase_ : def __init__( self :Tuple , __A :Any , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = 13 SCREAMING_SNAKE_CASE__ = 7 SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = 99 SCREAMING_SNAKE_CASE__ = 32 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = 37 SCREAMING_SNAKE_CASE__ = """gelu""" SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = 0.1 SCREAMING_SNAKE_CASE__ = 512 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = 0.0_2 SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = 4 SCREAMING_SNAKE_CASE__ = None def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = 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 , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :List[str] , __A :List[Any] , __A :Dict , __A :int , __A :Optional[Any] , __A :Any , __A :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModel(config=__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) SCREAMING_SNAKE_CASE__ = [input_ids, input_mask] SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Tuple , __A :Optional[int] , __A :List[str] , __A :Union[str, Any] , __A :Any , __A :List[Any] , __A :Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertForMaskedLM(config=__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Tuple , __A :int , __A :str , __A :Union[str, Any] , __A :Optional[Any] , __A :Any , __A :List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertForQuestionAnswering(config=__A ) SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """attention_mask""": input_mask, } SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self :Dict , __A :Optional[Any] , __A :Optional[Any] , __A :Dict , __A :Optional[int] , __A :List[Any] , __A :Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFDistilBertForSequenceClassification(__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :Union[str, Any] , __A :List[str] , __A :Any , __A :Optional[int] , __A :int , __A :str , __A :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_choices SCREAMING_SNAKE_CASE__ = TFDistilBertForMultipleChoice(__A ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = tf.tile(tf.expand_dims(__A , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE__ = { """input_ids""": multiple_choice_inputs_ids, """attention_mask""": multiple_choice_input_mask, } SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self :List[Any] , __A :Any , __A :Any , __A :int , __A :List[Any] , __A :str , __A :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = TFDistilBertForTokenClassification(__A ) SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__) , (SCREAMING_SNAKE_CASE__)) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) lowerCamelCase_ = ( { "feature-extraction": TFDistilBertModel, "fill-mask": TFDistilBertForMaskedLM, "question-answering": TFDistilBertForQuestionAnswering, "text-classification": TFDistilBertForSequenceClassification, "token-classification": TFDistilBertForTokenClassification, "zero-shot": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , dim=37 ) def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*__A ) def _snake_case ( self :List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*__A ) def _snake_case ( self :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*__A ) def _snake_case ( self :Dict ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*__A ) def _snake_case ( self :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*__A ) @slow def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): SCREAMING_SNAKE_CASE__ = TFDistilBertModel.from_pretrained(__A ) self.assertIsNotNone(__A ) @require_tf class UpperCamelCase_ ( unittest.TestCase ): @slow def _snake_case ( self :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TFDistilBertModel.from_pretrained("""distilbert-base-uncased""" ) SCREAMING_SNAKE_CASE__ = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE__ = model(__A )[0] SCREAMING_SNAKE_CASE__ = [1, 6, 768] self.assertEqual(output.shape , __A ) SCREAMING_SNAKE_CASE__ = tf.constant( [ [ [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9], [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4], [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , __A , atol=1E-4 )
59
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np import torch from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["input_features", "is_longer"] def __init__( self :str , __A :Tuple=64 , __A :List[str]=4_8000 , __A :Optional[Any]=480 , __A :Optional[int]=10 , __A :Dict=1024 , __A :Union[str, Any]=0.0 , __A :Optional[int]=False , __A :float = 0 , __A :float = 1_4000 , __A :int = None , __A :str = "fusion" , __A :str = "repeatpad" , **__A :Any , ) -> Optional[int]: """simple docstring""" super().__init__( feature_size=__A , sampling_rate=__A , padding_value=__A , return_attention_mask=__A , **__A , ) SCREAMING_SNAKE_CASE__ = top_db SCREAMING_SNAKE_CASE__ = truncation SCREAMING_SNAKE_CASE__ = padding SCREAMING_SNAKE_CASE__ = fft_window_size SCREAMING_SNAKE_CASE__ = (fft_window_size >> 1) + 1 SCREAMING_SNAKE_CASE__ = hop_length SCREAMING_SNAKE_CASE__ = max_length_s SCREAMING_SNAKE_CASE__ = max_length_s * sampling_rate SCREAMING_SNAKE_CASE__ = sampling_rate SCREAMING_SNAKE_CASE__ = frequency_min SCREAMING_SNAKE_CASE__ = frequency_max SCREAMING_SNAKE_CASE__ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm=__A , mel_scale="""htk""" , ) SCREAMING_SNAKE_CASE__ = mel_filter_bank( num_frequency_bins=self.nb_frequency_bins , num_mel_filters=__A , min_frequency=__A , max_frequency=__A , sampling_rate=__A , norm="""slaney""" , mel_scale="""slaney""" , ) def _snake_case ( self :List[Any] ) -> Dict[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] if "mel_filters_slaney" in output: del output["mel_filters_slaney"] return output def _snake_case ( self :Any , __A :np.array , __A :Optional[np.array] = None ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ = spectrogram( __A , window_function(self.fft_window_size , """hann""" ) , frame_length=self.fft_window_size , hop_length=self.hop_length , power=2.0 , mel_filters=__A , log_mel="""dB""" , ) return log_mel_spectrogram.T def _snake_case ( self :Optional[Any] , __A :Any , __A :Optional[int] , __A :str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = np.array_split(list(range(0 , total_frames - chunk_frames + 1 ) ) , 3 ) if len(ranges[1] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE__ = [0] if len(ranges[2] ) == 0: # if the audio is too short, we just use the first chunk SCREAMING_SNAKE_CASE__ = [0] # randomly choose index for each part SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[0] ) SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[1] ) SCREAMING_SNAKE_CASE__ = np.random.choice(ranges[2] ) SCREAMING_SNAKE_CASE__ = mel[idx_front : idx_front + chunk_frames, :] SCREAMING_SNAKE_CASE__ = mel[idx_middle : idx_middle + chunk_frames, :] SCREAMING_SNAKE_CASE__ = mel[idx_back : idx_back + chunk_frames, :] SCREAMING_SNAKE_CASE__ = torch.tensor(mel[None, None, :] ) SCREAMING_SNAKE_CASE__ = torch.nn.functional.interpolate( __A , size=[chunk_frames, 64] , mode="""bilinear""" , align_corners=__A ) SCREAMING_SNAKE_CASE__ = mel_shrink[0][0].numpy() SCREAMING_SNAKE_CASE__ = np.stack([mel_shrink, mel_chunk_front, mel_chunk_middle, mel_chunk_back] , axis=0 ) return mel_fusion def _snake_case ( self :Tuple , __A :np.array , __A :Tuple , __A :Tuple , __A :Tuple ) -> np.array: """simple docstring""" if waveform.shape[0] > max_length: if truncation == "rand_trunc": SCREAMING_SNAKE_CASE__ = True # random crop to max_length (for compatibility) -> this should be handled by self.pad SCREAMING_SNAKE_CASE__ = len(__A ) - max_length SCREAMING_SNAKE_CASE__ = np.random.randint(0 , overflow + 1 ) SCREAMING_SNAKE_CASE__ = waveform[idx : idx + max_length] SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :] elif truncation == "fusion": SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters ) SCREAMING_SNAKE_CASE__ = max_length // self.hop_length + 1 # the +1 related to how the spectrogram is computed SCREAMING_SNAKE_CASE__ = mel.shape[0] if chunk_frames == total_frames: # there is a corner case where the audio length is larger than max_length but smaller than max_length+hop_length. # In this case, we just use the whole audio. SCREAMING_SNAKE_CASE__ = np.stack([mel, mel, mel, mel] , axis=0 ) SCREAMING_SNAKE_CASE__ = False else: SCREAMING_SNAKE_CASE__ = self._random_mel_fusion(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = True else: raise NotImplementedError(f'''data_truncating {truncation} not implemented''' ) else: SCREAMING_SNAKE_CASE__ = False # only use repeat as a new possible value for padding. you repeat the audio before applying the usual max_length padding if waveform.shape[0] < max_length: if padding == "repeat": SCREAMING_SNAKE_CASE__ = int(max_length / len(__A ) ) SCREAMING_SNAKE_CASE__ = np.stack(np.tile(__A , n_repeat + 1 ) )[:max_length] if padding == "repeatpad": SCREAMING_SNAKE_CASE__ = int(max_length / len(__A ) ) SCREAMING_SNAKE_CASE__ = np.stack(np.tile(__A , __A ) ) SCREAMING_SNAKE_CASE__ = np.pad(__A , (0, max_length - waveform.shape[0]) , mode="""constant""" , constant_values=0 ) if truncation == "fusion": SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters ) SCREAMING_SNAKE_CASE__ = np.stack([input_mel, input_mel, input_mel, input_mel] , axis=0 ) else: SCREAMING_SNAKE_CASE__ = self._np_extract_fbank_features(__A , self.mel_filters_slaney )[None, :] return input_mel, longer def __call__( self :Any , __A :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __A :str = None , __A :Optional[str] = None , __A :Optional[int] = None , __A :Optional[int] = None , __A :Optional[Union[str, TensorType]] = None , **__A :List[Any] , ) -> BatchFeature: """simple docstring""" SCREAMING_SNAKE_CASE__ = truncation if truncation is not None else self.truncation SCREAMING_SNAKE_CASE__ = padding if padding else self.padding if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a''' f''' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input''' f''' was sampled with {self.sampling_rate} and not {sampling_rate}.''' ) else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""" ) SCREAMING_SNAKE_CASE__ = isinstance(__A , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'''Only mono-channel audio is supported for input to {self}''' ) SCREAMING_SNAKE_CASE__ = is_batched_numpy or ( isinstance(__A , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(__A , np.ndarray ): SCREAMING_SNAKE_CASE__ = np.asarray(__A , dtype=np.floataa ) elif isinstance(__A , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): SCREAMING_SNAKE_CASE__ = raw_speech.astype(np.floataa ) # always return batch if not is_batched: SCREAMING_SNAKE_CASE__ = [np.asarray(__A )] # convert to mel spectrogram, truncate and pad if needed. SCREAMING_SNAKE_CASE__ = [ self._get_input_mel(__A , max_length if max_length else self.nb_max_samples , __A , __A ) for waveform in raw_speech ] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for mel, longer in padded_inputs: input_mel.append(__A ) is_longer.append(__A ) if truncation == "fusion" and sum(__A ) == 0: # if no audio is longer than 10s, then randomly select one audio to be longer SCREAMING_SNAKE_CASE__ = np.random.randint(0 , len(__A ) ) SCREAMING_SNAKE_CASE__ = True if isinstance(input_mel[0] , __A ): SCREAMING_SNAKE_CASE__ = [np.asarray(__A , dtype=np.floataa ) for feature in input_mel] # is_longer is a list of bool SCREAMING_SNAKE_CASE__ = [[longer] for longer in is_longer] SCREAMING_SNAKE_CASE__ = {"""input_features""": input_mel, """is_longer""": is_longer} SCREAMING_SNAKE_CASE__ = BatchFeature(__A ) if return_tensors is not None: SCREAMING_SNAKE_CASE__ = input_features.convert_to_tensors(__A ) return input_features
59
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
1
import math from numpy import inf from scipy.integrate import quad def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float ): if num <= 0: raise ValueError("""math domain error""" ) return quad(UpperCamelCase__ , 0 , UpperCamelCase__ , args=(UpperCamelCase__) )[0] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return math.pow(UpperCamelCase__ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
1
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel _lowerCamelCase = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class UpperCamelCase_ ( unittest.TestCase ): @classmethod def _snake_case ( cls :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = TOKEN HfFolder.save_token(__A ) @classmethod def _snake_case ( cls :str ) -> List[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="""test-model-flax""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-model-flax-org""" ) except HTTPError: pass def _snake_case ( self :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) model.push_to_hub("""test-model-flax""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="""test-model-flax""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(__A , repo_id="""test-model-flax""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(f'''{USER}/test-model-flax''' ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) model.push_to_hub("""valid_org/test-model-flax-org""" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-model-flax-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( __A , repo_id="""valid_org/test-model-flax-org""" , push_to_hub=__A , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained("""valid_org/test-model-flax-org""" ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE__ = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE__ = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(__A , 1E-3 , msg=f'''{key} not identical''' ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = flatten_dict(modela.params ) SCREAMING_SNAKE_CASE__ = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1e-4: SCREAMING_SNAKE_CASE__ = False return models_are_equal @require_flax class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) SCREAMING_SNAKE_CASE__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__A , __A ) ) with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertTrue(check_models_equal(__A , __A ) ) def _snake_case ( self :Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = BertConfig.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) SCREAMING_SNAKE_CASE__ = FlaxBertModel(__A ) SCREAMING_SNAKE_CASE__ = """bert""" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(__A , __A ) , max_shard_size="""10KB""" ) with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertTrue(check_models_equal(__A , __A ) ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """bert""" SCREAMING_SNAKE_CASE__ = """hf-internal-testing/tiny-random-bert-subfolder""" with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertIsNotNone(__A ) def _snake_case ( self :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """bert""" SCREAMING_SNAKE_CASE__ = """hf-internal-testing/tiny-random-bert-sharded-subfolder""" with self.assertRaises(__A ): SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = FlaxBertModel.from_pretrained(__A , subfolder=__A ) self.assertIsNotNone(__A )
59
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = k_size // 2 SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mgrid[0 - center : k_size - center, 0 - center : k_size - center] SCREAMING_SNAKE_CASE__ = 1 / (2 * pi * sigma) * exp(-(square(UpperCamelCase__ ) + square(UpperCamelCase__ )) / (2 * square(UpperCamelCase__ )) ) return g def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: List[str] , UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image.shape[0], image.shape[1] # dst image height and width SCREAMING_SNAKE_CASE__ = height - k_size + 1 SCREAMING_SNAKE_CASE__ = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows SCREAMING_SNAKE_CASE__ = zeros((dst_height * dst_width, k_size * k_size) ) SCREAMING_SNAKE_CASE__ = 0 for i, j in product(range(UpperCamelCase__ ) , range(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = ravel(image[i : i + k_size, j : j + k_size] ) SCREAMING_SNAKE_CASE__ = window row += 1 # turn the kernel into shape(k*k, 1) SCREAMING_SNAKE_CASE__ = gen_gaussian_kernel(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = ravel(UpperCamelCase__ ) # reshape and get the dst image SCREAMING_SNAKE_CASE__ = dot(UpperCamelCase__ , UpperCamelCase__ ).reshape(UpperCamelCase__ , UpperCamelCase__ ).astype(UpperCamelCase__ ) return dst if __name__ == "__main__": # read original image _lowerCamelCase = imread(R'../image_data/lena.jpg') # turn image in gray scale value _lowerCamelCase = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size _lowerCamelCase = gaussian_filter(gray, 3, sigma=1) _lowerCamelCase = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow('gaussian filter with 3x3 mask', gaussianaxa) imshow('gaussian filter with 5x5 mask', gaussianaxa) waitKey()
59
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
1
from ...utils import is_note_seq_available, is_transformers_available, is_torch_available from ...utils import OptionalDependencyNotAvailable try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .notes_encoder import SpectrogramNotesEncoder from .continous_encoder import SpectrogramContEncoder from .pipeline_spectrogram_diffusion import ( SpectrogramContEncoder, SpectrogramDiffusionPipeline, TaFilmDecoder, ) try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .midi_utils import MidiProcessor
59
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase_ ( unittest.TestCase ): def __init__( self :Dict , __A :List[Any] , __A :List[str]=3 , __A :Any=32 , __A :Dict=3 , __A :Optional[int]=10 , __A :Dict=[10, 20, 30, 40] , __A :List[str]=[1, 1, 2, 1] , __A :int=True , __A :str=True , __A :List[str]="relu" , __A :Optional[int]=3 , __A :List[Any]=None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embeddings_size SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = scope SCREAMING_SNAKE_CASE__ = len(__A ) def _snake_case ( self :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, pixel_values def _snake_case ( self :Optional[int] ) -> Tuple: """simple docstring""" return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def _snake_case ( self :str , __A :int , __A :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetModel(config=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def _snake_case ( self :Optional[Any] , __A :Dict , __A :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.num_labels SCREAMING_SNAKE_CASE__ = FlaxRegNetForImageClassification(config=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , has_text_modality=__A ) def _snake_case ( self :List[str] ) -> 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 _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" return def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__A ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def _snake_case ( self :int ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def _snake_case ( self :Tuple ) -> List[Any]: """simple docstring""" pass def _snake_case ( self :Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __A ) def _snake_case ( self :Union[str, Any] ) -> str: """simple docstring""" def check_hidden_states_output(__A :Optional[int] , __A :str , __A :Optional[Any] ): SCREAMING_SNAKE_CASE__ = model_class(__A ) SCREAMING_SNAKE_CASE__ = model(**self._prepare_for_class(__A , __A ) ) SCREAMING_SNAKE_CASE__ = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ = self.model_tester.num_stages self.assertEqual(len(__A ) , expected_num_stages + 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ = True check_hidden_states_output(__A , __A , __A ) def _snake_case ( self :Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE__ = self._prepare_for_class(__A , __A ) SCREAMING_SNAKE_CASE__ = model_class(__A ) @jax.jit def model_jitted(__A :Dict , **__A :Any ): return model(pixel_values=__A , **__A ) with self.subTest("""JIT Enabled""" ): SCREAMING_SNAKE_CASE__ = model_jitted(**__A ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__ = model_jitted(**__A ).to_tuple() self.assertEqual(len(__A ) , len(__A ) ) for jitted_output, output in zip(__A , __A ): self.assertEqual(jitted_output.shape , output.shape ) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class UpperCamelCase_ ( unittest.TestCase ): @cached_property def _snake_case ( self :List[Any] ) -> Optional[Any]: """simple docstring""" return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) SCREAMING_SNAKE_CASE__ = self.default_image_processor SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=__A , return_tensors="""np""" ) SCREAMING_SNAKE_CASE__ = model(**__A ) # verify the logits SCREAMING_SNAKE_CASE__ = (1, 1000) self.assertEqual(outputs.logits.shape , __A ) SCREAMING_SNAKE_CASE__ = jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __A , atol=1E-4 ) )
59
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
1
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): @register_to_config def __init__( self :Optional[Any] , __A :int = 768 , ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = nn.Parameter(torch.zeros(1 , __A ) ) SCREAMING_SNAKE_CASE__ = nn.Parameter(torch.ones(1 , __A ) ) def _snake_case ( self :List[str] , __A :Optional[Union[str, torch.device]] = None , __A :Optional[torch.dtype] = None , ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = nn.Parameter(self.mean.to(__A ).to(__A ) ) SCREAMING_SNAKE_CASE__ = nn.Parameter(self.std.to(__A ).to(__A ) ) return self def _snake_case ( self :List[Any] , __A :str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = (embeds - self.mean) * 1.0 / self.std return embeds def _snake_case ( self :Optional[Any] , __A :int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = (embeds * self.std) + self.mean return embeds
59
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
1
import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :Optional[int] , __A :List[str] , __A :Tuple , __A :int=1024 , __A :int=1024 , __A :str=3.6 ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = tokenizer SCREAMING_SNAKE_CASE__ = tokenizer.bos_token_id SCREAMING_SNAKE_CASE__ = dataset SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = seq_length * chars_per_token * num_of_sequences def __iter__( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = iter(self.dataset ) SCREAMING_SNAKE_CASE__ = True while more_examples: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(__A )["""content"""] ) buffer_len += len(buffer[-1] ) except StopIteration: SCREAMING_SNAKE_CASE__ = False break SCREAMING_SNAKE_CASE__ = tokenizer(__A , truncation=__A )["""input_ids"""] SCREAMING_SNAKE_CASE__ = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(__A ) , self.seq_length ): SCREAMING_SNAKE_CASE__ = all_token_ids[i : i + self.seq_length] if len(__A ) == self.seq_length: yield torch.tensor(__A ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = {"""streaming""": True} SCREAMING_SNAKE_CASE__ = load_dataset(args.dataset_name , split="""train""" , **UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = ConstantLengthDataset(UpperCamelCase__ , UpperCamelCase__ , seq_length=args.seq_length ) SCREAMING_SNAKE_CASE__ = DataLoader(UpperCamelCase__ , batch_size=args.batch_size ) return eval_dataloader def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): model.eval() SCREAMING_SNAKE_CASE__ = [] for step, batch in enumerate(UpperCamelCase__ ): with torch.no_grad(): SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ , labels=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(UpperCamelCase__ ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break SCREAMING_SNAKE_CASE__ = torch.mean(torch.cat(UpperCamelCase__ ) ) try: SCREAMING_SNAKE_CASE__ = torch.exp(UpperCamelCase__ ) except OverflowError: SCREAMING_SNAKE_CASE__ = float("""inf""" ) return loss.item(), perplexity.item() # Setup Accelerator _lowerCamelCase = Accelerator() # Parse configuration _lowerCamelCase = HfArgumentParser(EvaluationArguments) _lowerCamelCase = parser.parse_args() set_seed(args.seed) # Logging _lowerCamelCase = logging.getLogger(__name__) logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO ) # Load model and tokenizer _lowerCamelCase = AutoModelForCausalLM.from_pretrained(args.model_ckpt) _lowerCamelCase = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader _lowerCamelCase = create_dataloader(args) # Prepare everything with our `accelerator`. _lowerCamelCase , _lowerCamelCase = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info('Evaluating and saving model after training') _lowerCamelCase , _lowerCamelCase = evaluate(args) logger.info(F'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
59
# 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 = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
import operator as op def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = lambda UpperCamelCase__ , UpperCamelCase__ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE__ = { """^""": 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(UpperCamelCase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(UpperCamelCase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ("""push(""" + x + """)""").ljust(12 ) , """,""".join(UpperCamelCase__ ) , sep=""" | """ ) else: SCREAMING_SNAKE_CASE__ = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + b + """)""").ljust(12 ) , """,""".join(UpperCamelCase__ ) , sep=""" | """ ) SCREAMING_SNAKE_CASE__ = stack.pop() # pop stack # output in tabular format print("""""".rjust(8 ) , ("""pop(""" + a + """)""").ljust(12 ) , """,""".join(UpperCamelCase__ ) , sep=""" | """ ) stack.append( str(opr[x](int(UpperCamelCase__ ) , int(UpperCamelCase__ ) ) ) ) # 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(UpperCamelCase__ ) , sep=""" | """ , ) return int(stack[0] ) if __name__ == "__main__": _lowerCamelCase = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ') print('\n\tResult = ', solve(Postfix))
59
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
1
import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): # Initialise PyTorch model SCREAMING_SNAKE_CASE__ = TaConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TaForConditionalGeneration(UpperCamelCase__ ) # Load weights from tf checkpoint load_tf_weights_in_ta(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model print(f'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained T5 model. \nThis specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
59
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
1
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class UpperCamelCase_ : def __init__( self :Tuple , __A :str , __A :Optional[int]=13 , __A :Union[str, Any]=7 , __A :Optional[Any]=True , __A :Any=True , __A :List[Any]=False , __A :List[Any]=True , __A :Any=99 , __A :List[str]=32 , __A :int=5 , __A :Any=4 , __A :List[Any]=37 , __A :int="gelu" , __A :Tuple=0.1 , __A :Optional[int]=0.1 , __A :Dict=512 , __A :Optional[Any]=16 , __A :List[Any]=2 , __A :Dict=0.0_2 , __A :Dict=3 , __A :Dict=4 , __A :int=None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = seq_length SCREAMING_SNAKE_CASE__ = is_training SCREAMING_SNAKE_CASE__ = use_input_mask SCREAMING_SNAKE_CASE__ = use_token_type_ids SCREAMING_SNAKE_CASE__ = use_labels SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = max_position_embeddings SCREAMING_SNAKE_CASE__ = type_vocab_size SCREAMING_SNAKE_CASE__ = type_sequence_label_size SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = num_labels SCREAMING_SNAKE_CASE__ = num_choices SCREAMING_SNAKE_CASE__ = scope def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None if self.use_labels: SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self :Optional[int] ) -> int: """simple docstring""" return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__A , initializer_range=self.initializer_range , use_stable_embedding=__A , ) def _snake_case ( self :Optional[Any] , __A :Optional[int] , __A :Optional[Any] , __A :Union[str, Any] , __A :List[str] , __A :Dict , __A :Dict , __A :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaModel(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A ) SCREAMING_SNAKE_CASE__ = model(__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Optional[int] , __A :Union[str, Any] , __A :List[Any] , __A :str , __A :Dict , __A :Dict , __A :Optional[Any] , __A :Tuple , __A :Dict , __A :Union[str, Any] , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , ) SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , ) SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self :Any , __A :Tuple , __A :Any , __A :Optional[int] , __A :str , __A :Optional[Any] , __A :List[Any] , __A :str , __A :Tuple , __A :List[Any] , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaForCausalLM(config=__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self :Union[str, Any] , __A :List[str] , __A :Optional[int] , __A :Dict , __A :Tuple , __A :Tuple , __A :Optional[Any] , __A :str , __A :Optional[Any] , __A :Tuple , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = OpenLlamaForCausalLM(config=__A ) model.to(__A ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , use_cache=__A , ) SCREAMING_SNAKE_CASE__ = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , output_hidden_states=__A , )["""hidden_states"""][0] SCREAMING_SNAKE_CASE__ = model( __A , attention_mask=__A , encoder_hidden_states=__A , encoder_attention_mask=__A , past_key_values=__A , output_hidden_states=__A , )["""hidden_states"""][0] # select random slice SCREAMING_SNAKE_CASE__ = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__A , __A , atol=1E-3 ) ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) = config_and_inputs SCREAMING_SNAKE_CASE__ = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) lowerCamelCase_ = (OpenLlamaForCausalLM,) if is_torch_available() else () lowerCamelCase_ = ( { "feature-extraction": OpenLlamaModel, "text-classification": OpenLlamaForSequenceClassification, "text-generation": OpenLlamaForCausalLM, "zero-shot": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase_ = False lowerCamelCase_ = False def _snake_case ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenLlamaModelTester(self ) SCREAMING_SNAKE_CASE__ = ConfigTester(self , config_class=__A , hidden_size=37 ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ = type self.model_tester.create_and_check_model(*__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = """single_label_classification""" SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = 3 SCREAMING_SNAKE_CASE__ = """multi_label_classification""" SCREAMING_SNAKE_CASE__ = input_dict["""input_ids"""] SCREAMING_SNAKE_CASE__ = input_ids.ne(1 ).to(__A ) SCREAMING_SNAKE_CASE__ = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ = OpenLlamaForSequenceClassification(__A ) model.to(__A ) model.eval() SCREAMING_SNAKE_CASE__ = model(__A , attention_mask=__A , labels=__A ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""Open-Llama buffers include complex numbers, which breaks this test""" ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def _snake_case ( self :Tuple , __A :str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ = ids_tensor([1, 10] , config.vocab_size ) SCREAMING_SNAKE_CASE__ = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) original_model.to(__A ) original_model.eval() SCREAMING_SNAKE_CASE__ = original_model(__A ).last_hidden_state SCREAMING_SNAKE_CASE__ = original_model(__A ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights SCREAMING_SNAKE_CASE__ = {"""type""": scaling_type, """factor""": 1_0.0} SCREAMING_SNAKE_CASE__ = OpenLlamaModel(__A ) scaled_model.to(__A ) scaled_model.eval() SCREAMING_SNAKE_CASE__ = scaled_model(__A ).last_hidden_state SCREAMING_SNAKE_CASE__ = scaled_model(__A ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__A , __A , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(__A , __A , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__A , __A , atol=1E-5 ) )
59
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import 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 UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = ShapEPipeline lowerCamelCase_ = ["prompt"] lowerCamelCase_ = ["prompt"] lowerCamelCase_ = [ "num_images_per_prompt", "num_inference_steps", "generator", "latents", "guidance_scale", "frame_size", "output_type", "return_dict", ] lowerCamelCase_ = False @property def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" return 32 @property def _snake_case ( self :Dict ) -> str: """simple docstring""" return 32 @property def _snake_case ( self :str ) -> Tuple: """simple docstring""" return self.time_input_dim * 4 @property def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" return 8 @property def _snake_case ( self :Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def _snake_case ( self :Tuple ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__A ) @property def _snake_case ( self :str ) -> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """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""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } SCREAMING_SNAKE_CASE__ = PriorTransformer(**__A ) return model @property def _snake_case ( self :List[Any] ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ = { """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, ), } SCREAMING_SNAKE_CASE__ = ShapERenderer(**__A ) return model def _snake_case ( self :int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.dummy_prior SCREAMING_SNAKE_CASE__ = self.dummy_text_encoder SCREAMING_SNAKE_CASE__ = self.dummy_tokenizer SCREAMING_SNAKE_CASE__ = self.dummy_renderer SCREAMING_SNAKE_CASE__ = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=__A , clip_sample=__A , clip_sample_range=1.0 , ) SCREAMING_SNAKE_CASE__ = { """prior""": prior, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """renderer""": renderer, """scheduler""": scheduler, } return components def _snake_case ( self :List[Any] , __A :Tuple , __A :List[str]=0 ) -> Optional[int]: """simple docstring""" if str(__A ).startswith("""mps""" ): SCREAMING_SNAKE_CASE__ = torch.manual_seed(__A ) else: SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(__A ) SCREAMING_SNAKE_CASE__ = { """prompt""": """horse""", """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = """cpu""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = pipe(**self.get_dummy_inputs(__A ) ) SCREAMING_SNAKE_CASE__ = output.images[0] SCREAMING_SNAKE_CASE__ = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) SCREAMING_SNAKE_CASE__ = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def _snake_case ( self :Dict ) -> Any: """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def _snake_case ( self :Union[str, Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = torch_device == """cpu""" SCREAMING_SNAKE_CASE__ = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=__A , relax_max_difference=__A , ) def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_dummy_components() SCREAMING_SNAKE_CASE__ = self.pipeline_class(**__A ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = 2 SCREAMING_SNAKE_CASE__ = self.get_dummy_inputs(__A ) for key in inputs.keys(): if key in self.batch_params: SCREAMING_SNAKE_CASE__ = batch_size * [inputs[key]] SCREAMING_SNAKE_CASE__ = pipe(**__A , num_images_per_prompt=__A )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_np_out.npy""" ) SCREAMING_SNAKE_CASE__ = ShapEPipeline.from_pretrained("""openai/shap-e""" ) SCREAMING_SNAKE_CASE__ = pipe.to(__A ) pipe.set_progress_bar_config(disable=__A ) SCREAMING_SNAKE_CASE__ = torch.Generator(device=__A ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ = pipe( """a shark""" , generator=__A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(__A , __A )
59
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..bit import BitConfig _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'Intel/dpt-large': 'https://huggingface.co/Intel/dpt-large/resolve/main/config.json', # See all DPT models at https://huggingface.co/models?filter=dpt } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "dpt" def __init__( self :Union[str, Any] , __A :int=768 , __A :Optional[int]=12 , __A :Optional[Any]=12 , __A :Dict=3072 , __A :Optional[Any]="gelu" , __A :Union[str, Any]=0.0 , __A :Optional[Any]=0.0 , __A :int=0.0_2 , __A :Optional[Any]=1E-12 , __A :Union[str, Any]=384 , __A :int=16 , __A :Tuple=3 , __A :Tuple=False , __A :int=True , __A :Optional[Any]=[2, 5, 8, 11] , __A :Any="project" , __A :Any=[4, 2, 1, 0.5] , __A :str=[96, 192, 384, 768] , __A :int=256 , __A :Union[str, Any]=-1 , __A :List[Any]=False , __A :int=True , __A :List[Any]=0.4 , __A :Any=255 , __A :Any=0.1 , __A :Tuple=[1, 1024, 24, 24] , __A :int=[0, 1] , __A :Union[str, Any]=None , **__A :Dict , ) -> Optional[Any]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = is_hybrid if self.is_hybrid: if backbone_config is None: logger.info("""Initializing the config with a `BiT` backbone.""" ) SCREAMING_SNAKE_CASE__ = { """global_padding""": """same""", """layer_type""": """bottleneck""", """depths""": [3, 4, 9], """out_features""": ["""stage1""", """stage2""", """stage3"""], """embedding_dynamic_padding""": True, } SCREAMING_SNAKE_CASE__ = BitConfig(**__A ) elif isinstance(__A , __A ): logger.info("""Initializing the config with a `BiT` backbone.""" ) SCREAMING_SNAKE_CASE__ = BitConfig(**__A ) elif isinstance(__A , __A ): SCREAMING_SNAKE_CASE__ = backbone_config else: raise ValueError( f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.''' ) SCREAMING_SNAKE_CASE__ = backbone_featmap_shape SCREAMING_SNAKE_CASE__ = neck_ignore_stages if readout_type != "project": raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode.""" ) else: SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = intermediate_size SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = backbone_out_indices if readout_type not in ["ignore", "add", "project"]: raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']""" ) SCREAMING_SNAKE_CASE__ = readout_type SCREAMING_SNAKE_CASE__ = reassemble_factors SCREAMING_SNAKE_CASE__ = neck_hidden_sizes SCREAMING_SNAKE_CASE__ = fusion_hidden_size SCREAMING_SNAKE_CASE__ = head_in_index SCREAMING_SNAKE_CASE__ = use_batch_norm_in_fusion_residual # auxiliary head attributes (semantic segmentation) SCREAMING_SNAKE_CASE__ = use_auxiliary_head SCREAMING_SNAKE_CASE__ = auxiliary_loss_weight SCREAMING_SNAKE_CASE__ = semantic_loss_ignore_index SCREAMING_SNAKE_CASE__ = semantic_classifier_dropout def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: SCREAMING_SNAKE_CASE__ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
1
_lowerCamelCase = tuple[float, float, float] _lowerCamelCase = tuple[float, float, float] def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Pointad , UpperCamelCase__: Pointad ): SCREAMING_SNAKE_CASE__ = end_pointa[0] - end_pointa[0] SCREAMING_SNAKE_CASE__ = end_pointa[1] - end_pointa[1] SCREAMING_SNAKE_CASE__ = end_pointa[2] - end_pointa[2] return (x, y, z) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Vectorad , UpperCamelCase__: Vectorad ): SCREAMING_SNAKE_CASE__ = ab[1] * ac[2] - ab[2] * ac[1] # *i SCREAMING_SNAKE_CASE__ = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j SCREAMING_SNAKE_CASE__ = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Vectorad , UpperCamelCase__: int ): return tuple(round(UpperCamelCase__ , UpperCamelCase__ ) for x in vector ) == (0, 0, 0) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Pointad , UpperCamelCase__: Pointad , UpperCamelCase__: Pointad , UpperCamelCase__: int = 10 ): SCREAMING_SNAKE_CASE__ = create_vector(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = create_vector(UpperCamelCase__ , UpperCamelCase__ ) return is_zero_vector(get_ad_vectors_cross(UpperCamelCase__ , UpperCamelCase__ ) , UpperCamelCase__ )
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = '▁' _lowerCamelCase = {'vocab_file': 'sentencepiece.bpe.model'} _lowerCamelCase = { 'vocab_file': { 'facebook/mbart-large-en-ro': ( 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model' ), 'facebook/mbart-large-cc25': ( 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model' ), } } _lowerCamelCase = { 'facebook/mbart-large-en-ro': 1024, 'facebook/mbart-large-cc25': 1024, } # fmt: off _lowerCamelCase = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN'] class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = VOCAB_FILES_NAMES lowerCamelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase_ = ["input_ids", "attention_mask"] lowerCamelCase_ = [] lowerCamelCase_ = [] def __init__( self :List[str] , __A :Optional[int] , __A :Tuple="<s>" , __A :Optional[Any]="</s>" , __A :List[Any]="</s>" , __A :Tuple="<s>" , __A :Optional[Any]="<unk>" , __A :str="<pad>" , __A :Tuple="<mask>" , __A :str=None , __A :str=None , __A :List[Any]=None , __A :Optional[Dict[str, Any]] = None , __A :int=None , **__A :Dict , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = AddedToken(__A , lstrip=__A , rstrip=__A ) if isinstance(__A , __A ) else mask_token SCREAMING_SNAKE_CASE__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__A , eos_token=__A , unk_token=__A , sep_token=__A , cls_token=__A , pad_token=__A , mask_token=__A , tokenizer_file=__A , src_lang=__A , tgt_lang=__A , additional_special_tokens=__A , sp_model_kwargs=self.sp_model_kwargs , **__A , ) SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__A ) ) SCREAMING_SNAKE_CASE__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token SCREAMING_SNAKE_CASE__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = len(self.sp_model ) SCREAMING_SNAKE_CASE__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(__A ) } SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.lang_code_to_id.items()} SCREAMING_SNAKE_CASE__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) SCREAMING_SNAKE_CASE__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} SCREAMING_SNAKE_CASE__ = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) SCREAMING_SNAKE_CASE__ = src_lang if src_lang is not None else """en_XX""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[self._src_lang] SCREAMING_SNAKE_CASE__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.__dict__.copy() SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() return state def __setstate__( self :Tuple , __A :List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _snake_case ( self :Optional[Any] ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _snake_case ( self :Optional[int] , __A :str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _snake_case ( self :Dict , __A :List[int] , __A :Optional[List[int]] = None , __A :bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = [1] * len(self.prefix_tokens ) SCREAMING_SNAKE_CASE__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def _snake_case ( self :Any , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _snake_case ( self :List[Any] , __A :List[int] , __A :Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _snake_case ( self :List[Any] , __A :str , __A :str , __A :Optional[str] , __A :Optional[str] , **__A :List[str] ) -> Union[str, Any]: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = self(__A , add_special_tokens=__A , return_tensors=__A , **__A ) SCREAMING_SNAKE_CASE__ = self.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tgt_lang_id return inputs def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = {self.convert_ids_to_tokens(__A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _snake_case ( self :List[str] , __A :str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__A , out_type=__A ) def _snake_case ( self :str , __A :Tuple ) -> Optional[int]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] SCREAMING_SNAKE_CASE__ = self.sp_model.PieceToId(__A ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _snake_case ( self :Optional[int] , __A :Dict ) -> Dict: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _snake_case ( self :Optional[Any] , __A :Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = """""".join(__A ).replace(__A , """ """ ).strip() return out_string def _snake_case ( self :int , __A :str , __A :Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ = os.path.join( __A , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __A ) elif not os.path.isfile(self.vocab_file ): with open(__A , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ = self.sp_model.serialized_model_proto() fi.write(__A ) return (out_vocab_file,) def _snake_case ( self :Optional[int] , __A :List[str] , __A :str = "en_XX" , __A :Optional[List[str]] = None , __A :str = "ro_RO" , **__A :Optional[int] , ) -> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ = src_lang SCREAMING_SNAKE_CASE__ = tgt_lang return super().prepare_seqaseq_batch(__A , __A , **__A ) def _snake_case ( self :Dict ) -> Dict: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _snake_case ( self :str , __A :Union[str, Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[src_lang] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code] def _snake_case ( self :int , __A :str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.lang_code_to_id[lang] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [self.eos_token_id, self.cur_lang_code]
59
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
1
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) _lowerCamelCase = logging.getLogger() _lowerCamelCase = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Optional[int] , __A :Union[str, Any] ) -> Dict: """simple docstring""" os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = {"""source""": """What is love ?""", """target""": """life"""} SCREAMING_SNAKE_CASE__ = {"""train""": 12, """val""": 2, """test""": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: SCREAMING_SNAKE_CASE__ = """\n""".join([contents[field]] * n_lines[split] ) with open(os.path.join(__A , f'''{split}.{field}''' ) , """w""" ) as f: f.write(__A ) def _snake_case ( self :List[str] , __A :int , __A :str = "pytorch" ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE__ = os.path.join(__A , """output""" ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """data""" ) self._create_dummy_data(data_dir=__A ) SCREAMING_SNAKE_CASE__ = f''' --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ '''.split() if gpus > 0: testargs.append(f'''--gpus={gpus}''' ) if is_apex_available(): testargs.append("""--fp16""" ) else: testargs.append("""--gpus=0""" ) testargs.append("""--distributed_backend=ddp_cpu""" ) testargs.append("""--num_processes=2""" ) SCREAMING_SNAKE_CASE__ = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(__A , env=self.get_env() ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """metrics.json""" ) with open(__A ) as f: SCREAMING_SNAKE_CASE__ = json.load(__A ) return result @require_torch_gpu def _snake_case ( self :Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_gpu @require_ray def _snake_case ( self :int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 ) @require_torch_multi_gpu @require_ray def _snake_case ( self :int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self._run_finetune(gpus=1 , distributed_retriever="""ray""" ) self.assertGreaterEqual(result["""test"""][0]["""test_avg_em"""] , 0.2 )
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
1
from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: Optional[str] = None ): if version.parse(hfh.__version__ ).release < version.parse("""0.11.0""" ).release: # old versions of hfh don't url-encode the file path SCREAMING_SNAKE_CASE__ = quote(UpperCamelCase__ ) return hfh.hf_hub_url(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" , revision=UpperCamelCase__ )
59
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
1
import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": _lowerCamelCase = pd.read_csv('sample_data.csv', header=None) _lowerCamelCase = df.shape[:1][0] # If you're using some other dataset input the target column _lowerCamelCase = df.iloc[:, 1:2] _lowerCamelCase = actual_data.values.reshape(len_data, 1) _lowerCamelCase = MinMaxScaler().fit_transform(actual_data) _lowerCamelCase = 10 _lowerCamelCase = 5 _lowerCamelCase = 20 _lowerCamelCase = len_data - periods * look_back _lowerCamelCase = actual_data[:division] _lowerCamelCase = actual_data[division - look_back :] _lowerCamelCase , _lowerCamelCase = [], [] _lowerCamelCase , _lowerCamelCase = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) _lowerCamelCase = np.array(train_x) _lowerCamelCase = np.array(test_x) _lowerCamelCase = np.array([list(i.ravel()) for i in train_y]) _lowerCamelCase = np.array([list(i.ravel()) for i in test_y]) _lowerCamelCase = Sequential() model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(128, 1))) model.add(Dense(forward_days)) model.compile(loss='mean_squared_error', optimizer='adam') _lowerCamelCase = model.fit( x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4 ) _lowerCamelCase = model.predict(x_test)
59
def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [] for data in source_data: for i, el in enumerate(UpperCamelCase__ ): if len(UpperCamelCase__ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(UpperCamelCase__ ) ) return data_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = [] for dlist, weight in zip(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = min(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = max(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: SCREAMING_SNAKE_CASE__ = f'''Invalid weight of {weight:f} provided''' raise ValueError(UpperCamelCase__ ) score_lists.append(UpperCamelCase__ ) return score_lists def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] ): SCREAMING_SNAKE_CASE__ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = final_scores[j] + ele return final_scores def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[float]] , UpperCamelCase__: list[int] ): SCREAMING_SNAKE_CASE__ = get_data(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = calculate_each_score(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = generate_final_scores(UpperCamelCase__ ) # append scores to source data for i, ele in enumerate(UpperCamelCase__ ): source_data[i].append(UpperCamelCase__ ) return source_data
59
1
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class UpperCamelCase_ ( UpperCamelCase__ ): def _snake_case ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ = 8 # DPR tok SCREAMING_SNAKE_CASE__ = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing""", """,""", """low""", """lowest""", ] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """dpr_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , DPR_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] ) ) # BART tok SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """bart_tokenizer""" ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , BART_VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Tuple ) -> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , """dpr_tokenizer""" ) ) def _snake_case ( self :Tuple ) -> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , """bart_tokenizer""" ) ) def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" shutil.rmtree(self.tmpdirname ) @require_tokenizers def _snake_case ( self :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , """rag_tokenizer""" ) SCREAMING_SNAKE_CASE__ = RagConfig(question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() ) SCREAMING_SNAKE_CASE__ = RagTokenizer(question_encoder=self.get_dpr_tokenizer() , generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(__A ) rag_tokenizer.save_pretrained(__A ) SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained(__A , config=__A ) self.assertIsInstance(new_rag_tokenizer.question_encoder , __A ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab() , rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator , __A ) self.assertEqual(new_rag_tokenizer.generator.get_vocab() , rag_tokenizer.generator.get_vocab() ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained("""facebook/rag-token-nq""" ) SCREAMING_SNAKE_CASE__ = [ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] SCREAMING_SNAKE_CASE__ = tokenizer(__A ) self.assertIsNotNone(__A ) @slow def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = RagTokenizer.from_pretrained("""facebook/rag-sequence-nq""" ) SCREAMING_SNAKE_CASE__ = [ """who got the first nobel prize in physics""", """when is the next deadpool movie being released""", """which mode is used for short wave broadcast service""", """who is the owner of reading football club""", """when is the next scandal episode coming out""", """when is the last time the philadelphia won the superbowl""", """what is the most current adobe flash player version""", """how many episodes are there in dragon ball z""", """what is the first step in the evolution of the eye""", """where is gall bladder situated in human body""", """what is the main mineral in lithium batteries""", """who is the president of usa right now""", """where do the greasers live in the outsiders""", """panda is a national animal of which country""", """what is the name of manchester united stadium""", ] SCREAMING_SNAKE_CASE__ = tokenizer(__A ) self.assertIsNotNone(__A )
59
import warnings from functools import wraps from typing import Callable def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Callable ): @wraps(UpperCamelCase__ ) def _inner_fn(*UpperCamelCase__: Dict , **UpperCamelCase__: Any ): warnings.warn( (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') , UpperCamelCase__ , ) return fn(*UpperCamelCase__ , **UpperCamelCase__ ) return _inner_fn
59
1
from math import pow def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: int , ): if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count SCREAMING_SNAKE_CASE__ = int(pow(UpperCamelCase__ , UpperCamelCase__ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = backtrack( UpperCamelCase__ , UpperCamelCase__ , current_number + 1 , UpperCamelCase__ , UpperCamelCase__ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = backtrack( UpperCamelCase__ , UpperCamelCase__ , current_number + 1 , UpperCamelCase__ , UpperCamelCase__ ) return current_sum, solutions_count def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: int ): if not (1 <= needed_sum <= 1_000 and 2 <= power <= 10): raise ValueError( """Invalid input\n""" """needed_sum must be between 1 and 1000, power between 2 and 10.""" ) return backtrack(UpperCamelCase__ , UpperCamelCase__ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
59
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _snake_case ( self :int ) -> str: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = DPTConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE__ = 1_024 SCREAMING_SNAKE_CASE__ = 4_096 SCREAMING_SNAKE_CASE__ = 24 SCREAMING_SNAKE_CASE__ = 16 SCREAMING_SNAKE_CASE__ = [5, 11, 17, 23] SCREAMING_SNAKE_CASE__ = [256, 512, 1_024, 1_024] SCREAMING_SNAKE_CASE__ = (1, 384, 384) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = 150 SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = """ade20k-id2label.json""" SCREAMING_SNAKE_CASE__ = json.load(open(cached_download(hf_hub_url(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = [1, 150, 480, 480] return config, expected_shape def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ = ["""pretrained.model.head.weight""", """pretrained.model.head.bias"""] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.model""" , """dpt.encoder""" ) if "pretrained.model" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.model""" , """dpt.embeddings""" ) if "patch_embed" in name: SCREAMING_SNAKE_CASE__ = name.replace("""patch_embed""" , """patch_embeddings""" ) if "pos_embed" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pos_embed""" , """position_embeddings""" ) if "attn.proj" in name: SCREAMING_SNAKE_CASE__ = name.replace("""attn.proj""" , """attention.output.dense""" ) if "proj" in name and "project" not in name: SCREAMING_SNAKE_CASE__ = name.replace("""proj""" , """projection""" ) if "blocks" in name: SCREAMING_SNAKE_CASE__ = name.replace("""blocks""" , """layer""" ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""mlp.fc2""" , """output.dense""" ) if "norm1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""norm2""" , """layernorm_after""" ) if "scratch.output_conv" in name: SCREAMING_SNAKE_CASE__ = name.replace("""scratch.output_conv""" , """head""" ) if "scratch" in name: SCREAMING_SNAKE_CASE__ = name.replace("""scratch""" , """neck""" ) if "layer1_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer1_rn""" , """convs.0""" ) if "layer2_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer2_rn""" , """convs.1""" ) if "layer3_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer3_rn""" , """convs.2""" ) if "layer4_rn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""layer4_rn""" , """convs.3""" ) if "refinenet" in name: SCREAMING_SNAKE_CASE__ = int(name[len("""neck.refinenet""" ) : len("""neck.refinenet""" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 SCREAMING_SNAKE_CASE__ = name.replace(f'''refinenet{layer_idx}''' , f'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: SCREAMING_SNAKE_CASE__ = name.replace("""out_conv""" , """projection""" ) if "resConfUnit1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""resConfUnit1""" , """residual_layer1""" ) if "resConfUnit2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""resConfUnit2""" , """residual_layer2""" ) if "conv1" in name: SCREAMING_SNAKE_CASE__ = name.replace("""conv1""" , """convolution1""" ) if "conv2" in name: SCREAMING_SNAKE_CASE__ = name.replace("""conv2""" , """convolution2""" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.0.project.0""" , """neck.reassemble_stage.readout_projects.0.0""" ) if "pretrained.act_postprocess2.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.0.project.0""" , """neck.reassemble_stage.readout_projects.1.0""" ) if "pretrained.act_postprocess3.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess3.0.project.0""" , """neck.reassemble_stage.readout_projects.2.0""" ) if "pretrained.act_postprocess4.0.project.0" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.0.project.0""" , """neck.reassemble_stage.readout_projects.3.0""" ) # resize blocks if "pretrained.act_postprocess1.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.3""" , """neck.reassemble_stage.layers.0.projection""" ) if "pretrained.act_postprocess1.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess1.4""" , """neck.reassemble_stage.layers.0.resize""" ) if "pretrained.act_postprocess2.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.3""" , """neck.reassemble_stage.layers.1.projection""" ) if "pretrained.act_postprocess2.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess2.4""" , """neck.reassemble_stage.layers.1.resize""" ) if "pretrained.act_postprocess3.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess3.3""" , """neck.reassemble_stage.layers.2.projection""" ) if "pretrained.act_postprocess4.3" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.3""" , """neck.reassemble_stage.layers.3.projection""" ) if "pretrained.act_postprocess4.4" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained.act_postprocess4.4""" , """neck.reassemble_stage.layers.3.resize""" ) if "pretrained" in name: SCREAMING_SNAKE_CASE__ = name.replace("""pretrained""" , """dpt""" ) if "bn" in name: SCREAMING_SNAKE_CASE__ = name.replace("""bn""" , """batch_norm""" ) if "head" in name: SCREAMING_SNAKE_CASE__ = name.replace("""head""" , """head.head""" ) if "encoder.norm" in name: SCREAMING_SNAKE_CASE__ = name.replace("""encoder.norm""" , """layernorm""" ) if "auxlayer" in name: SCREAMING_SNAKE_CASE__ = name.replace("""auxlayer""" , """auxiliary_head.head""" ) return name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: str ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ = state_dict.pop(f'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ = in_proj_weight[: config.hidden_size, :] SCREAMING_SNAKE_CASE__ = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: Dict , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Optional[int] ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_dpt_config(UpperCamelCase__ ) # load original state_dict from URL SCREAMING_SNAKE_CASE__ = torch.hub.load_state_dict_from_url(UpperCamelCase__ , map_location="""cpu""" ) # remove certain keys remove_ignore_keys_(UpperCamelCase__ ) # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ = state_dict.pop(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = val # read in qkv matrices read_in_q_k_v(UpperCamelCase__ , UpperCamelCase__ ) # load HuggingFace model SCREAMING_SNAKE_CASE__ = DPTForSemanticSegmentation(UpperCamelCase__ ) if """ade""" in checkpoint_url else DPTForDepthEstimation(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Check outputs on an image SCREAMING_SNAKE_CASE__ = 480 if """ade""" in checkpoint_url else 384 SCREAMING_SNAKE_CASE__ = DPTImageProcessor(size=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(UpperCamelCase__ , return_tensors="""pt""" ) # forward pass SCREAMING_SNAKE_CASE__ = model(**UpperCamelCase__ ).logits if """ade""" in checkpoint_url else model(**UpperCamelCase__ ).predicted_depth # Assert logits SCREAMING_SNAKE_CASE__ = torch.tensor([[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]] ) if "ade" in checkpoint_url: SCREAMING_SNAKE_CASE__ = torch.tensor([[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]] ) assert outputs.shape == torch.Size(UpperCamelCase__ ) assert ( torch.allclose(outputs[0, 0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] , UpperCamelCase__ ) ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if push_to_hub: print("""Pushing model to hub...""" ) model.push_to_hub( repo_path_or_name=Path(UpperCamelCase__ , UpperCamelCase__ ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=UpperCamelCase__ , ) image_processor.push_to_hub( repo_path_or_name=Path(UpperCamelCase__ , UpperCamelCase__ ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=UpperCamelCase__ , ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt', type=str, help='URL of the original DPT checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', ) parser.add_argument( '--model_name', default='dpt-large', type=str, help='Name of the model, in case you\'re pushing to the hub.', ) _lowerCamelCase = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
59
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[Any] , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = original_name.split(""".""" )[0] SCREAMING_SNAKE_CASE__ = key.split(""".""" ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 2] ) SCREAMING_SNAKE_CASE__ = int(key_list[key_list.index(UpperCamelCase__ ) - 1] ) SCREAMING_SNAKE_CASE__ = orig_block_num - offset SCREAMING_SNAKE_CASE__ = key.replace(f'''{orig_block_num}.{layer_num}.{original_name}''' , f'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = OrderedDict() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0, 0 for key, value in state_dict.items(): if key.startswith("""network""" ): SCREAMING_SNAKE_CASE__ = key.replace("""network""" , """poolformer.encoder""" ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith("""bias""" ) and "patch_embed" not in key: patch_emb_offset += 1 SCREAMING_SNAKE_CASE__ = key[: key.find("""proj""" )] SCREAMING_SNAKE_CASE__ = key.replace(UpperCamelCase__ , f'''patch_embeddings.{total_embed_found}.''' ) SCREAMING_SNAKE_CASE__ = key.replace("""proj""" , """projection""" ) if key.endswith("""bias""" ): total_embed_found += 1 if "patch_embeddings" in key: SCREAMING_SNAKE_CASE__ = """poolformer.encoder.""" + key if "mlp.fc1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc1""" , """output.conv1""" ) if "mlp.fc2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """mlp.fc2""" , """output.conv2""" ) if "norm1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm1""" , """before_norm""" ) if "norm2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """norm2""" , """after_norm""" ) if "layer_scale_1" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_1""" , """layer_scale_1""" ) if "layer_scale_2" in key: SCREAMING_SNAKE_CASE__ = replace_key_with_offset(UpperCamelCase__ , UpperCamelCase__ , """layer_scale_2""" , """layer_scale_2""" ) if "head" in key: SCREAMING_SNAKE_CASE__ = key.replace("""head""" , """classifier""" ) SCREAMING_SNAKE_CASE__ = value return new_state_dict def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = """http://images.cocodataset.org/val2017/000000039769.jpg""" SCREAMING_SNAKE_CASE__ = Image.open(requests.get(UpperCamelCase__ , stream=UpperCamelCase__ ).raw ) return image @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = PoolFormerConfig() # set attributes based on model_name SCREAMING_SNAKE_CASE__ = """huggingface/label-files""" SCREAMING_SNAKE_CASE__ = model_name[-3:] SCREAMING_SNAKE_CASE__ = 1_000 SCREAMING_SNAKE_CASE__ = """imagenet-1k-id2label.json""" SCREAMING_SNAKE_CASE__ = (1, 1_000) # set config attributes SCREAMING_SNAKE_CASE__ = json.load(open(hf_hub_download(UpperCamelCase__ , UpperCamelCase__ , repo_type="""dataset""" ) , """r""" ) ) SCREAMING_SNAKE_CASE__ = {int(UpperCamelCase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ = idalabel SCREAMING_SNAKE_CASE__ = {v: k for k, v in idalabel.items()} if size == "s12": SCREAMING_SNAKE_CASE__ = [2, 2, 6, 2] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s24": SCREAMING_SNAKE_CASE__ = [4, 4, 12, 4] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "s36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [64, 128, 320, 512] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9 elif size == "m36": SCREAMING_SNAKE_CASE__ = [6, 6, 18, 6] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 elif size == "m48": SCREAMING_SNAKE_CASE__ = [8, 8, 24, 8] SCREAMING_SNAKE_CASE__ = [96, 192, 384, 768] SCREAMING_SNAKE_CASE__ = 4.0 SCREAMING_SNAKE_CASE__ = 1e-6 SCREAMING_SNAKE_CASE__ = 0.9_5 else: raise ValueError(f'''Size {size} not supported''' ) # load image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) # Prepare image SCREAMING_SNAKE_CASE__ = prepare_img() SCREAMING_SNAKE_CASE__ = image_processor(images=UpperCamelCase__ , return_tensors="""pt""" ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location=torch.device("""cpu""" ) ) # rename keys SCREAMING_SNAKE_CASE__ = rename_keys(UpperCamelCase__ ) # create HuggingFace model and load state dict SCREAMING_SNAKE_CASE__ = PoolFormerForImageClassification(UpperCamelCase__ ) model.load_state_dict(UpperCamelCase__ ) model.eval() # Define image processor SCREAMING_SNAKE_CASE__ = PoolFormerImageProcessor(crop_pct=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = image_processor(images=prepare_img() , return_tensors="""pt""" ).pixel_values # forward pass SCREAMING_SNAKE_CASE__ = model(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = outputs.logits # define expected logit slices for different models if size == "s12": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.3_0_4_5, -0.6_7_5_8, -0.4_8_6_9] ) elif size == "s24": SCREAMING_SNAKE_CASE__ = torch.tensor([0.4_4_0_2, -0.1_3_7_4, -0.8_0_4_5] ) elif size == "s36": SCREAMING_SNAKE_CASE__ = torch.tensor([-0.6_0_8_0, -0.5_1_3_3, -0.5_8_9_8] ) elif size == "m36": SCREAMING_SNAKE_CASE__ = torch.tensor([0.3_9_5_2, 0.2_2_6_3, -1.2_6_6_8] ) elif size == "m48": SCREAMING_SNAKE_CASE__ = torch.tensor([0.1_1_6_7, -0.0_6_5_6, -0.3_4_2_3] ) else: raise ValueError(f'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , UpperCamelCase__ , atol=1e-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCamelCase__ ).mkdir(exist_ok=UpperCamelCase__ ) model.save_pretrained(UpperCamelCase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--model_name', default='poolformer_s12', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) _lowerCamelCase = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
59
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import add_start_docstrings _lowerCamelCase = R'\n [`RagConfig`] stores the configuration of a *RagModel*. Configuration objects inherit from [`PretrainedConfig`] and\n can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information.\n\n Args:\n title_sep (`str`, *optional*, defaults to `" / "`):\n Separator inserted between the title and the text of the retrieved document when calling [`RagRetriever`].\n doc_sep (`str`, *optional*, defaults to `" // "`):\n Separator inserted between the text of the retrieved document and the original input when calling\n [`RagRetriever`].\n n_docs (`int`, *optional*, defaults to 5):\n Number of documents to retrieve.\n max_combined_length (`int`, *optional*, defaults to 300):\n Max length of contextualized input returned by [`~RagRetriever.__call__`].\n retrieval_vector_size (`int`, *optional*, defaults to 768):\n Dimensionality of the document embeddings indexed by [`RagRetriever`].\n retrieval_batch_size (`int`, *optional*, defaults to 8):\n Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated\n [`RagRetriever`].\n dataset (`str`, *optional*, defaults to `"wiki_dpr"`):\n A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids\n using `datasets.list_datasets()`).\n dataset_split (`str`, *optional*, defaults to `"train"`)\n Which split of the `dataset` to load.\n index_name (`str`, *optional*, defaults to `"compressed"`)\n The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and\n `"compressed"`.\n index_path (`str`, *optional*)\n The path to the serialized faiss index on disk.\n passages_path (`str`, *optional*):\n A path to text passages compatible with the faiss index. Required if using\n [`~models.rag.retrieval_rag.LegacyIndex`]\n use_dummy_dataset (`bool`, *optional*, defaults to `False`)\n Whether to load a "dummy" variant of the dataset specified by `dataset`.\n label_smoothing (`float`, *optional*, defaults to 0.0):\n Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing\n in the loss calculation. If set to 0, no label smoothing is performed.\n do_marginalize (`bool`, *optional*, defaults to `False`):\n If `True`, the logits are marginalized over all documents by making use of\n `torch.nn.functional.log_softmax`.\n reduce_loss (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.\n do_deduplication (`bool`, *optional*, defaults to `True`):\n Whether or not to deduplicate the generations from different context documents for a given input. Has to be\n set to `False` if used while training with distributed backend.\n exclude_bos_score (`bool`, *optional*, defaults to `False`):\n Whether or not to disregard the BOS token when computing the loss.\n output_retrieved(`bool`, *optional*, defaults to `False`):\n If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and\n `context_attention_mask` are returned. See returned tensors for more detail.\n use_cache (`bool`, *optional*, defaults to `True`):\n Whether or not the model should return the last key/values attentions (not used by all models).\n forced_eos_token_id (`int`, *optional*):\n The id of the token to force as the last generated token when `max_length` is reached. Usually set to\n `eos_token_id`.\n' @add_start_docstrings(UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "rag" lowerCamelCase_ = True def __init__( self :Tuple , __A :Optional[int]=None , __A :Optional[Any]=True , __A :List[str]=None , __A :List[Any]=None , __A :List[Any]=None , __A :Tuple=None , __A :List[Any]=None , __A :Optional[int]=" / " , __A :Optional[Any]=" // " , __A :Tuple=5 , __A :int=300 , __A :Dict=768 , __A :str=8 , __A :int="wiki_dpr" , __A :Optional[Any]="train" , __A :Any="compressed" , __A :str=None , __A :str=None , __A :List[Any]=False , __A :Tuple=False , __A :int=0.0 , __A :Any=True , __A :Any=False , __A :int=False , __A :int=False , __A :Union[str, Any]=True , __A :str=None , **__A :Dict , ) -> Dict: """simple docstring""" super().__init__( bos_token_id=__A , pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , forced_eos_token_id=__A , is_encoder_decoder=__A , prefix=__A , vocab_size=__A , **__A , ) assert ( "question_encoder" in kwargs and "generator" in kwargs ), "Config has to be initialized with question_encoder and generator config" SCREAMING_SNAKE_CASE__ = kwargs.pop("""question_encoder""" ) SCREAMING_SNAKE_CASE__ = question_encoder_config.pop("""model_type""" ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""generator""" ) SCREAMING_SNAKE_CASE__ = decoder_config.pop("""model_type""" ) from ..auto.configuration_auto import AutoConfig SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = AutoConfig.for_model(__A , **__A ) SCREAMING_SNAKE_CASE__ = reduce_loss SCREAMING_SNAKE_CASE__ = label_smoothing SCREAMING_SNAKE_CASE__ = exclude_bos_score SCREAMING_SNAKE_CASE__ = do_marginalize SCREAMING_SNAKE_CASE__ = title_sep SCREAMING_SNAKE_CASE__ = doc_sep SCREAMING_SNAKE_CASE__ = n_docs SCREAMING_SNAKE_CASE__ = max_combined_length SCREAMING_SNAKE_CASE__ = dataset SCREAMING_SNAKE_CASE__ = dataset_split SCREAMING_SNAKE_CASE__ = index_name SCREAMING_SNAKE_CASE__ = retrieval_vector_size SCREAMING_SNAKE_CASE__ = retrieval_batch_size SCREAMING_SNAKE_CASE__ = passages_path SCREAMING_SNAKE_CASE__ = index_path SCREAMING_SNAKE_CASE__ = use_dummy_dataset SCREAMING_SNAKE_CASE__ = output_retrieved SCREAMING_SNAKE_CASE__ = do_deduplication SCREAMING_SNAKE_CASE__ = use_cache if self.forced_eos_token_id is None: SCREAMING_SNAKE_CASE__ = getattr(self.generator , """forced_eos_token_id""" , __A ) @classmethod def _snake_case ( cls :Union[str, Any] , __A :PretrainedConfig , __A :PretrainedConfig , **__A :List[Any] ) -> PretrainedConfig: """simple docstring""" return cls(question_encoder=question_encoder_config.to_dict() , generator=generator_config.to_dict() , **__A ) def _snake_case ( self :Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.question_encoder.to_dict() SCREAMING_SNAKE_CASE__ = self.generator.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'google/pix2struct-textcaps-base': ( 'https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json' ), } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_text_model" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :Union[str, Any] , __A :Any=5_0244 , __A :Optional[Any]=768 , __A :Tuple=64 , __A :List[str]=2048 , __A :int=12 , __A :str=12 , __A :Any=32 , __A :Tuple=128 , __A :int=0.1 , __A :str=1E-6 , __A :Optional[Any]=1.0 , __A :Union[str, Any]="gelu_new" , __A :Any=0 , __A :List[str]=False , __A :Optional[Any]=0 , __A :int=1 , __A :Optional[int]=False , __A :Optional[Any]=True , **__A :List[Any] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = eos_token_id SCREAMING_SNAKE_CASE__ = decoder_start_token_id # for backwards compatibility SCREAMING_SNAKE_CASE__ = dense_act_fn super().__init__( pad_token_id=__A , eos_token_id=__A , decoder_start_token_id=__A , tie_word_embeddings=__A , is_decoder=__A , **__A , ) @classmethod def _snake_case ( cls :Optional[int] , __A :Union[str, os.PathLike] , **__A :Optional[int] ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""text_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct_vision_model" def __init__( self :Optional[int] , __A :int=768 , __A :Optional[Any]=768 , __A :Union[str, Any]=2048 , __A :int=64 , __A :Union[str, Any]=12 , __A :str=12 , __A :Any="gelu_new" , __A :List[Any]=1E-6 , __A :Dict=0.0 , __A :int=0.0 , __A :int=1E-10 , __A :Dict=1.0 , __A :int=4096 , __A :int=32 , __A :int=128 , **__A :Tuple , ) -> str: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = hidden_size SCREAMING_SNAKE_CASE__ = patch_embed_hidden_size SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = num_hidden_layers SCREAMING_SNAKE_CASE__ = num_attention_heads SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = dense_act_fn SCREAMING_SNAKE_CASE__ = seq_len SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = d_kv @classmethod def _snake_case ( cls :str , __A :Union[str, os.PathLike] , **__A :str ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__A ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("""model_type""" ) == "pix2struct": SCREAMING_SNAKE_CASE__ = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "pix2struct" lowerCamelCase_ = True def __init__( self :str , __A :Optional[Any]=None , __A :List[str]=None , __A :Optional[Any]=1.0 , __A :Optional[Any]=0.0_2 , __A :Any=False , __A :Tuple=False , __A :Any=True , **__A :Dict , ) -> Union[str, Any]: """simple docstring""" super().__init__(tie_word_embeddings=__A , is_encoder_decoder=__A , **__A ) if text_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" ) if vision_config is None: SCREAMING_SNAKE_CASE__ = {} logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" ) SCREAMING_SNAKE_CASE__ = PixaStructTextConfig(**__A ) SCREAMING_SNAKE_CASE__ = PixaStructVisionConfig(**__A ) SCREAMING_SNAKE_CASE__ = self.text_config.decoder_start_token_id SCREAMING_SNAKE_CASE__ = self.text_config.pad_token_id SCREAMING_SNAKE_CASE__ = self.text_config.eos_token_id SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = self.initializer_range SCREAMING_SNAKE_CASE__ = is_vqa @classmethod def _snake_case ( cls :Union[str, Any] , __A :PixaStructTextConfig , __A :PixaStructVisionConfig , **__A :Optional[int] ) -> Optional[Any]: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _snake_case ( self :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output
59
1
from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) # We need to create solution object to save path. SCREAMING_SNAKE_CASE__ = [[0 for _ in range(UpperCamelCase__ )] for _ in range(UpperCamelCase__ )] SCREAMING_SNAKE_CASE__ = run_maze(UpperCamelCase__ , 0 , 0 , UpperCamelCase__ ) if solved: print("""\n""".join(str(UpperCamelCase__ ) for row in solutions ) ) else: print("""No solution exists!""" ) return solved def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list[list[int]] , UpperCamelCase__: int , UpperCamelCase__: int , UpperCamelCase__: list[list[int]] ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) # Final check point. if i == j == (size - 1): SCREAMING_SNAKE_CASE__ = 1 return True SCREAMING_SNAKE_CASE__ = (not i < 0) and (not j < 0) # Check lower bounds SCREAMING_SNAKE_CASE__ = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. SCREAMING_SNAKE_CASE__ = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited SCREAMING_SNAKE_CASE__ = 1 # check for directions if ( run_maze(UpperCamelCase__ , i + 1 , UpperCamelCase__ , UpperCamelCase__ ) or run_maze(UpperCamelCase__ , UpperCamelCase__ , j + 1 , UpperCamelCase__ ) or run_maze(UpperCamelCase__ , i - 1 , UpperCamelCase__ , UpperCamelCase__ ) or run_maze(UpperCamelCase__ , UpperCamelCase__ , j - 1 , UpperCamelCase__ ) ): return True SCREAMING_SNAKE_CASE__ = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
59
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = inspect.getfile(accelerate.test_utils ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_script.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_distributed_data_loop.py"""] ) SCREAMING_SNAKE_CASE__ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["""scripts""", """test_ops.py"""] ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Tuple ) -> Optional[Any]: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices.''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__A , env=os.environ.copy() ) @require_multi_gpu def _snake_case ( self :Optional[int] ) -> str: """simple docstring""" print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) SCREAMING_SNAKE_CASE__ = ["""torchrun""", f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="""0,1""" ): execute_subprocess_async(__A , env=os.environ.copy() ) if __name__ == "__main__": _lowerCamelCase = Accelerator() _lowerCamelCase = (accelerator.state.process_index + 2, 10) _lowerCamelCase = torch.randint(0, 10, shape).to(accelerator.device) _lowerCamelCase = '' _lowerCamelCase = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." _lowerCamelCase = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." _lowerCamelCase = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
59
1
import os import warnings from typing import List, Optional from ...tokenization_utils_base import BatchEncoding from ...utils import logging from .configuration_rag import RagConfig _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ : def __init__( self :Any , __A :int , __A :str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = question_encoder SCREAMING_SNAKE_CASE__ = generator SCREAMING_SNAKE_CASE__ = self.question_encoder def _snake_case ( self :Optional[Any] , __A :Optional[Any] ) -> Optional[int]: """simple docstring""" if os.path.isfile(__A ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(__A , exist_ok=__A ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """question_encoder_tokenizer""" ) SCREAMING_SNAKE_CASE__ = os.path.join(__A , """generator_tokenizer""" ) self.question_encoder.save_pretrained(__A ) self.generator.save_pretrained(__A ) @classmethod def _snake_case ( cls :List[str] , __A :Optional[int] , **__A :str ) -> Optional[int]: """simple docstring""" from ..auto.tokenization_auto import AutoTokenizer SCREAMING_SNAKE_CASE__ = kwargs.pop("""config""" , __A ) if config is None: SCREAMING_SNAKE_CASE__ = RagConfig.from_pretrained(__A ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( __A , config=config.question_encoder , subfolder="""question_encoder_tokenizer""" ) SCREAMING_SNAKE_CASE__ = AutoTokenizer.from_pretrained( __A , config=config.generator , subfolder="""generator_tokenizer""" ) return cls(question_encoder=__A , generator=__A ) def __call__( self :Optional[int] , *__A :List[Any] , **__A :str ) -> Optional[Any]: """simple docstring""" return self.current_tokenizer(*__A , **__A ) def _snake_case ( self :Optional[int] , *__A :Optional[Any] , **__A :List[Any] ) -> Optional[int]: """simple docstring""" return self.generator.batch_decode(*__A , **__A ) def _snake_case ( self :Union[str, Any] , *__A :int , **__A :List[Any] ) -> List[Any]: """simple docstring""" return self.generator.decode(*__A , **__A ) def _snake_case ( self :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.question_encoder def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.generator def _snake_case ( self :str , __A :List[str] , __A :Optional[List[str]] = None , __A :Optional[int] = None , __A :Optional[int] = None , __A :str = "longest" , __A :str = None , __A :bool = True , **__A :int , ) -> BatchEncoding: """simple docstring""" warnings.warn( """`prepare_seq2seq_batch` is deprecated and will be removed in version 5 of 🤗 Transformers. Use the """ """regular `__call__` method to prepare your inputs and the tokenizer under the `with_target_tokenizer` """ """context manager to prepare your targets. See the documentation of your specific tokenizer for more """ """details""" , __A , ) if max_length is None: SCREAMING_SNAKE_CASE__ = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE__ = self( __A , add_special_tokens=__A , return_tensors=__A , max_length=__A , padding=__A , truncation=__A , **__A , ) if tgt_texts is None: return model_inputs # Process tgt_texts if max_target_length is None: SCREAMING_SNAKE_CASE__ = self.current_tokenizer.model_max_length SCREAMING_SNAKE_CASE__ = self( text_target=__A , add_special_tokens=__A , return_tensors=__A , padding=__A , max_length=__A , truncation=__A , **__A , ) SCREAMING_SNAKE_CASE__ = labels["""input_ids"""] return model_inputs
59
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _lowerCamelCase = { 'configuration_layoutlmv3': [ 'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LayoutLMv3Config', 'LayoutLMv3OnnxConfig', ], 'processing_layoutlmv3': ['LayoutLMv3Processor'], 'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3TokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'LayoutLMv3ForQuestionAnswering', 'LayoutLMv3ForSequenceClassification', 'LayoutLMv3ForTokenClassification', 'LayoutLMv3Model', 'LayoutLMv3PreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLayoutLMv3ForQuestionAnswering', 'TFLayoutLMv3ForSequenceClassification', 'TFLayoutLMv3ForTokenClassification', 'TFLayoutLMv3Model', 'TFLayoutLMv3PreTrainedModel', ] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['LayoutLMv3FeatureExtractor'] _lowerCamelCase = ['LayoutLMv3ImageProcessor'] if TYPE_CHECKING: from .configuration_layoutlmva import ( LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig, LayoutLMvaOnnxConfig, ) from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_layoutlmva import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, TFLayoutLMvaPreTrainedModel, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor from .image_processing_layoutlmva import LayoutLMvaImageProcessor else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _lowerCamelCase = { 'configuration_blenderbot_small': [ 'BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotSmallConfig', 'BlenderbotSmallOnnxConfig', ], 'tokenization_blenderbot_small': ['BlenderbotSmallTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = ['BlenderbotSmallTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotSmallForCausalLM', 'BlenderbotSmallForConditionalGeneration', 'BlenderbotSmallModel', 'BlenderbotSmallPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'TFBlenderbotSmallForConditionalGeneration', 'TFBlenderbotSmallModel', 'TFBlenderbotSmallPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxBlenderbotSmallForConditionalGeneration', 'FlaxBlenderbotSmallModel', 'FlaxBlenderbotSmallPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
import inspect import unittest class UpperCamelCase_ ( unittest.TestCase ): def _snake_case ( self :str ) -> Union[str, Any]: """simple docstring""" try: import diffusers # noqa: F401 except ImportError: assert False def _snake_case ( self :Any ) -> Any: """simple docstring""" import diffusers from diffusers.dependency_versions_table import deps SCREAMING_SNAKE_CASE__ = inspect.getmembers(__A , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": SCREAMING_SNAKE_CASE__ = """k-diffusion""" elif backend == "invisible_watermark": SCREAMING_SNAKE_CASE__ = """invisible-watermark""" assert backend in deps, f'''{backend} is not in the deps table!'''
59
1
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( nn.Module ): def __init__( self :int , __A :str=3 , __A :Optional[Any]=3 , __A :str=("DownEncoderBlock2D",) , __A :Tuple=(64,) , __A :List[Any]=2 , __A :List[str]=32 , __A :str="silu" , __A :Optional[int]=True , ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = torch.nn.Convad( __A , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) # down SCREAMING_SNAKE_CASE__ = block_out_channels[0] for i, down_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_down_block( __A , num_layers=self.layers_per_block , in_channels=__A , out_channels=__A , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , ) self.down_blocks.append(__A ) # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # out SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = 2 * out_channels if double_z else out_channels SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[-1] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :str , __A :int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = x SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) if self.training and self.gradient_checkpointing: def create_custom_forward(__A :str ): def custom_forward(*__A :str ): return module(*__A ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , use_reentrant=__A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , use_reentrant=__A ) else: for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __A ) else: # down for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = down_block(__A ) # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A ) # post-process SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Dict , __A :Optional[Any]=3 , __A :Tuple=3 , __A :Optional[int]=("UpDecoderBlock2D",) , __A :int=(64,) , __A :int=2 , __A :Dict=32 , __A :Dict="silu" , __A :str="group" , ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = nn.Convad( __A , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) SCREAMING_SNAKE_CASE__ = in_channels if norm_type == """spatial""" else None # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # up SCREAMING_SNAKE_CASE__ = list(reversed(__A ) ) SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_up_block( __A , num_layers=self.layers_per_block + 1 , in_channels=__A , out_channels=__A , prev_output_channel=__A , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , resnet_time_scale_shift=__A , ) self.up_blocks.append(__A ) SCREAMING_SNAKE_CASE__ = output_channel # out if norm_type == "spatial": SCREAMING_SNAKE_CASE__ = SpatialNorm(block_out_channels[0] , __A ) else: SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[0] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :List[str] , __A :Any , __A :Dict=None ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ = z SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) SCREAMING_SNAKE_CASE__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__A :str ): def custom_forward(*__A :Dict ): return module(*__A ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A , use_reentrant=__A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , __A , use_reentrant=__A ) else: # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A , __A ) else: # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = up_block(__A , __A ) # post-process if latent_embeds is None: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) else: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A , __A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :List[str] , __A :Optional[Any] , __A :Tuple , __A :Optional[int] , __A :int=None , __A :Optional[Any]="random" , __A :int=False , __A :Any=True ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = vq_embed_dim SCREAMING_SNAKE_CASE__ = beta SCREAMING_SNAKE_CASE__ = legacy SCREAMING_SNAKE_CASE__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) SCREAMING_SNAKE_CASE__ = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) SCREAMING_SNAKE_CASE__ = self.used.shape[0] SCREAMING_SNAKE_CASE__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": SCREAMING_SNAKE_CASE__ = self.re_embed SCREAMING_SNAKE_CASE__ = self.re_embed + 1 print( f'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' f'''Using {self.unknown_index} for unknown indices.''' ) else: SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = sane_index_shape def _snake_case ( self :str , __A :List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) SCREAMING_SNAKE_CASE__ = (inds[:, :, None] == used[None, None, ...]).long() SCREAMING_SNAKE_CASE__ = match.argmax(-1 ) SCREAMING_SNAKE_CASE__ = match.sum(2 ) < 1 if self.unknown_index == "random": SCREAMING_SNAKE_CASE__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: SCREAMING_SNAKE_CASE__ = self.unknown_index return new.reshape(__A ) def _snake_case ( self :Dict , __A :str ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) if self.re_embed > self.used.shape[0]: # extra token SCREAMING_SNAKE_CASE__ = 0 # simply set to zero SCREAMING_SNAKE_CASE__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __A ) return back.reshape(__A ) def _snake_case ( self :Tuple , __A :Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = z.permute(0 , 2 , 3 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z SCREAMING_SNAKE_CASE__ = torch.argmin(torch.cdist(__A , self.embedding.weight ) , dim=1 ) SCREAMING_SNAKE_CASE__ = self.embedding(__A ).view(z.shape ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # compute loss for embedding if not self.legacy: SCREAMING_SNAKE_CASE__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: SCREAMING_SNAKE_CASE__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients SCREAMING_SNAKE_CASE__ = z + (z_q - z).detach() # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.remap_to_used(__A ) SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _snake_case ( self :List[Any] , __A :Tuple , __A :List[str] ) -> List[Any]: """simple docstring""" if self.remap is not None: SCREAMING_SNAKE_CASE__ = indices.reshape(shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.unmap_to_all(__A ) SCREAMING_SNAKE_CASE__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors SCREAMING_SNAKE_CASE__ = self.embedding(__A ) if shape is not None: SCREAMING_SNAKE_CASE__ = z_q.view(__A ) # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :List[Any] , __A :int=False ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = torch.chunk(__A , 2 , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) SCREAMING_SNAKE_CASE__ = deterministic SCREAMING_SNAKE_CASE__ = torch.exp(0.5 * self.logvar ) SCREAMING_SNAKE_CASE__ = torch.exp(self.logvar ) if self.deterministic: SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _snake_case ( self :Any , __A :Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" SCREAMING_SNAKE_CASE__ = randn_tensor( self.mean.shape , generator=__A , device=self.parameters.device , dtype=self.parameters.dtype ) SCREAMING_SNAKE_CASE__ = self.mean + self.std * sample return x def _snake_case ( self :Union[str, Any] , __A :int=None ) -> int: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _snake_case ( self :str , __A :Tuple , __A :int=[1, 2, 3] ) -> int: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) SCREAMING_SNAKE_CASE__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__A ) def _snake_case ( self :Tuple ) -> Optional[int]: """simple docstring""" return self.mean
59
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput _lowerCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): warnings.warn( """The preprocess method is deprecated and will be removed in a future version. Please""" """ use VaeImageProcessor.preprocess instead""" , UpperCamelCase__ , ) if isinstance(UpperCamelCase__ , torch.Tensor ): return image elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [image] if isinstance(image[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 SCREAMING_SNAKE_CASE__ = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION["""lanczos"""] ) )[None, :] for i in image] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = np.array(UpperCamelCase__ ).astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = image.transpose(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ = 2.0 * image - 1.0 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(image[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return image def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Union[List, PIL.Image.Image, torch.Tensor] ): if isinstance(UpperCamelCase__ , torch.Tensor ): return mask elif isinstance(UpperCamelCase__ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ = [mask] if isinstance(mask[0] , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = mask[0].size SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 SCREAMING_SNAKE_CASE__ = [np.array(m.convert("""L""" ).resize((w, h) , resample=PIL_INTERPOLATION["""nearest"""] ) )[None, :] for m in mask] SCREAMING_SNAKE_CASE__ = np.concatenate(UpperCamelCase__ , axis=0 ) SCREAMING_SNAKE_CASE__ = mask.astype(np.floataa ) / 2_5_5.0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 1 SCREAMING_SNAKE_CASE__ = torch.from_numpy(UpperCamelCase__ ) elif isinstance(mask[0] , torch.Tensor ): SCREAMING_SNAKE_CASE__ = torch.cat(UpperCamelCase__ , dim=0 ) return mask class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Any , __A :List[Any] , __A :Optional[Any] ) -> Union[str, Any]: """simple docstring""" super().__init__() self.register_modules(unet=__A , scheduler=__A ) @torch.no_grad() def __call__( self :str , __A :Union[torch.Tensor, PIL.Image.Image] , __A :Union[torch.Tensor, PIL.Image.Image] , __A :int = 250 , __A :float = 0.0 , __A :int = 10 , __A :int = 10 , __A :Optional[Union[torch.Generator, List[torch.Generator]]] = None , __A :Optional[str] = "pil" , __A :bool = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE__ = image SCREAMING_SNAKE_CASE__ = _preprocess_image(__A ) SCREAMING_SNAKE_CASE__ = original_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = _preprocess_mask(__A ) SCREAMING_SNAKE_CASE__ = mask_image.to(device=self.device , dtype=self.unet.dtype ) SCREAMING_SNAKE_CASE__ = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(__A , __A ) and len(__A ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(__A )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) SCREAMING_SNAKE_CASE__ = original_image.shape SCREAMING_SNAKE_CASE__ = randn_tensor(__A , generator=__A , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(__A , __A , __A , self.device ) SCREAMING_SNAKE_CASE__ = eta SCREAMING_SNAKE_CASE__ = self.scheduler.timesteps[0] + 1 SCREAMING_SNAKE_CASE__ = generator[0] if isinstance(__A , __A ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual SCREAMING_SNAKE_CASE__ = self.unet(__A , __A ).sample # compute previous image: x_t -> x_t-1 SCREAMING_SNAKE_CASE__ = self.scheduler.step(__A , __A , __A , __A , __A , __A ).prev_sample else: # compute the reverse: x_t-1 -> x_t SCREAMING_SNAKE_CASE__ = self.scheduler.undo_step(__A , __A , __A ) SCREAMING_SNAKE_CASE__ = t SCREAMING_SNAKE_CASE__ = (image / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE__ = self.numpy_to_pil(__A ) if not return_dict: return (image,) return ImagePipelineOutput(images=__A )
59
1
import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RoCBertTokenizer lowerCamelCase_ = None lowerCamelCase_ = False lowerCamelCase_ = True lowerCamelCase_ = filter_non_english def _snake_case ( self :List[Any] ) -> List[Any]: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """你""", """好""", """是""", """谁""", """a""", """b""", """c""", """d"""] SCREAMING_SNAKE_CASE__ = {} SCREAMING_SNAKE_CASE__ = {} for i, value in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_shape_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""word_pronunciation_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) with open(self.word_shape_file , """w""" , encoding="""utf-8""" ) as word_shape_writer: json.dump(__A , __A , ensure_ascii=__A ) with open(self.word_pronunciation_file , """w""" , encoding="""utf-8""" ) as word_pronunciation_writer: json.dump(__A , __A , ensure_ascii=__A ) def _snake_case ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.tokenize("""你好[SEP]你是谁""" ) self.assertListEqual(__A , ["""你""", """好""", """[SEP]""", """你""", """是""", """谁"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(__A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(__A ) , [5, 6, 2, 5, 7, 8] ) def _snake_case ( self :List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] ) self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] ) def _snake_case ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , strip_accents=__A ) self.assertListEqual( tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def _snake_case ( self :List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = RoCBertBasicTokenizer(do_lower_case=__A , never_split=["""[UNK]"""] ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] ) def _snake_case ( self :Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""] SCREAMING_SNAKE_CASE__ = {} for i, token in enumerate(__A ): SCREAMING_SNAKE_CASE__ = i SCREAMING_SNAKE_CASE__ = RoCBertWordpieceTokenizer(vocab=__A , unk_token="""[UNK]""" ) self.assertListEqual(tokenizer.tokenize("""""" ) , [] ) self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] ) self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] ) def _snake_case ( self :Any ) -> str: """simple docstring""" self.assertTrue(_is_whitespace(""" """ ) ) self.assertTrue(_is_whitespace("""\t""" ) ) self.assertTrue(_is_whitespace("""\r""" ) ) self.assertTrue(_is_whitespace("""\n""" ) ) self.assertTrue(_is_whitespace("""\u00A0""" ) ) self.assertFalse(_is_whitespace("""A""" ) ) self.assertFalse(_is_whitespace("""-""" ) ) def _snake_case ( self :int ) -> str: """simple docstring""" self.assertTrue(_is_control("""\u0005""" ) ) self.assertFalse(_is_control("""A""" ) ) self.assertFalse(_is_control(""" """ ) ) self.assertFalse(_is_control("""\t""" ) ) self.assertFalse(_is_control("""\r""" ) ) def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" self.assertTrue(_is_punctuation("""-""" ) ) self.assertTrue(_is_punctuation("""$""" ) ) self.assertTrue(_is_punctuation("""`""" ) ) self.assertTrue(_is_punctuation(""".""" ) ) self.assertFalse(_is_punctuation("""A""" ) ) self.assertFalse(_is_punctuation(""" """ ) ) def _snake_case ( self :str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) if self.test_rust_tokenizer: SCREAMING_SNAKE_CASE__ = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(__A ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] ) def _snake_case ( self :int ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus( __A , return_attention_mask=__A , return_token_type_ids=__A , return_offsets_mapping=__A , add_special_tokens=__A , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.do_lower_case if hasattr(__A , """do_lower_case""" ) else False SCREAMING_SNAKE_CASE__ = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """A"""), ((1, 2), ""","""), ((3, 5), """na"""), ((5, 6), """##ï"""), ((6, 8), """##ve"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """Allen"""), ((21, 23), """##NL"""), ((23, 24), """##P"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), """a"""), ((1, 2), ""","""), ((3, 8), """naive"""), ((9, 15), tokenizer_r.mask_token), ((16, 21), """allen"""), ((21, 23), """##nl"""), ((23, 24), """##p"""), ((25, 33), """sentence"""), ((33, 34), """."""), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) ) self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] ) def _snake_case ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = ["""的""", """人""", """有"""] SCREAMING_SNAKE_CASE__ = """""".join(__A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = False SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(__A ) # it is expected that only the first Chinese character is not preceded by "##". SCREAMING_SNAKE_CASE__ = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(__A ) ] self.assertListEqual(__A , __A ) self.assertListEqual(__A , __A ) @slow def _snake_case ( self :Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你好""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""你是谁""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def _snake_case ( self :List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizers(do_lower_case=__A ) for tokenizer in tokenizers: with self.subTest(f'''{tokenizer.__class__.__name__}''' ): SCREAMING_SNAKE_CASE__ = """你好,你是谁""" SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_shape_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_pronunciation_ids(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.prepare_for_model( __A , __A , __A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode_plus(__A , add_special_tokens=__A ) self.assertEqual(__A , __A )
59
import json import os import unittest from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = OpenAIGPTTokenizer lowerCamelCase_ = OpenAIGPTTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = False def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""] SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(__A ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :Union[str, Any] , __A :str ) -> List[Any]: """simple docstring""" return "lower newer", "lower newer" def _snake_case ( self :Optional[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = OpenAIGPTTokenizer(self.vocab_file , self.merges_file ) SCREAMING_SNAKE_CASE__ = """lower""" SCREAMING_SNAKE_CASE__ = ["""low""", """er</w>"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + ["""<unk>"""] SCREAMING_SNAKE_CASE__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] , __A :Optional[Any]=15 ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) # Simple input SCREAMING_SNAKE_CASE__ = """This is a simple input""" SCREAMING_SNAKE_CASE__ = ["""This is a simple input 1""", """This is a simple input 2"""] SCREAMING_SNAKE_CASE__ = ("""This is a simple input""", """This is a pair""") SCREAMING_SNAKE_CASE__ = [ ("""This is a simple input 1""", """This is a simple input 2"""), ("""This is a simple pair 1""", """This is a simple pair 2"""), ] # Simple input tests self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Simple input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) # Pair input self.assertRaises(__A , tokenizer_r.encode , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises(__A , tokenizer_r.encode_plus , __A , max_length=__A , padding="""max_length""" ) # Pair input self.assertRaises( __A , tokenizer_r.batch_encode_plus , __A , max_length=__A , padding="""max_length""" , ) def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" pass @require_ftfy @require_spacy @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ ): pass
59
1
import itertools import json import os import unittest from transformers import AddedToken, RobertaTokenizer, RobertaTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCamelCase_ ( UpperCamelCase__ , unittest.TestCase ): lowerCamelCase_ = RobertaTokenizer lowerCamelCase_ = RobertaTokenizerFast lowerCamelCase_ = True lowerCamelCase_ = {"cls_token": "<s>"} def _snake_case ( self :List[str] ) -> Dict: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt SCREAMING_SNAKE_CASE__ = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """\u0120""", """\u0120l""", """\u0120n""", """\u0120lo""", """\u0120low""", """er""", """\u0120lowest""", """\u0120newer""", """\u0120wider""", """<unk>""", ] SCREAMING_SNAKE_CASE__ = dict(zip(__A , range(len(__A ) ) ) ) SCREAMING_SNAKE_CASE__ = ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""] SCREAMING_SNAKE_CASE__ = {"""unk_token""": """<unk>"""} SCREAMING_SNAKE_CASE__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ = 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(__A ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(__A ) ) def _snake_case ( self :List[str] , **__A :List[Any] ) -> List[str]: """simple docstring""" kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :Union[str, Any] , **__A :int ) -> List[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return RobertaTokenizerFast.from_pretrained(self.tmpdirname , **__A ) def _snake_case ( self :str , __A :Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = """lower newer""" return input_text, output_text def _snake_case ( self :List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE__ = """lower newer""" SCREAMING_SNAKE_CASE__ = ["""l""", """o""", """w""", """er""", """\u0120""", """n""", """e""", """w""", """er"""] SCREAMING_SNAKE_CASE__ = tokenizer.tokenize(__A ) # , add_prefix_space=True) self.assertListEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokens + [tokenizer.unk_token] SCREAMING_SNAKE_CASE__ = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , __A ) def _snake_case ( self :Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() self.assertListEqual(tokenizer.encode("""Hello world!""" , add_special_tokens=__A ) , [0, 3_1414, 232, 328, 2] ) self.assertListEqual( tokenizer.encode("""Hello world! cécé herlolip 418""" , add_special_tokens=__A ) , [0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2] , ) @slow def _snake_case ( self :List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained("""roberta-base""" ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""sequence builders""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode("""multi-sequence build""" , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode( """sequence builders""" , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode( """sequence builders""" , """multi-sequence build""" , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.build_inputs_with_special_tokens(__A , __A ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode def _snake_case ( self :Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.get_tokenizer() SCREAMING_SNAKE_CASE__ = """Encode this sequence.""" SCREAMING_SNAKE_CASE__ = tokenizer.byte_encoder[""" """.encode("""utf-8""" )[0]] # Testing encoder arguments SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertNotEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A , add_prefix_space=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[0] )[0] self.assertEqual(__A , __A ) tokenizer.add_special_tokens({"""bos_token""": """<s>"""} ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A , add_special_tokens=__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[1] )[0] self.assertNotEqual(__A , __A ) # Testing spaces after special tokens SCREAMING_SNAKE_CASE__ = """<mask>""" tokenizer.add_special_tokens( {"""mask_token""": AddedToken(__A , lstrip=__A , rstrip=__A )} ) # mask token has a left space SCREAMING_SNAKE_CASE__ = tokenizer.convert_tokens_to_ids(__A ) SCREAMING_SNAKE_CASE__ = """Encode <mask> sequence""" SCREAMING_SNAKE_CASE__ = """Encode <mask>sequence""" SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A ) SCREAMING_SNAKE_CASE__ = encoded.index(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertEqual(__A , __A ) SCREAMING_SNAKE_CASE__ = tokenizer.encode(__A ) SCREAMING_SNAKE_CASE__ = encoded.index(__A ) SCREAMING_SNAKE_CASE__ = tokenizer.convert_ids_to_tokens(encoded[mask_loc + 1] )[0] self.assertNotEqual(__A , __A ) def _snake_case ( self :List[Any] ) -> List[str]: """simple docstring""" pass def _snake_case ( self :Any ) -> Optional[Any]: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = self.tokenizer_class.from_pretrained(__A , **__A ) SCREAMING_SNAKE_CASE__ = """A, <mask> AllenNLP sentence.""" SCREAMING_SNAKE_CASE__ = tokenizer_r.encode_plus(__A , add_special_tokens=__A , return_token_type_ids=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_p.encode_plus(__A , add_special_tokens=__A , return_token_type_ids=__A ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r["""token_type_ids"""] ) , sum(tokens_p["""token_type_ids"""] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r["""attention_mask"""] ) / len(tokens_r["""attention_mask"""] ) , sum(tokens_p["""attention_mask"""] ) / len(tokens_p["""attention_mask"""] ) , ) SCREAMING_SNAKE_CASE__ = tokenizer_r.convert_ids_to_tokens(tokens_r["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = tokenizer_p.convert_ids_to_tokens(tokens_p["""input_ids"""] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual(tokens_r["""input_ids"""] , [0, 250, 6, 5_0264, 3823, 487, 2_1992, 3645, 4, 2] ) self.assertSequenceEqual( __A , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) self.assertSequenceEqual( __A , ["""<s>""", """A""", """,""", """<mask>""", """ĠAllen""", """N""", """LP""", """Ġsentence""", """.""", """</s>"""] ) def _snake_case ( self :List[str] ) -> List[Any]: """simple docstring""" for trim_offsets, add_prefix_space in itertools.product([True, False] , repeat=2 ): SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( self.tmpdirname , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_r.backend_tokenizer.pre_tokenizer.__getstate__() ) SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_r.backend_tokenizer.post_processor.__getstate__() ) self.assertEqual(pre_tokenizer_state["""add_prefix_space"""] , __A ) self.assertEqual(post_processor_state["""add_prefix_space"""] , __A ) self.assertEqual(post_processor_state["""trim_offsets"""] , __A ) def _snake_case ( self :Optional[int] ) -> Any: """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ = """hello""" # `hello` is a token in the vocabulary of `pretrained_name` SCREAMING_SNAKE_CASE__ = f'''{text_of_1_token} {text_of_1_token}''' SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ) + 1, len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ) + 1, len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ), len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (len(__A ), len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = f''' {text}''' # tokenizer_r = self.rust_tokenizer_class.from_pretrained( # pretrained_name, use_fast=True, add_prefix_space=True, trim_offsets=True # ) # encoding = tokenizer_r(text, return_offsets_mapping=True, add_special_tokens=False) # self.assertEqual(encoding.offset_mapping[0], (1, 1 + len(text_of_1_token))) # self.assertEqual( # encoding.offset_mapping[1], # (1 + len(text_of_1_token) + 1, 1 + len(text_of_1_token) + 1 + len(text_of_1_token)), # ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ) + 1, 1 + len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ), 1 + len(__A ) + 1 + len(__A )) , ) SCREAMING_SNAKE_CASE__ = self.rust_tokenizer_class.from_pretrained( __A , use_fast=__A , add_prefix_space=__A , trim_offsets=__A ) SCREAMING_SNAKE_CASE__ = tokenizer_r(__A , return_offsets_mapping=__A , add_special_tokens=__A ) self.assertEqual(encoding.offset_mapping[0] , (0, 1 + len(__A )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(__A ), 1 + len(__A ) + 1 + len(__A )) , )
59
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
1
from math import ceil def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = list(range(0 , UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = [item for sublist in list(device_map.values() ) for item in sublist] # Duplicate check SCREAMING_SNAKE_CASE__ = [] for i in device_map_blocks: if device_map_blocks.count(UpperCamelCase__ ) > 1 and i not in duplicate_blocks: duplicate_blocks.append(UpperCamelCase__ ) # Missing blocks SCREAMING_SNAKE_CASE__ = [i for i in blocks if i not in device_map_blocks] SCREAMING_SNAKE_CASE__ = [i for i in device_map_blocks if i not in blocks] if len(UpperCamelCase__ ) != 0: raise ValueError( """Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device.""" """ These attention blocks were specified more than once: """ + str(UpperCamelCase__ ) ) if len(UpperCamelCase__ ) != 0: raise ValueError( """There are attention blocks for this model that are not specified in the device_map. Add these attention """ """blocks to a device on the device_map: """ + str(UpperCamelCase__ ) ) if len(UpperCamelCase__ ) != 0: raise ValueError( """The device_map contains more attention blocks than this model has. Remove these from the device_map:""" + str(UpperCamelCase__ ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = list(range(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = int(ceil(n_layers / len(UpperCamelCase__ ) ) ) SCREAMING_SNAKE_CASE__ = [layers[i : i + n_blocks] for i in range(0 , UpperCamelCase__ , UpperCamelCase__ )] return dict(zip(UpperCamelCase__ , UpperCamelCase__ ) )
59
# 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 = { 'configuration_xmod': [ 'XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XmodConfig', 'XmodOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'XMOD_PRETRAINED_MODEL_ARCHIVE_LIST', 'XmodForCausalLM', 'XmodForMaskedLM', 'XmodForMultipleChoice', 'XmodForQuestionAnswering', 'XmodForSequenceClassification', 'XmodForTokenClassification', 'XmodModel', 'XmodPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _lowerCamelCase = { 'configuration_gpt_neo': ['GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoConfig', 'GPTNeoOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST', 'GPTNeoForCausalLM', 'GPTNeoForQuestionAnswering', 'GPTNeoForSequenceClassification', 'GPTNeoForTokenClassification', 'GPTNeoModel', 'GPTNeoPreTrainedModel', 'load_tf_weights_in_gpt_neo', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ 'FlaxGPTNeoForCausalLM', 'FlaxGPTNeoModel', 'FlaxGPTNeoPreTrainedModel', ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
59
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "timm_backbone" def __init__( self :Union[str, Any] , __A :str=None , __A :Union[str, Any]=3 , __A :str=True , __A :Any=True , __A :Optional[Any]=None , **__A :List[str] , ) -> Tuple: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = features_only SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = True SCREAMING_SNAKE_CASE__ = out_indices if out_indices is not None else (-1,)
59
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'microsoft/focalnet-tiny': 'https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json', } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "focalnet" def __init__( self :Optional[int] , __A :str=224 , __A :List[Any]=4 , __A :List[Any]=3 , __A :Optional[Any]=96 , __A :Optional[Any]=False , __A :Union[str, Any]=[192, 384, 768, 768] , __A :Dict=[2, 2, 6, 2] , __A :Union[str, Any]=[2, 2, 2, 2] , __A :str=[3, 3, 3, 3] , __A :Optional[Any]="gelu" , __A :Tuple=4.0 , __A :List[str]=0.0 , __A :str=0.1 , __A :int=False , __A :Optional[Any]=1E-4 , __A :List[str]=False , __A :str=False , __A :List[str]=False , __A :Optional[int]=0.0_2 , __A :Union[str, Any]=1E-5 , __A :Tuple=32 , __A :Optional[Any]=None , __A :str=None , **__A :Optional[Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = image_size SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = use_conv_embed SCREAMING_SNAKE_CASE__ = hidden_sizes SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = focal_levels SCREAMING_SNAKE_CASE__ = focal_windows SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = use_layerscale SCREAMING_SNAKE_CASE__ = layerscale_value SCREAMING_SNAKE_CASE__ = use_post_layernorm SCREAMING_SNAKE_CASE__ = use_post_layernorm_in_modulation SCREAMING_SNAKE_CASE__ = normalize_modulator SCREAMING_SNAKE_CASE__ = initializer_range SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = encoder_stride SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
from math import pow, sqrt def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__: float ): SCREAMING_SNAKE_CASE__ = len(UpperCamelCase__ ) > 0 and all(value > 0.0 for value in values ) return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ ) else ValueError("""Input Error: Molar mass values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate * sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(effusion_rate / sqrt(molar_mass_a / molar_mass_a ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(molar_mass / pow(effusion_rate_a / effusion_rate_a , 2 ) , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: float , UpperCamelCase__: float , UpperCamelCase__: float ): return ( round(pow(effusion_rate_a / effusion_rate_a , 2 ) / molar_mass , 6 ) if validate(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else ValueError( """Input Error: Molar mass and effusion rate values must greater than 0.""" ) )
59
1
from maths.prime_check import is_prime def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): if not isinstance(UpperCamelCase__ , UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = f'''Input value of [number={number}] must be an integer''' raise TypeError(UpperCamelCase__ ) if is_prime(UpperCamelCase__ ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
59
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json', # See all Nat models at https://huggingface.co/models?filter=nat } class UpperCamelCase_ ( UpperCamelCase__ , UpperCamelCase__ ): lowerCamelCase_ = "nat" lowerCamelCase_ = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self :List[Any] , __A :Optional[Any]=4 , __A :Any=3 , __A :Optional[int]=64 , __A :Optional[int]=[3, 4, 6, 5] , __A :Union[str, Any]=[2, 4, 8, 16] , __A :Optional[Any]=7 , __A :Optional[Any]=3.0 , __A :List[Any]=True , __A :int=0.0 , __A :Dict=0.0 , __A :Optional[Any]=0.1 , __A :str="gelu" , __A :Optional[Any]=0.0_2 , __A :Optional[int]=1E-5 , __A :Optional[int]=0.0 , __A :Optional[Any]=None , __A :Union[str, Any]=None , **__A :Union[str, Any] , ) -> Optional[int]: """simple docstring""" super().__init__(**__A ) SCREAMING_SNAKE_CASE__ = patch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = embed_dim SCREAMING_SNAKE_CASE__ = depths SCREAMING_SNAKE_CASE__ = len(__A ) SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = kernel_size SCREAMING_SNAKE_CASE__ = mlp_ratio SCREAMING_SNAKE_CASE__ = qkv_bias SCREAMING_SNAKE_CASE__ = hidden_dropout_prob SCREAMING_SNAKE_CASE__ = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ = drop_path_rate SCREAMING_SNAKE_CASE__ = hidden_act SCREAMING_SNAKE_CASE__ = layer_norm_eps SCREAMING_SNAKE_CASE__ = initializer_range # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ = int(embed_dim * 2 ** (len(__A ) - 1) ) SCREAMING_SNAKE_CASE__ = layer_scale_init_value SCREAMING_SNAKE_CASE__ = ["""stem"""] + [f'''stage{idx}''' for idx in range(1 , len(__A ) + 1 )] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_aligned_output_features_output_indices( out_features=__A , out_indices=__A , stage_names=self.stage_names )
59
1
from collections import namedtuple import requests from lxml import html # type: ignore _lowerCamelCase = namedtuple('covid_data', 'cases deaths recovered') def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str = "https://www.worldometers.info/coronavirus/" ): SCREAMING_SNAKE_CASE__ = """//div[@class = \"maincounter-number\"]/span/text()""" return covid_data(*html.fromstring(requests.get(UpperCamelCase__ ).content ).xpath(UpperCamelCase__ ) ) _lowerCamelCase = 'Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
59
from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): return {key.lstrip("""-""" ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = ArgumentParser( """HuggingFace Datasets CLI tool""" , usage="""datasets-cli <command> [<args>]""" , allow_abbrev=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = parser.add_subparsers(help="""datasets-cli command helpers""" ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(UpperCamelCase__ ) EnvironmentCommand.register_subcommand(UpperCamelCase__ ) TestCommand.register_subcommand(UpperCamelCase__ ) RunBeamCommand.register_subcommand(UpperCamelCase__ ) DummyDataCommand.register_subcommand(UpperCamelCase__ ) # Parse args SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = parser.parse_known_args() if not hasattr(UpperCamelCase__ , """func""" ): parser.print_help() exit(1 ) SCREAMING_SNAKE_CASE__ = parse_unknown_args(UpperCamelCase__ ) # Run SCREAMING_SNAKE_CASE__ = args.func(UpperCamelCase__ , **UpperCamelCase__ ) service.run() if __name__ == "__main__": main()
59
1
import requests _lowerCamelCase = 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=' def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str ): # fetching a list of articles in json format SCREAMING_SNAKE_CASE__ = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page["""articles"""] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key='<Your BBC News API key goes here>')
59
import warnings from ...utils import logging from .image_processing_layoutlmva import LayoutLMvaImageProcessor _lowerCamelCase = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , *__A :Tuple , **__A :Dict ) -> None: """simple docstring""" warnings.warn( """The class LayoutLMv2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use LayoutLMv2ImageProcessor instead.""" , __A , ) super().__init__(*__A , **__A )
59
1
import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) _lowerCamelCase = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class UpperCamelCase_ : lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Model type selected in the list: " + ", ".join(UpperCamelCase__ )} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "The input data dir. Should contain the .json files for the SQuAD task."} ) lowerCamelCase_ = field( default=1_28 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) lowerCamelCase_ = field( default=1_28 , metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."} , ) lowerCamelCase_ = field( default=64 , metadata={ "help": ( "The maximum number of tokens for the question. Questions longer than this will " "be truncated to this length." ) } , ) lowerCamelCase_ = field( default=30 , metadata={ "help": ( "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." ) } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={"help": "If true, the SQuAD examples contain some that do not have an answer."} ) lowerCamelCase_ = field( default=0.0 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCamelCase_ = field( default=20 , metadata={"help": "If null_score - best_non_null is greater than the threshold predict null."} ) lowerCamelCase_ = field( default=0 , metadata={ "help": ( "language id of input for language-specific xlm models (see" " tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)" ) } , ) lowerCamelCase_ = field(default=1 , metadata={"help": "multiple threads for converting example to features"} ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "train" lowerCamelCase_ = "dev" class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 lowerCamelCase_ = 42 def __init__( self :Dict , __A :SquadDataTrainingArguments , __A :PreTrainedTokenizer , __A :Optional[int] = None , __A :Union[str, Split] = Split.train , __A :Optional[bool] = False , __A :Optional[str] = None , __A :Optional[str] = "pt" , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ = args SCREAMING_SNAKE_CASE__ = is_language_sensitive SCREAMING_SNAKE_CASE__ = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(__A , __A ): try: SCREAMING_SNAKE_CASE__ = Split[mode] except KeyError: raise KeyError("""mode is not a valid split name""" ) SCREAMING_SNAKE_CASE__ = mode # Load data features from cache or dataset file SCREAMING_SNAKE_CASE__ = """v2""" if args.version_2_with_negative else """v1""" SCREAMING_SNAKE_CASE__ = os.path.join( cache_dir if cache_dir is not None else args.data_dir , f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}''' , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. SCREAMING_SNAKE_CASE__ = cached_features_file + """.lock""" with FileLock(__A ): if os.path.exists(__A ) and not args.overwrite_cache: SCREAMING_SNAKE_CASE__ = time.time() SCREAMING_SNAKE_CASE__ = torch.load(__A ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. SCREAMING_SNAKE_CASE__ = self.old_features["""features"""] SCREAMING_SNAKE_CASE__ = self.old_features.get("""dataset""" , __A ) SCREAMING_SNAKE_CASE__ = self.old_features.get("""examples""" , __A ) logger.info( f'''Loading features from cached file {cached_features_file} [took %.3f s]''' , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( f'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in''' """ future run""" ) else: if mode == Split.dev: SCREAMING_SNAKE_CASE__ = self.processor.get_dev_examples(args.data_dir ) else: SCREAMING_SNAKE_CASE__ = self.processor.get_train_examples(args.data_dir ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = squad_convert_examples_to_features( examples=self.examples , tokenizer=__A , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=__A , ) SCREAMING_SNAKE_CASE__ = time.time() torch.save( {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples} , __A , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]''' ) def __len__( self :int ) -> Union[str, Any]: """simple docstring""" return len(self.features ) def __getitem__( self :Any , __A :Dict ) -> Dict[str, torch.Tensor]: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.features[i] SCREAMING_SNAKE_CASE__ = torch.tensor(feature.input_ids , dtype=torch.long ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.attention_mask , dtype=torch.long ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.token_type_ids , dtype=torch.long ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.cls_index , dtype=torch.long ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.p_mask , dtype=torch.float ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.is_impossible , dtype=torch.float ) SCREAMING_SNAKE_CASE__ = { """input_ids""": input_ids, """attention_mask""": attention_mask, """token_type_ids""": token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask} ) if self.args.version_2_with_negative: inputs.update({"""is_impossible""": is_impossible} ) if self.is_language_sensitive: inputs.update({"""langs""": (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: SCREAMING_SNAKE_CASE__ = torch.tensor(feature.start_position , dtype=torch.long ) SCREAMING_SNAKE_CASE__ = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions} ) return inputs
59
import unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class UpperCamelCase_ ( unittest.TestCase ): @require_torch def _snake_case ( self :Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""hf-internal-testing/tiny-clap-htsat-unfused""" ) SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [{"""score""": 0.5_0_1, """label""": """Sound of a dog"""}, {"""score""": 0.4_9_9, """label""": """Sound of vaccum cleaner"""}] , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :Dict ) -> List[str]: """simple docstring""" pass @slow @require_torch def _snake_case ( self :Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = pipeline( task="""zero-shot-audio-classification""" , model="""laion/clap-htsat-unfused""" , ) # This is an audio of a dog SCREAMING_SNAKE_CASE__ = load_dataset("""ashraq/esc50""" ) SCREAMING_SNAKE_CASE__ = dataset["""train"""]["""audio"""][-1]["""array"""] SCREAMING_SNAKE_CASE__ = audio_classifier(__A , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ] , ) SCREAMING_SNAKE_CASE__ = audio_classifier([audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) SCREAMING_SNAKE_CASE__ = audio_classifier( [audio] * 5 , candidate_labels=["""Sound of a dog""", """Sound of vaccum cleaner"""] , batch_size=5 ) self.assertEqual( nested_simplify(__A ) , [ [ {"""score""": 0.9_9_9, """label""": """Sound of a dog"""}, {"""score""": 0.0_0_1, """label""": """Sound of vaccum cleaner"""}, ], ] * 5 , ) @unittest.skip("""No models are available in TF""" ) def _snake_case ( self :str ) -> Optional[int]: """simple docstring""" pass
59
1
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Image from .base import TaskTemplate @dataclass(frozen=UpperCamelCase__ ) class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = field(default="image-classification" , metadata={"include_in_asdict_even_if_is_default": True} ) lowerCamelCase_ = Features({"image": Image()} ) lowerCamelCase_ = Features({"labels": ClassLabel} ) lowerCamelCase_ = "image" lowerCamelCase_ = "labels" def _snake_case ( self :List[str] , __A :Tuple ) -> Tuple: """simple docstring""" if self.label_column not in features: raise ValueError(f'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , __A ): raise ValueError(f'''Column {self.label_column} is not a ClassLabel.''' ) SCREAMING_SNAKE_CASE__ = copy.deepcopy(self ) SCREAMING_SNAKE_CASE__ = self.label_schema.copy() SCREAMING_SNAKE_CASE__ = features[self.label_column] SCREAMING_SNAKE_CASE__ = label_schema return task_template @property def _snake_case ( self :Dict ) -> Dict[str, str]: """simple docstring""" return { self.image_column: "image", self.label_column: "labels", }
59
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 _lowerCamelCase = data_utils.TransfoXLTokenizer _lowerCamelCase = data_utils.TransfoXLCorpus _lowerCamelCase = data_utils _lowerCamelCase = data_utils def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Any , UpperCamelCase__: Any , UpperCamelCase__: Tuple ): if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , """rb""" ) as fp: SCREAMING_SNAKE_CASE__ = pickle.load(UpperCamelCase__ , encoding="""latin1""" ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + VOCAB_FILES_NAMES["""pretrained_vocab_file"""] print(f'''Save vocabulary to {pytorch_vocab_dump_path}''' ) SCREAMING_SNAKE_CASE__ = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = corpus.__dict__ corpus_dict_no_vocab.pop("""vocab""" , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = pytorch_dump_folder_path + """/""" + CORPUS_NAME print(f'''Save dataset to {pytorch_dataset_dump_path}''' ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.abspath(UpperCamelCase__ ) print(f'''Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.''' ) # Initialise PyTorch model if transfo_xl_config_file == "": SCREAMING_SNAKE_CASE__ = TransfoXLConfig() else: SCREAMING_SNAKE_CASE__ = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(f'''Building PyTorch model from configuration: {config}''' ) SCREAMING_SNAKE_CASE__ = TransfoXLLMHeadModel(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(f'''Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}''' ) torch.save(model.state_dict() , UpperCamelCase__ ) print(f'''Save configuration file to {os.path.abspath(UpperCamelCase__ )}''' ) with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the folder to store the PyTorch model or dataset/vocab.', ) parser.add_argument( '--tf_checkpoint_path', default='', type=str, help='An optional path to a TensorFlow checkpoint path to be converted.', ) parser.add_argument( '--transfo_xl_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--transfo_xl_dataset_file', default='', type=str, help='An optional dataset file to be converted in a vocabulary.', ) _lowerCamelCase = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
59
1
from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = "t5" lowerCamelCase_ = ["past_key_values"] lowerCamelCase_ = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self :List[str] , __A :str=3_2128 , __A :Any=512 , __A :List[str]=64 , __A :Dict=2048 , __A :Optional[Any]=6 , __A :int=None , __A :List[Any]=8 , __A :int=32 , __A :Optional[Any]=128 , __A :str=0.1 , __A :str=1E-6 , __A :List[str]=1.0 , __A :Optional[int]="relu" , __A :Optional[Any]=True , __A :int=True , __A :Any=0 , __A :Union[str, Any]=1 , **__A :Optional[int] , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ = vocab_size SCREAMING_SNAKE_CASE__ = d_model SCREAMING_SNAKE_CASE__ = d_kv SCREAMING_SNAKE_CASE__ = d_ff SCREAMING_SNAKE_CASE__ = num_layers SCREAMING_SNAKE_CASE__ = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry SCREAMING_SNAKE_CASE__ = num_heads SCREAMING_SNAKE_CASE__ = relative_attention_num_buckets SCREAMING_SNAKE_CASE__ = relative_attention_max_distance SCREAMING_SNAKE_CASE__ = dropout_rate SCREAMING_SNAKE_CASE__ = layer_norm_epsilon SCREAMING_SNAKE_CASE__ = initializer_factor SCREAMING_SNAKE_CASE__ = feed_forward_proj SCREAMING_SNAKE_CASE__ = use_cache SCREAMING_SNAKE_CASE__ = self.feed_forward_proj.split("""-""" ) SCREAMING_SNAKE_CASE__ = act_info[-1] SCREAMING_SNAKE_CASE__ = act_info[0] == """gated""" if len(__A ) > 1 and act_info[0] != "gated" or len(__A ) > 2: raise ValueError( f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.''' """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """ """'gated-gelu' or 'relu'""" ) # for backwards compatibility if feed_forward_proj == "gated-gelu": SCREAMING_SNAKE_CASE__ = """gelu_new""" super().__init__( pad_token_id=__A , eos_token_id=__A , is_encoder_decoder=__A , **__A , ) class UpperCamelCase_ ( UpperCamelCase__ ): @property def _snake_case ( self :Union[str, Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ = { """input_ids""": {0: """batch""", 1: """encoder_sequence"""}, """attention_mask""": {0: """batch""", 1: """encoder_sequence"""}, } if self.use_past: SCREAMING_SNAKE_CASE__ = """past_encoder_sequence + sequence""" SCREAMING_SNAKE_CASE__ = {0: """batch"""} SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """decoder_sequence"""} SCREAMING_SNAKE_CASE__ = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(__A , direction="""inputs""" ) return common_inputs @property def _snake_case ( self :int ) -> int: """simple docstring""" return 13
59
import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: str , UpperCamelCase__: str , UpperCamelCase__: str ): def get_masked_lm_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_array(UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_layer_array(UpperCamelCase__: int , UpperCamelCase__: str ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) def get_encoder_attention_layer_array(UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = f'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE''' SCREAMING_SNAKE_CASE__ = tf.train.load_variable(UpperCamelCase__ , UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = array.reshape(UpperCamelCase__ ) if "kernel" in name: SCREAMING_SNAKE_CASE__ = array.transpose() return torch.from_numpy(UpperCamelCase__ ) print(f'''Loading model based on config from {config_path}...''' ) SCREAMING_SNAKE_CASE__ = BertConfig.from_json_file(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = BertForMaskedLM(UpperCamelCase__ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ = model.bert.encoder.layer[layer_index] # Self-attention SCREAMING_SNAKE_CASE__ = layer.attention.self SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/kernel""" , self_attn.query.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_query_dense/bias""" , self_attn.query.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/kernel""" , self_attn.key.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_key_dense/bias""" , self_attn.key.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/kernel""" , self_attn.value.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_value_dense/bias""" , self_attn.value.bias.data.shape ) # Self-attention Output SCREAMING_SNAKE_CASE__ = layer.attention.output SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/kernel""" , self_output.dense.weight.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_attention_layer_array( UpperCamelCase__ , """_output_dense/bias""" , self_output.dense.bias.data.shape ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_attention_layer_norm/beta""" ) # Intermediate SCREAMING_SNAKE_CASE__ = layer.intermediate SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_intermediate_dense/bias""" ) # Output SCREAMING_SNAKE_CASE__ = layer.output SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_layer_array(UpperCamelCase__ , """_output_layer_norm/beta""" ) # Embeddings SCREAMING_SNAKE_CASE__ = get_encoder_array("""_position_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_type_embedding_layer/embeddings""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/gamma""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_embedding_norm_layer/beta""" ) # LM Head SCREAMING_SNAKE_CASE__ = model.cls.predictions.transform SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/kernel""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""dense/bias""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/gamma""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""layer_norm/beta""" ) SCREAMING_SNAKE_CASE__ = get_masked_lm_array("""embedding_table""" ) # Pooling SCREAMING_SNAKE_CASE__ = BertPooler(config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/kernel""" ) SCREAMING_SNAKE_CASE__ = get_encoder_array("""_pooler_layer/bias""" ) # Export final model model.save_pretrained(UpperCamelCase__ ) # Integration test - should load without any errors ;) SCREAMING_SNAKE_CASE__ = BertForMaskedLM.from_pretrained(UpperCamelCase__ ) print(new_model.eval() ) print("""Model conversion was done sucessfully!""" ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--tf_checkpoint_path', type=str, required=True, help='Path to the TensorFlow Token Dropping checkpoint path.' ) parser.add_argument( '--bert_config_file', type=str, required=True, help='The config json file corresponding to the BERT model. This specifies the model architecture.', ) parser.add_argument( '--pytorch_dump_path', type=str, required=True, help='Path to the output PyTorch model.', ) _lowerCamelCase = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
59
1
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = ["image_processor", "tokenizer"] lowerCamelCase_ = "ChineseCLIPImageProcessor" lowerCamelCase_ = ("BertTokenizer", "BertTokenizerFast") def __init__( self :List[str] , __A :int=None , __A :Optional[Any]=None , **__A :Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , __A , ) SCREAMING_SNAKE_CASE__ = kwargs.pop("""feature_extractor""" ) SCREAMING_SNAKE_CASE__ = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(__A , __A ) SCREAMING_SNAKE_CASE__ = self.image_processor def __call__( self :List[str] , __A :Tuple=None , __A :int=None , __A :Optional[int]=None , **__A :List[Any] ) -> Tuple: """simple docstring""" if text is None and images is None: raise ValueError("""You have to specify either text or images. Both cannot be none.""" ) if text is not None: SCREAMING_SNAKE_CASE__ = self.tokenizer(__A , return_tensors=__A , **__A ) if images is not None: SCREAMING_SNAKE_CASE__ = self.image_processor(__A , return_tensors=__A , **__A ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__A ) , tensor_type=__A ) def _snake_case ( self :List[Any] , *__A :Union[str, Any] , **__A :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__A , **__A ) def _snake_case ( self :Any , *__A :Optional[int] , **__A :str ) -> List[Any]: """simple docstring""" return self.tokenizer.decode(*__A , **__A ) @property def _snake_case ( self :Any ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def _snake_case ( self :Dict ) -> List[Any]: """simple docstring""" warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , __A , ) return self.image_processor_class
59
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _lowerCamelCase = '\\n Text data.\n Second line of data.' _lowerCamelCase = 'file' @pytest.fixture(scope="""session""" ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") SCREAMING_SNAKE_CASE__ = bytes(UpperCamelCase__ , """utf-8""" ) with zstd.open(UpperCamelCase__ , """wb""" ) as f: f.write(UpperCamelCase__ ) return path @pytest.fixture def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): with open(os.path.join(tmpfs.local_root_dir , UpperCamelCase__ ) , """w""" ) as f: f.write(UpperCamelCase__ ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Dict , UpperCamelCase__: int , UpperCamelCase__: str , UpperCamelCase__: Optional[int] , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} SCREAMING_SNAKE_CASE__ = input_paths[compression_format] SCREAMING_SNAKE_CASE__ = tmp_path / """cache""" SCREAMING_SNAKE_CASE__ = DownloadConfig(cache_dir=UpperCamelCase__ , extract_compressed_file=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: List[str] , UpperCamelCase__: Optional[int] , UpperCamelCase__: Any , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = """custom_cache""" SCREAMING_SNAKE_CASE__ = """custom_extracted_dir""" SCREAMING_SNAKE_CASE__ = tmp_path / """custom_extracted_path""" if default_extracted: SCREAMING_SNAKE_CASE__ = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , UpperCamelCase__ ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) SCREAMING_SNAKE_CASE__ = xz_file SCREAMING_SNAKE_CASE__ = ( DownloadConfig(extract_compressed_file=UpperCamelCase__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=UpperCamelCase__ ) ) SCREAMING_SNAKE_CASE__ = cached_path(UpperCamelCase__ , download_config=UpperCamelCase__ ) assert Path(UpperCamelCase__ ).parent.parts[-2:] == expected def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[int] ): # absolute path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve() ) assert cached_path(UpperCamelCase__ ) == text_file # relative path SCREAMING_SNAKE_CASE__ = str(Path(UpperCamelCase__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(UpperCamelCase__ ) == text_file def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): # absolute path SCREAMING_SNAKE_CASE__ = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) # relative path SCREAMING_SNAKE_CASE__ = """./__missing_file__.txt""" with pytest.raises(UpperCamelCase__ ): cached_path(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = get_from_cache(f'''tmp://{tmpfs_file}''' ) with open(UpperCamelCase__ ) as f: SCREAMING_SNAKE_CASE__ = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( ): with pytest.raises(UpperCamelCase__ ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): http_get("""https://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): ftp_get("""ftp://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int ): SCREAMING_SNAKE_CASE__ = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(UpperCamelCase__ ): fsspec_get("""s3://huggingface.co""" , temp_file=UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): fsspec_head("""s3://huggingface.co""" )
59
1
import random from typing import Any def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: list ): for _ in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = random.randint(0 , len(UpperCamelCase__ ) - 1 ) SCREAMING_SNAKE_CASE__ = random.randint(0 , len(UpperCamelCase__ ) - 1 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = data[b], data[a] return data if __name__ == "__main__": _lowerCamelCase = [0, 1, 2, 3, 4, 5, 6, 7] _lowerCamelCase = ['python', 'says', 'hello', '!'] print('Fisher-Yates Shuffle:') print('List', integers, strings) print('FY Shuffle', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
59
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _lowerCamelCase = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE__ ( ): SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser( description="""Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.""" ) parser.add_argument( """--dataset_name""" , type=UpperCamelCase__ , default="""wikitext""" , help="""Name of the training. Explore datasets at: hf.co/datasets.""" , ) parser.add_argument( """--dataset_config""" , type=UpperCamelCase__ , default="""wikitext-103-raw-v1""" , help="""Configuration name of the dataset.""" ) parser.add_argument( """--tokenizer_name_or_path""" , type=UpperCamelCase__ , default="""sayakpaul/unigram-tokenizer-wikitext""" , help="""Tokenizer identifier. Can be a local filepath or a Hub identifier.""" , ) parser.add_argument( """--shard_size""" , type=UpperCamelCase__ , default=1_000 , help="""Number of entries to go in a single shard.""" , ) parser.add_argument("""--split""" , type=UpperCamelCase__ , default="""train""" , choices=["""train""", """test""", """validation"""] ) parser.add_argument( """--limit""" , default=UpperCamelCase__ , type=UpperCamelCase__ , help="""Limit the number of shards (used for debugging).""" , ) parser.add_argument( """--max_length""" , type=UpperCamelCase__ , 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=UpperCamelCase__ , 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.""" , ) SCREAMING_SNAKE_CASE__ = parser.parse_args() return args def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[Any] ): def fn(UpperCamelCase__: Any ): return tokenizer(examples["""text"""] ) return fn def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = [] for i in range(len(tokenized_data["""input_ids"""] ) ): SCREAMING_SNAKE_CASE__ = { """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] ) ), } SCREAMING_SNAKE_CASE__ = tf.train.Features(feature=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = tf.train.Example(features=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = example.SerializeToString() records.append(UpperCamelCase__ ) return records def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: List[str] ): SCREAMING_SNAKE_CASE__ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE__ = min(len(UpperCamelCase__ ) , args.limit ) SCREAMING_SNAKE_CASE__ = dataset.select(range(UpperCamelCase__ ) ) print(f'''Limiting the dataset to {args.limit} entries.''' ) SCREAMING_SNAKE_CASE__ = 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 ) SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) if not os.path.exists(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) else: SCREAMING_SNAKE_CASE__ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE__ = tokenize_function(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = dataset.map(UpperCamelCase__ , batched=UpperCamelCase__ , 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(UpperCamelCase__: int ): # Concatenate all texts. SCREAMING_SNAKE_CASE__ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE__ = 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 🫀 SCREAMING_SNAKE_CASE__ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE__ = { k: [t[i : i + args.max_length] for i in range(0 , UpperCamelCase__ , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE__ = dataset_tokenized.map(UpperCamelCase__ , batched=UpperCamelCase__ , batch_size=1_000 , num_proc=4 ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 for shard in range(0 , len(UpperCamelCase__ ) , args.shard_size ): SCREAMING_SNAKE_CASE__ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE__ = len(dataset_snapshot["""input_ids"""] ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''dataset-{shard_count}-{records_containing}.tfrecord''' ) SCREAMING_SNAKE_CASE__ = get_serialized_examples(UpperCamelCase__ ) with tf.io.TFRecordWriter(UpperCamelCase__ ) as out_file: for i in range(len(UpperCamelCase__ ) ): SCREAMING_SNAKE_CASE__ = serialized_examples[i] out_file.write(UpperCamelCase__ ) print("""Wrote file {} containing {} records""".format(UpperCamelCase__ , UpperCamelCase__ ) ) 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=UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = parse_args() main(args)
59
1