code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None UpperCamelCase = None class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A=1 , A=0 , A=2 , A=512 , A="cls" , A=False , A=True , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _SCREAMING_SNAKE_CASE = project_dim _SCREAMING_SNAKE_CASE = pooler_fn _SCREAMING_SNAKE_CASE = learn_encoder _SCREAMING_SNAKE_CASE = use_attention_mask class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = [R'''pooler''', R'''logit_scale'''] UpperCamelCase = [R'''position_ids''', R'''predictions.decoder.bias'''] UpperCamelCase = '''roberta''' UpperCamelCase = RobertaSeriesConfig def __init__( self , A ) -> Optional[int]: super().__init__(A ) _SCREAMING_SNAKE_CASE = XLMRobertaModel(A ) _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) _SCREAMING_SNAKE_CASE = getattr(A , """has_pre_transformation""" , A ) if self.has_pre_transformation: _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.project_dim ) _SCREAMING_SNAKE_CASE = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def snake_case_( self , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , A = None , ) -> Any: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.base_model( input_ids=A , attention_mask=A , token_type_ids=A , position_ids=A , head_mask=A , inputs_embeds=A , encoder_hidden_states=A , encoder_attention_mask=A , output_attentions=A , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=A , ) if self.has_pre_transformation: _SCREAMING_SNAKE_CASE = outputs["""hidden_states"""][-2] _SCREAMING_SNAKE_CASE = self.pre_LN(A ) _SCREAMING_SNAKE_CASE = self.transformation_pre(A ) return TransformationModelOutput( projection_state=A , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: _SCREAMING_SNAKE_CASE = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=A , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
58
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def lowerCamelCase ( __lowerCamelCase : str ) ->str: if not sentence: return "" _SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , __lowerCamelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
58
1
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ) ->Union[str, Any]: assert isinstance(__lowerCamelCase , __lowerCamelCase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] ) ->Optional[int]: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase ).read() _check_json_dataset(__lowerCamelCase , __lowerCamelCase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : str , __lowerCamelCase : str ) ->Dict: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE = ( Features({feature: Value(__lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase ).read() _check_json_dataset(__lowerCamelCase , __lowerCamelCase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""}, ] , ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_3""": """float64""", """col_1""": """string""", """col_2""": """int64"""} _SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE = ( Features({feature: Value(__lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase ).read() assert isinstance(__lowerCamelCase , __lowerCamelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Tuple ) ->Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} _SCREAMING_SNAKE_CASE = {"""col_2""": """int64""", """col_3""": """float64""", """col_1""": """string"""} _SCREAMING_SNAKE_CASE = features.copy() _SCREAMING_SNAKE_CASE = ( Features({feature: Value(__lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , features=__lowerCamelCase , cache_dir=__lowerCamelCase ).read() assert isinstance(__lowerCamelCase , __lowerCamelCase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int] ) ->Dict: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , cache_dir=__lowerCamelCase , split=__lowerCamelCase ).read() _check_json_dataset(__lowerCamelCase , __lowerCamelCase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize("""path_type""" , [str, list] ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str ) ->Any: if issubclass(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = jsonl_path elif issubclass(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = [jsonl_path] _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , cache_dir=__lowerCamelCase ).read() _check_json_dataset(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : List[str] , __lowerCamelCase : int=("train",) ) ->Optional[int]: assert isinstance(__lowerCamelCase , __lowerCamelCase ) for split in splits: _SCREAMING_SNAKE_CASE = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("""keep_in_memory""" , [False, True] ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Any , __lowerCamelCase : int ) ->List[Any]: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): _SCREAMING_SNAKE_CASE = JsonDatasetReader({"""train""": jsonl_path} , cache_dir=__lowerCamelCase , keep_in_memory=__lowerCamelCase ).read() _check_json_datasetdict(__lowerCamelCase , __lowerCamelCase ) @pytest.mark.parametrize( """features""" , [ None, {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""}, {"""col_1""": """string""", """col_2""": """string""", """col_3""": """string"""}, {"""col_1""": """int32""", """col_2""": """int32""", """col_3""": """int32"""}, {"""col_1""": """float32""", """col_2""": """float32""", """col_3""": """float32"""}, ] , ) def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any ) ->str: _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE = features.copy() if features else default_expected_features _SCREAMING_SNAKE_CASE = ( Features({feature: Value(__lowerCamelCase ) for feature, dtype in features.items()} ) if features is not None else None ) _SCREAMING_SNAKE_CASE = JsonDatasetReader({"""train""": jsonl_path} , features=__lowerCamelCase , cache_dir=__lowerCamelCase ).read() _check_json_datasetdict(__lowerCamelCase , __lowerCamelCase ) @pytest.mark.parametrize("""split""" , [None, NamedSplit("""train""" ), """train""", """test"""] ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : int ) ->int: if split: _SCREAMING_SNAKE_CASE = {split: jsonl_path} else: _SCREAMING_SNAKE_CASE = """train""" _SCREAMING_SNAKE_CASE = {"""train""": jsonl_path, """test""": jsonl_path} _SCREAMING_SNAKE_CASE = tmp_path / """cache""" _SCREAMING_SNAKE_CASE = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} _SCREAMING_SNAKE_CASE = JsonDatasetReader(__lowerCamelCase , cache_dir=__lowerCamelCase ).read() _check_json_datasetdict(__lowerCamelCase , __lowerCamelCase , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase ( __lowerCamelCase : List[str] ) ->Optional[Any]: return json.load(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : int ) ->str: return [json.loads(__lowerCamelCase ) for line in buffer] class a_ : '''simple docstring''' @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def snake_case_( self , A , A , A ) -> Dict: with io.BytesIO() as buffer: JsonDatasetWriter(A , A , lines=A ).write() buffer.seek(0 ) _SCREAMING_SNAKE_CASE = load_json_function(A ) assert isinstance(A , A ) assert isinstance(exported_content[0] , A ) assert len(A ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def snake_case_( self , A , A , A , A , A ) -> Union[str, Any]: with io.BytesIO() as buffer: JsonDatasetWriter(A , A , lines=A , orient=A ).write() buffer.seek(0 ) _SCREAMING_SNAKE_CASE = load_json(A ) assert isinstance(A , A ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(A ) == 10 @pytest.mark.parametrize("""lines, load_json_function""" , [(True, load_json_lines), (False, load_json)] ) def snake_case_( self , A , A , A ) -> Tuple: with io.BytesIO() as buffer: JsonDatasetWriter(A , A , lines=A , num_proc=2 ).write() buffer.seek(0 ) _SCREAMING_SNAKE_CASE = load_json_function(A ) assert isinstance(A , A ) assert isinstance(exported_content[0] , A ) assert len(A ) == 10 @pytest.mark.parametrize( """orient, container, keys, len_at""" , [ ("""records""", list, {"""tokens""", """labels""", """answers""", """id"""}, None), ("""split""", dict, {"""columns""", """data"""}, """data"""), ("""index""", dict, set("""0123456789""" ), None), ("""columns""", dict, {"""tokens""", """labels""", """answers""", """id"""}, """tokens"""), ("""values""", list, None, None), ("""table""", dict, {"""schema""", """data"""}, """data"""), ] , ) def snake_case_( self , A , A , A , A , A ) -> List[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(A , A , lines=A , orient=A , num_proc=2 ).write() buffer.seek(0 ) _SCREAMING_SNAKE_CASE = load_json(A ) assert isinstance(A , A ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A , """keys""" ) and not hasattr(exported_content[0] , """keys""" ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(A ) == 10 def snake_case_( self , A ) -> int: with pytest.raises(A ): with io.BytesIO() as buffer: JsonDatasetWriter(A , A , num_proc=0 ) @pytest.mark.parametrize("""compression, extension""" , [("""gzip""", """gz"""), ("""bz2""", """bz2"""), ("""xz""", """xz""")] ) def snake_case_( self , A , A , A , A , A ) -> Any: _SCREAMING_SNAKE_CASE = tmp_path_factory.mktemp("""data""" ) / f'test.json.{extension}' _SCREAMING_SNAKE_CASE = str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(A , A , compression=A ).write() with fsspec.open(A , """rb""" , compression="""infer""" ) as f: _SCREAMING_SNAKE_CASE = f.read() with fsspec.open(A , """rb""" , compression="""infer""" ) as f: _SCREAMING_SNAKE_CASE = f.read() assert exported_content == original_content
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available lowercase_ = {"""tokenization_herbert""": ["""HerbertTokenizer"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""HerbertTokenizerFast"""] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any]=8 ) ->Tuple: _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A , A , ) -> Union[str, Any]: super().__init__() self.register_modules( unet=A , scheduler=A , movq=A , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_( self , A , A , A , A , A , A ) -> Union[str, Any]: if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A , device=A , dtype=A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(A ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_( self , A=0 ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A , A ) def snake_case_( self , A=0 ) -> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(A , A , prev_module_hook=A ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_( self ) -> Tuple: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self , A , A , A = 512 , A = 512 , A = 100 , A = 4.0 , A = 1 , A = None , A = None , A = "pil" , A = True , ) -> List[str]: _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A ) self.scheduler.set_timesteps(A , device=A ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(A , A , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A , A , A , self.scheduler , ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE = self.unet( sample=A , timestep=A , encoder_hidden_states=A , added_cond_kwargs=A , return_dict=A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( A , A , A , generator=A , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(A , force_not_quantize=A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
58
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[Any]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Tuple: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Dict: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Tuple: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Any: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Any: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> List[str]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> int: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Any: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> List[str]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[str]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Union[str, Any]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Optional[Any]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Tuple: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[Any]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[Any]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Union[str, Any]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> str: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Tuple: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[Any]: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> List[str]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> str: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Tuple: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Optional[Any]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Optional[Any]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Optional[int]: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> Optional[int]: requires_backends(cls , ["""flax"""] ) class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''flax'''] def __init__( self , *A , **A ) -> Dict: requires_backends(self , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> str: requires_backends(cls , ["""flax"""] ) @classmethod def snake_case_( cls , *A , **A ) -> int: requires_backends(cls , ["""flax"""] )
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str ) ->bool: _SCREAMING_SNAKE_CASE = get_failure_array(__lowerCamelCase ) # 2) Step through text searching for pattern _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 0, 0 # index into text, pattern while i < len(__lowerCamelCase ): if pattern[j] == text[i]: if j == (len(__lowerCamelCase ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: _SCREAMING_SNAKE_CASE = failure[j - 1] continue i += 1 return False def lowerCamelCase ( __lowerCamelCase : str ) ->list[int]: _SCREAMING_SNAKE_CASE = [0] _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 1 while j < len(__lowerCamelCase ): if pattern[i] == pattern[j]: i += 1 elif i > 0: _SCREAMING_SNAKE_CASE = failure[i - 1] continue j += 1 failure.append(__lowerCamelCase ) return failure if __name__ == "__main__": # Test 1) lowercase_ = """abc1abc12""" lowercase_ = """alskfjaldsabc1abc1abc12k23adsfabcabc""" lowercase_ = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) lowercase_ = """ABABX""" lowercase_ = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) lowercase_ = """AAAB""" lowercase_ = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) lowercase_ = """abcdabcy""" lowercase_ = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) lowercase_ = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
58
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """PoolFormerConfig""" # Base docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = [1, 512, 7, 7] # Image classification docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : float = 0.0 , __lowerCamelCase : bool = False ) ->int: if drop_prob == 0.0 or not training: return input _SCREAMING_SNAKE_CASE = 1 - drop_prob _SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _SCREAMING_SNAKE_CASE = keep_prob + torch.rand(__lowerCamelCase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _SCREAMING_SNAKE_CASE = input.div(__lowerCamelCase ) * random_tensor return output class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A = None ) -> None: super().__init__() _SCREAMING_SNAKE_CASE = drop_prob def snake_case_( self , A ) -> torch.Tensor: return drop_path(A , self.drop_prob , self.training ) def snake_case_( self ) -> str: return "p={}".format(self.drop_prob ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A=None ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = patch_size if isinstance(A , collections.abc.Iterable ) else (patch_size, patch_size) _SCREAMING_SNAKE_CASE = stride if isinstance(A , collections.abc.Iterable ) else (stride, stride) _SCREAMING_SNAKE_CASE = padding if isinstance(A , collections.abc.Iterable ) else (padding, padding) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , kernel_size=A , stride=A , padding=A ) _SCREAMING_SNAKE_CASE = norm_layer(A ) if norm_layer else nn.Identity() def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.projection(A ) _SCREAMING_SNAKE_CASE = self.norm(A ) return embeddings class a_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self , A , **A ) -> Union[str, Any]: super().__init__(1 , A , **A ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.AvgPoolad(A , stride=1 , padding=pool_size // 2 , count_include_pad=A ) def snake_case_( self , A ) -> Union[str, Any]: return self.pool(A ) - hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if isinstance(config.hidden_act , A ): _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: _SCREAMING_SNAKE_CASE = config.hidden_act def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.act_fn(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) return hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = PoolFormerPooling(A ) _SCREAMING_SNAKE_CASE = PoolFormerOutput(A , A , A , A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) # Useful for training neural nets _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() _SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) def snake_case_( self , A ) -> Optional[Any]: if self.use_layer_scale: _SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = () _SCREAMING_SNAKE_CASE = self.output(self.after_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: _SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection _SCREAMING_SNAKE_CASE = pooling_output + hidden_states _SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block _SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(A ) ) ) _SCREAMING_SNAKE_CASE = hidden_states + layer_output _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE = config # stochastic depth decay rule _SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) # Transformer blocks _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(A ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) def snake_case_( self , A , A=False , A=True ) -> List[Any]: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None _SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states _SCREAMING_SNAKE_CASE = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): _SCREAMING_SNAKE_CASE = blk(A ) _SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: _SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = PoolFormerConfig UpperCamelCase = '''poolformer''' UpperCamelCase = '''pixel_values''' UpperCamelCase = True def snake_case_( self , A ) -> int: if isinstance(A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_( self , A , A=False ) -> Dict: if isinstance(A , A ): _SCREAMING_SNAKE_CASE = value lowercase_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> int: super().__init__(A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def snake_case_( self ) -> Any: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A = None , A = None , A = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A , hidden_states=encoder_outputs.hidden_states , ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> Optional[Any]: super().__init__(A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = PoolFormerModel(A ) # Final norm _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.poolformer( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = outputs[0] _SCREAMING_SNAKE_CASE = self.classifier(self.norm(A ).mean([-2, -1] ) ) _SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE = """single_label_classification""" else: _SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE = loss_fct(A , A ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE = CrossEntropyLoss() _SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE = loss_fct(A , A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
1
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase_ = logging.getLogger(__name__) lowercase_ = """Hello world! cécé herlolip""" lowercase_ = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir=""".""" , finetune_bert=__lowerCamelCase , large=__lowerCamelCase , share_emb=__lowerCamelCase , use_bert_emb=__lowerCamelCase , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , lambda __lowerCamelCase , __lowerCamelCase : storage ) _SCREAMING_SNAKE_CASE = AbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) , __lowerCamelCase ) original.eval() _SCREAMING_SNAKE_CASE = BertAbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass _SCREAMING_SNAKE_CASE = encoder_input_ids _SCREAMING_SNAKE_CASE = decoder_input_ids _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical _SCREAMING_SNAKE_CASE = original(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = original.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = new_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = new_model.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) lowercase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
58
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
58
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
1
'''simple docstring''' class a_ : '''simple docstring''' def __init__( self , A ) -> None: _SCREAMING_SNAKE_CASE = size _SCREAMING_SNAKE_CASE = [0] * size _SCREAMING_SNAKE_CASE = [0] * size @staticmethod def snake_case_( A ) -> int: return index | (index + 1) @staticmethod def snake_case_( A ) -> int: return (index & (index + 1)) - 1 def snake_case_( self , A , A ) -> None: _SCREAMING_SNAKE_CASE = value while index < self.size: _SCREAMING_SNAKE_CASE = self.get_prev(A ) + 1 if current_left_border == index: _SCREAMING_SNAKE_CASE = value else: _SCREAMING_SNAKE_CASE = max(A , A , A ) _SCREAMING_SNAKE_CASE = self.get_next(A ) def snake_case_( self , A , A ) -> int: right -= 1 # Because of right is exclusive _SCREAMING_SNAKE_CASE = 0 while left <= right: _SCREAMING_SNAKE_CASE = self.get_prev(A ) if left <= current_left: _SCREAMING_SNAKE_CASE = max(A , self.tree[right] ) _SCREAMING_SNAKE_CASE = current_left else: _SCREAMING_SNAKE_CASE = max(A , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" , __lowerCamelCase ).groups()[0] class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=None , A=None ) -> int: _SCREAMING_SNAKE_CASE = file_names _SCREAMING_SNAKE_CASE = image_transform _SCREAMING_SNAKE_CASE = label_to_id def __len__( self ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.file_names[idx] _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) _SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ) if self.image_transform is not None: _SCREAMING_SNAKE_CASE = self.image_transform(A ) _SCREAMING_SNAKE_CASE = extract_label(A ) if self.label_to_id is not None: _SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) ->str: # Initialize accelerator if args.with_tracking: _SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = config["""image_size"""] if not isinstance(__lowerCamelCase , (list, tuple) ): _SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , """isdigit""" ): if args.checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _SCREAMING_SNAKE_CASE = int(args.checkpointing_steps ) else: raise ValueError( F'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _SCREAMING_SNAKE_CASE = os.path.split(__lowerCamelCase )[-1].split(""".""" )[0] accelerator.init_trackers(__lowerCamelCase , __lowerCamelCase ) # Grab all the image filenames _SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , __lowerCamelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences _SCREAMING_SNAKE_CASE = [extract_label(__lowerCamelCase ) for fname in file_names] _SCREAMING_SNAKE_CASE = list(set(__lowerCamelCase ) ) id_to_label.sort() _SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(__lowerCamelCase )} # Set the seed before splitting the data. np.random.seed(__lowerCamelCase ) torch.manual_seed(__lowerCamelCase ) torch.cuda.manual_seed_all(__lowerCamelCase ) # Split our filenames between train and validation _SCREAMING_SNAKE_CASE = np.random.permutation(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = int(0.8 * len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = random_perm[:cut] _SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop _SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(__lowerCamelCase , scale=(0.5, 1.0) ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # For evaluation, we use a deterministic Resize _SCREAMING_SNAKE_CASE = Compose([Resize(__lowerCamelCase ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = create_model("""resnet50d""" , pretrained=__lowerCamelCase , num_classes=len(__lowerCamelCase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): _SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=__lowerCamelCase , max_lr=__lowerCamelCase , epochs=__lowerCamelCase , steps_per_epoch=len(__lowerCamelCase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # We need to keep track of how many total steps we have iterated over _SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly _SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _SCREAMING_SNAKE_CASE = os.path.splitext(__lowerCamelCase )[0] if "epoch" in training_difference: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""epoch_""" , """""" ) ) + 1 _SCREAMING_SNAKE_CASE = None else: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""step_""" , """""" ) ) _SCREAMING_SNAKE_CASE = resume_step // len(__lowerCamelCase ) resume_step -= starting_epoch * len(__lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase , __lowerCamelCase ): model.train() if args.with_tracking: _SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(__lowerCamelCase , __lowerCamelCase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(__lowerCamelCase , batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowerCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = F'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) _SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 100 * eval_metric, """train_loss""": total_loss.item() / len(__lowerCamelCase ), """epoch""": epoch, } , step=__lowerCamelCase , ) if checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = F'epoch_{epoch}' if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) if args.with_tracking: accelerator.end_training() def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" , required=__lowerCamelCase , help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , ) parser.add_argument( """--output_dir""" , type=__lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=__lowerCamelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
1
'''simple docstring''' import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotSmallConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ = """platform""" import jax import jax.numpy as jnp from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, shift_tokens_right, ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : int=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : Dict=None , ) ->Union[str, Any]: if attention_mask is None: _SCREAMING_SNAKE_CASE = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: _SCREAMING_SNAKE_CASE = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: _SCREAMING_SNAKE_CASE = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: _SCREAMING_SNAKE_CASE = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: _SCREAMING_SNAKE_CASE = np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class a_ : '''simple docstring''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=16 , A=2 , A=4 , A=4 , A="gelu" , A=0.1 , A=0.1 , A=32 , A=2 , A=1 , A=0 , A=0.02 , ) -> int: _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_act _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 _SCREAMING_SNAKE_CASE = initializer_range def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) _SCREAMING_SNAKE_CASE = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) _SCREAMING_SNAKE_CASE = shift_tokens_right(A , 1 , 2 ) _SCREAMING_SNAKE_CASE = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=A , ) _SCREAMING_SNAKE_CASE = prepare_blenderbot_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() return config, inputs_dict def snake_case_( self , A , A , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = 20 _SCREAMING_SNAKE_CASE = model_class_name(A ) _SCREAMING_SNAKE_CASE = model.encode(inputs_dict["""input_ids"""] ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , A , A ) _SCREAMING_SNAKE_CASE = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="""i4""" ) _SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , A , decoder_attention_mask=A , past_key_values=A , decoder_position_ids=A , ) _SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) _SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , A , decoder_attention_mask=A , past_key_values=outputs_cache.past_key_values , decoder_position_ids=A , ) _SCREAMING_SNAKE_CASE = model.decode(A , A ) _SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = 20 _SCREAMING_SNAKE_CASE = model_class_name(A ) _SCREAMING_SNAKE_CASE = model.encode(inputs_dict["""input_ids"""] ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( inputs_dict["""decoder_input_ids"""], inputs_dict["""decoder_attention_mask"""], ) _SCREAMING_SNAKE_CASE = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) _SCREAMING_SNAKE_CASE = model.init_cache(decoder_input_ids.shape[0] , A , A ) _SCREAMING_SNAKE_CASE = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) _SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, :-1] , A , decoder_attention_mask=A , past_key_values=A , decoder_position_ids=A , ) _SCREAMING_SNAKE_CASE = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="""i4""" ) _SCREAMING_SNAKE_CASE = model.decode( decoder_input_ids[:, -1:] , A , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=A , decoder_position_ids=A , ) _SCREAMING_SNAKE_CASE = model.decode(A , A , decoder_attention_mask=A ) _SCREAMING_SNAKE_CASE = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) @require_flax class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = 99 def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) _SCREAMING_SNAKE_CASE = input_ids.shape[0] _SCREAMING_SNAKE_CASE = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_config_and_data() _SCREAMING_SNAKE_CASE = FlaxBlenderbotSmallForConditionalGeneration(A ) _SCREAMING_SNAKE_CASE = lm_model(input_ids=A ) _SCREAMING_SNAKE_CASE = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs["""logits"""].shape , A ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = BlenderbotSmallConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) _SCREAMING_SNAKE_CASE = FlaxBlenderbotSmallForConditionalGeneration(A ) _SCREAMING_SNAKE_CASE = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) _SCREAMING_SNAKE_CASE = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) _SCREAMING_SNAKE_CASE = lm_model(input_ids=A , decoder_input_ids=A ) _SCREAMING_SNAKE_CASE = (*summary.shape, config.vocab_size) self.assertEqual(outputs["""logits"""].shape , A ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) _SCREAMING_SNAKE_CASE = shift_tokens_right(A , 1 , 2 ) _SCREAMING_SNAKE_CASE = np.equal(A , 1 ).astype(np.floataa ).sum() _SCREAMING_SNAKE_CASE = np.equal(A , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(A , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class a_ ( snake_case_ , unittest.TestCase , snake_case_ ): '''simple docstring''' UpperCamelCase = True UpperCamelCase = ( ( FlaxBlenderbotSmallModel, FlaxBlenderbotSmallForConditionalGeneration, ) if is_flax_available() else () ) UpperCamelCase = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else () def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = FlaxBlenderbotSmallModelTester(self ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(A , A , A ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(A , A , A ) def snake_case_( self ) -> List[str]: _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 encode_jitted(A , A=None , **A ): return model.encode(input_ids=A , attention_mask=A ) with self.subTest("""JIT Enabled""" ): _SCREAMING_SNAKE_CASE = encode_jitted(**A ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): _SCREAMING_SNAKE_CASE = encode_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 snake_case_( self ) -> List[Any]: _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 = model_class(A ) _SCREAMING_SNAKE_CASE = model.encode(inputs_dict["""input_ids"""] , inputs_dict["""attention_mask"""] ) _SCREAMING_SNAKE_CASE = { """decoder_input_ids""": inputs_dict["""decoder_input_ids"""], """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""], """encoder_outputs""": encoder_outputs, } @jax.jit def decode_jitted(A , A , A ): return model.decode( decoder_input_ids=A , decoder_attention_mask=A , encoder_outputs=A , ) with self.subTest("""JIT Enabled""" ): _SCREAMING_SNAKE_CASE = decode_jitted(**A ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): _SCREAMING_SNAKE_CASE = decode_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 ) @slow def snake_case_( self ) -> str: for model_class_name in self.all_model_classes: _SCREAMING_SNAKE_CASE = model_class_name.from_pretrained("""facebook/blenderbot_small-90M""" ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids _SCREAMING_SNAKE_CASE = np.ones((1, 1) ) * model.config.eos_token_id _SCREAMING_SNAKE_CASE = model(A ) self.assertIsNotNone(A )
58
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = """Usage of script: script_name <size_of_canvas:int>""" lowercase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase ( __lowerCamelCase : int ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCamelCase )] for j in range(__lowerCamelCase )] return canvas def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->None: for i, row in enumerate(__lowerCamelCase ): for j, _ in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCamelCase ): for c, pt in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = __judge_point( __lowerCamelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) _SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. _SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def lowerCamelCase ( __lowerCamelCase : bool , __lowerCamelCase : list[list[bool]] ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. _SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: _SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: _SCREAMING_SNAKE_CASE = True elif alive > 3: _SCREAMING_SNAKE_CASE = False else: if alive == 3: _SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ , lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(["""w""", """k"""]) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
58
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """unc-nlp/lxmert-base-uncased""": """https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''lxmert''' UpperCamelCase = {} def __init__( self , A=3_0522 , A=768 , A=12 , A=9500 , A=1600 , A=400 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=9 , A=5 , A=5 , A=2048 , A=4 , A=6.67 , A=True , A=True , A=True , A=True , A=True , A=True , A=True , **A , ) -> int: _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = num_qa_labels _SCREAMING_SNAKE_CASE = num_object_labels _SCREAMING_SNAKE_CASE = num_attr_labels _SCREAMING_SNAKE_CASE = l_layers _SCREAMING_SNAKE_CASE = x_layers _SCREAMING_SNAKE_CASE = r_layers _SCREAMING_SNAKE_CASE = visual_feat_dim _SCREAMING_SNAKE_CASE = visual_pos_dim _SCREAMING_SNAKE_CASE = visual_loss_normalizer _SCREAMING_SNAKE_CASE = task_matched _SCREAMING_SNAKE_CASE = task_mask_lm _SCREAMING_SNAKE_CASE = task_obj_predict _SCREAMING_SNAKE_CASE = task_qa _SCREAMING_SNAKE_CASE = visual_obj_loss _SCREAMING_SNAKE_CASE = visual_attr_loss _SCREAMING_SNAKE_CASE = visual_feat_loss _SCREAMING_SNAKE_CASE = {"""vision""": r_layers, """cross_encoder""": x_layers, """language""": l_layers} super().__init__(**A )
58
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase_ = HUGGINGFACE_HUB_CACHE lowercase_ = """config.json""" lowercase_ = """diffusion_pytorch_model.bin""" lowercase_ = """diffusion_flax_model.msgpack""" lowercase_ = """model.onnx""" lowercase_ = """diffusion_pytorch_model.safetensors""" lowercase_ = """weights.pb""" lowercase_ = """https://huggingface.co""" lowercase_ = default_cache_path lowercase_ = """diffusers_modules""" lowercase_ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowercase_ = ["""fp16""", """non-ema"""] lowercase_ = """.self_attn"""
58
1
'''simple docstring''' import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class a_ ( unittest.TestCase ): '''simple docstring''' @property def snake_case_( self ) -> Optional[int]: return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = ort.SessionOptions() _SCREAMING_SNAKE_CASE = False return options def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _SCREAMING_SNAKE_CASE = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=A ) _SCREAMING_SNAKE_CASE = """A red cat sitting on a park bench""" _SCREAMING_SNAKE_CASE = np.random.RandomState(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=A , image=A , mask_image=A , guidance_scale=7.5 , num_inference_steps=10 , generator=A , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images _SCREAMING_SNAKE_CASE = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) _SCREAMING_SNAKE_CASE = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) _SCREAMING_SNAKE_CASE = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=A , safety_checker=A , feature_extractor=A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=A ) _SCREAMING_SNAKE_CASE = """A red cat sitting on a park bench""" _SCREAMING_SNAKE_CASE = np.random.RandomState(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=A , image=A , mask_image=A , guidance_scale=7.5 , num_inference_steps=20 , generator=A , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images _SCREAMING_SNAKE_CASE = images[0, 255:258, 255:258, -1] assert images.shape == (1, 512, 512, 3) _SCREAMING_SNAKE_CASE = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
58
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
1
'''simple docstring''' import argparse import struct import unittest class a_ : '''simple docstring''' def __init__( self , A ) -> None: _SCREAMING_SNAKE_CASE = data # Initialize hash values _SCREAMING_SNAKE_CASE = [ 0X6a09_e667, 0Xbb67_ae85, 0X3c6e_f372, 0Xa54f_f53a, 0X510e_527f, 0X9b05_688c, 0X1f83_d9ab, 0X5be0_cd19, ] # Initialize round constants _SCREAMING_SNAKE_CASE = [ 0X428a_2f98, 0X7137_4491, 0Xb5c0_fbcf, 0Xe9b5_dba5, 0X3956_c25b, 0X59f1_11f1, 0X923f_82a4, 0Xab1c_5ed5, 0Xd807_aa98, 0X1283_5b01, 0X2431_85be, 0X550c_7dc3, 0X72be_5d74, 0X80de_b1fe, 0X9bdc_06a7, 0Xc19b_f174, 0Xe49b_69c1, 0Xefbe_4786, 0X0fc1_9dc6, 0X240c_a1cc, 0X2de9_2c6f, 0X4a74_84aa, 0X5cb0_a9dc, 0X76f9_88da, 0X983e_5152, 0Xa831_c66d, 0Xb003_27c8, 0Xbf59_7fc7, 0Xc6e0_0bf3, 0Xd5a7_9147, 0X06ca_6351, 0X1429_2967, 0X27b7_0a85, 0X2e1b_2138, 0X4d2c_6dfc, 0X5338_0d13, 0X650a_7354, 0X766a_0abb, 0X81c2_c92e, 0X9272_2c85, 0Xa2bf_e8a1, 0Xa81a_664b, 0Xc24b_8b70, 0Xc76c_51a3, 0Xd192_e819, 0Xd699_0624, 0Xf40e_3585, 0X106a_a070, 0X19a4_c116, 0X1e37_6c08, 0X2748_774c, 0X34b0_bcb5, 0X391c_0cb3, 0X4ed8_aa4a, 0X5b9c_ca4f, 0X682e_6ff3, 0X748f_82ee, 0X78a5_636f, 0X84c8_7814, 0X8cc7_0208, 0X90be_fffa, 0Xa450_6ceb, 0Xbef9_a3f7, 0Xc671_78f2, ] _SCREAMING_SNAKE_CASE = self.preprocessing(self.data ) self.final_hash() @staticmethod def snake_case_( A ) -> bytes: _SCREAMING_SNAKE_CASE = b"""\x80""" + (b"""\x00""" * (63 - (len(A ) + 8) % 64)) _SCREAMING_SNAKE_CASE = struct.pack(""">Q""" , (len(A ) * 8) ) return data + padding + big_endian_integer def snake_case_( self ) -> None: # Convert into blocks of 64 bytes _SCREAMING_SNAKE_CASE = [ self.preprocessed_data[x : x + 64] for x in range(0 , len(self.preprocessed_data ) , 64 ) ] for block in self.blocks: # Convert the given block into a list of 4 byte integers _SCREAMING_SNAKE_CASE = list(struct.unpack(""">16L""" , A ) ) # add 48 0-ed integers words += [0] * 48 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.hashes for index in range(0 , 64 ): if index > 15: # modify the zero-ed indexes at the end of the array _SCREAMING_SNAKE_CASE = ( self.ror(words[index - 15] , 7 ) ^ self.ror(words[index - 15] , 18 ) ^ (words[index - 15] >> 3) ) _SCREAMING_SNAKE_CASE = ( self.ror(words[index - 2] , 17 ) ^ self.ror(words[index - 2] , 19 ) ^ (words[index - 2] >> 10) ) _SCREAMING_SNAKE_CASE = ( words[index - 16] + sa + words[index - 7] + sa ) % 0X1_0000_0000 # Compression _SCREAMING_SNAKE_CASE = self.ror(A , 6 ) ^ self.ror(A , 11 ) ^ self.ror(A , 25 ) _SCREAMING_SNAKE_CASE = (e & f) ^ ((~e & 0Xffff_ffff) & g) _SCREAMING_SNAKE_CASE = ( h + sa + ch + self.round_constants[index] + words[index] ) % 0X1_0000_0000 _SCREAMING_SNAKE_CASE = self.ror(A , 2 ) ^ self.ror(A , 13 ) ^ self.ror(A , 22 ) _SCREAMING_SNAKE_CASE = (a & b) ^ (a & c) ^ (b & c) _SCREAMING_SNAKE_CASE = (sa + maj) % 0X1_0000_0000 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( g, f, e, ((d + tempa) % 0X1_0000_0000), c, b, a, ((tempa + tempa) % 0X1_0000_0000), ) _SCREAMING_SNAKE_CASE = [a, b, c, d, e, f, g, h] # Modify final values _SCREAMING_SNAKE_CASE = [ ((element + mutated_hash_values[index]) % 0X1_0000_0000) for index, element in enumerate(self.hashes ) ] _SCREAMING_SNAKE_CASE = """""".join([hex(A )[2:].zfill(8 ) for value in self.hashes] ) def snake_case_( self , A , A ) -> int: return 0Xffff_ffff & (value << (32 - rotations)) | (value >> rotations) class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> None: import hashlib _SCREAMING_SNAKE_CASE = bytes("""Test String""" , """utf-8""" ) self.assertEqual(SHAaaa(A ).hash , hashlib.shaaaa(A ).hexdigest() ) def lowerCamelCase ( ) ->None: import doctest doctest.testmod() _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( """-s""" , """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument( """-f""" , """--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = args.input_string # hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() else: _SCREAMING_SNAKE_CASE = bytes(__lowerCamelCase , """utf-8""" ) print(SHAaaa(__lowerCamelCase ).hash ) if __name__ == "__main__": main()
58
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
1
'''simple docstring''' import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = tempfile.mkdtemp() _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 , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) _SCREAMING_SNAKE_CASE = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], } _SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , A ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(A , A ) def snake_case_( self , **A ) -> Union[str, Any]: return BertTokenizer.from_pretrained(self.tmpdirname , **A ) def snake_case_( self , **A ) -> Optional[int]: return BertTokenizerFast.from_pretrained(self.tmpdirname , **A ) def snake_case_( self , **A ) -> Optional[Any]: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **A ) def snake_case_( self ) -> Tuple: shutil.rmtree(self.tmpdirname ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(A , 0 , -1 ) ) for x in image_inputs] return image_inputs def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) processor_slow.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=A ) _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) processor_fast.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , A ) self.assertIsInstance(processor_fast.tokenizer , A ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , A ) self.assertIsInstance(processor_fast.image_processor , A ) def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=A , padding_value=1.0 ) _SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , A ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) _SCREAMING_SNAKE_CASE = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE = image_processor(A , return_tensors="""np""" ) _SCREAMING_SNAKE_CASE = processor(images=A , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) _SCREAMING_SNAKE_CASE = """lower newer""" _SCREAMING_SNAKE_CASE = processor(text=A ) _SCREAMING_SNAKE_CASE = tokenizer(A , padding="""max_length""" , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) _SCREAMING_SNAKE_CASE = """lower newer""" _SCREAMING_SNAKE_CASE = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE = processor(text=A , images=A ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(A ): processor() def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) _SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _SCREAMING_SNAKE_CASE = processor.batch_decode(A ) _SCREAMING_SNAKE_CASE = tokenizer.batch_decode(A ) self.assertListEqual(A , A ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.get_image_processor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=A , image_processor=A ) _SCREAMING_SNAKE_CASE = """lower newer""" _SCREAMING_SNAKE_CASE = self.prepare_image_inputs() _SCREAMING_SNAKE_CASE = processor(text=A , images=A ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
58
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowercase_ = logging.getLogger(__name__) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) lowercase_ = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, """rb""") as fp: lowercase_ = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowercase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowercase_ = [0] * args.vocab_size for k, v in counter.items(): lowercase_ = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
58
1
'''simple docstring''' import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse("""9.1.0"""): lowercase_ = { """linear""": PIL.Image.Resampling.BILINEAR, """bilinear""": PIL.Image.Resampling.BILINEAR, """bicubic""": PIL.Image.Resampling.BICUBIC, """lanczos""": PIL.Image.Resampling.LANCZOS, """nearest""": PIL.Image.Resampling.NEAREST, } else: lowercase_ = { """linear""": PIL.Image.LINEAR, """bilinear""": PIL.Image.BILINEAR, """bicubic""": PIL.Image.BICUBIC, """lanczos""": PIL.Image.LANCZOS, """nearest""": PIL.Image.NEAREST, } def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Dict: _SCREAMING_SNAKE_CASE = (images / 2 + 0.5).clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() _SCREAMING_SNAKE_CASE = numpy_to_pil(__lowerCamelCase ) return images def lowerCamelCase ( __lowerCamelCase : Any ) ->Dict: if images.ndim == 3: _SCREAMING_SNAKE_CASE = images[None, ...] _SCREAMING_SNAKE_CASE = (images * 255).round().astype("""uint8""" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images _SCREAMING_SNAKE_CASE = [Image.fromarray(image.squeeze() , mode="""L""" ) for image in images] else: _SCREAMING_SNAKE_CASE = [Image.fromarray(__lowerCamelCase ) for image in images] return pil_images
58
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
58
1
'''simple docstring''' import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple ) ->Optional[int]: # Initialise PyTorch model _SCREAMING_SNAKE_CASE = MobileBertConfig.from_json_file(__lowerCamelCase ) print(F'Building PyTorch model from configuration: {config}' ) _SCREAMING_SNAKE_CASE = MobileBertForPreTraining(__lowerCamelCase ) # Load weights from tf checkpoint _SCREAMING_SNAKE_CASE = load_tf_weights_in_mobilebert(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , __lowerCamelCase ) if __name__ == "__main__": lowercase_ = 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( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowercase_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
58
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(A , nn.Convad ) or isinstance(A , nn.BatchNormad ) if has_not_submodules: self.traced.append(A ) def __call__( self , A ) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(A ) [x.remove() for x in self.handles] return self @property def snake_case_( self ) -> str: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 0 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def __call__( self , A ) -> List[str]: _SCREAMING_SNAKE_CASE = Tracker(self.dest )(A ).parametrized _SCREAMING_SNAKE_CASE = Tracker(self.src )(A ).parametrized _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.src_skip , A ) ) _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.dest_skip , A ) ) if len(A ) != len(A ): raise Exception( f'Numbers of operations are different. Source module has {len(A )} operations while' f' destination module has {len(A )}.' ) for dest_m, src_m in zip(A , A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : ResNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True ) ->int: print(F'Converting {name}...' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ResNetForImageClassification(__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) assert torch.allclose(from_model(__lowerCamelCase ) , our_model(__lowerCamelCase ).logits ), "The model logits don't match the original one." _SCREAMING_SNAKE_CASE = F'resnet{"-".join(name.split("resnet" ) )}' print(__lowerCamelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=__lowerCamelCase , ) # we can use the convnext one _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=__lowerCamelCase , ) print(F'Pushed {checkpoint_name}' ) def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ) ->Any: _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = (1, num_labels) _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(__lowerCamelCase , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { """configuration_clipseg""": [ """CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPSegConfig""", """CLIPSegTextConfig""", """CLIPSegVisionConfig""", ], """processing_clipseg""": ["""CLIPSegProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPSegModel""", """CLIPSegPreTrainedModel""", """CLIPSegTextModel""", """CLIPSegVisionModel""", """CLIPSegForImageSegmentation""", ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[int]: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += [key] setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator def lowerCamelCase ( *__lowerCamelCase : List[str] ) ->Dict: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += keys setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator class a_ ( snake_case_ ): '''simple docstring''' def __new__( cls , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = super().__new__(cls , A , A , A ) if not hasattr(A , """key_handler""" ): setattr(A , """key_handler""" , {} ) setattr(A , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE = getattr(A , """handle_key""" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def snake_case_( cls ) -> str: _SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE = ord(A ) _SCREAMING_SNAKE_CASE = cls.key_handler.get(A ) if handler: _SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def lowerCamelCase ( cls : Any ) ->Dict: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
58
1
'''simple docstring''' import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class a_ : '''simple docstring''' def __init__( self , A , A=13 , A=30 , A=2 , A=3 , A=True , A=True , A=32 , A=5 , A=4 , A=37 , A="gelu" , A=0.1 , A=0.1 , A=10 , A=0.02 , A=3 , A=None , A=2 , ) -> Optional[int]: _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = use_labels _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 = type_sequence_label_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = scope _SCREAMING_SNAKE_CASE = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) _SCREAMING_SNAKE_CASE = (image_size // patch_size) ** 2 _SCREAMING_SNAKE_CASE = num_patches + 2 def snake_case_( self ) -> Tuple: _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.type_sequence_label_size ) _SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def snake_case_( self ) -> str: return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=A , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def snake_case_( self , A , A , A ) -> Dict: _SCREAMING_SNAKE_CASE = DeiTModel(config=A ) model.to(A ) model.eval() _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 , A , A , A ) -> Tuple: _SCREAMING_SNAKE_CASE = DeiTForMaskedImageModeling(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = DeiTForMaskedImageModeling(A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def snake_case_( self , A , A , A ) -> Any: _SCREAMING_SNAKE_CASE = self.type_sequence_label_size _SCREAMING_SNAKE_CASE = DeiTForImageClassification(A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = DeiTForImageClassification(A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE = model(A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def snake_case_( self ) -> Optional[int]: _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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) UpperCamelCase = ( { '''feature-extraction''': DeiTModel, '''image-classification''': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = DeiTModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A , has_text_modality=A , hidden_size=37 ) def snake_case_( self ) -> str: self.config_tester.run_common_tests() @unittest.skip(reason="""DeiT does not use inputs_embeds""" ) def snake_case_( self ) -> List[Any]: pass def snake_case_( self ) -> Union[str, Any]: _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 ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A , nn.Linear ) ) def snake_case_( self ) -> List[str]: _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: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) def snake_case_( self , A , A , A=False ) -> Dict: _SCREAMING_SNAKE_CASE = super()._prepare_for_class(A , A , return_labels=A ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def snake_case_( self ) -> Any: 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: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(A ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): 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() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = True for model_class in self.all_model_classes: if model_class in get_values(A ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue _SCREAMING_SNAKE_CASE = model_class(A ) model.gradient_checkpointing_enable() 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() def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE = [ {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float}, {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long}, {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(A ), *get_values(A ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=f'Testing {model_class} with {problem_type["title"]}' ): _SCREAMING_SNAKE_CASE = problem_type["""title"""] _SCREAMING_SNAKE_CASE = problem_type["""num_labels"""] _SCREAMING_SNAKE_CASE = model_class(A ) model.to(A ) model.train() _SCREAMING_SNAKE_CASE = self._prepare_for_class(A , A , return_labels=A ) if problem_type["num_labels"] > 1: _SCREAMING_SNAKE_CASE = inputs["""labels"""].unsqueeze(1 ).repeat(1 , problem_type["""num_labels"""] ) _SCREAMING_SNAKE_CASE = inputs["""labels"""].to(problem_type["""dtype"""] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=A ) as warning_list: _SCREAMING_SNAKE_CASE = model(**A ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( f'Something is going wrong in the regression problem: intercepted {w.message}' ) loss.backward() @slow def snake_case_( self ) -> Optional[int]: for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = DeiTModel.from_pretrained(A ) self.assertIsNotNone(A ) def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class a_ ( unittest.TestCase ): '''simple docstring''' @cached_property def snake_case_( self ) -> List[str]: return ( DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" ) if is_vision_available() else None ) @slow def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = DeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-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, 1000) ) self.assertEqual(outputs.logits.shape , A ) _SCREAMING_SNAKE_CASE = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = DeiTModel.from_pretrained( """facebook/deit-base-distilled-patch16-224""" , torch_dtype=torch.floataa , device_map="""auto""" ) _SCREAMING_SNAKE_CASE = self.default_image_processor _SCREAMING_SNAKE_CASE = prepare_img() _SCREAMING_SNAKE_CASE = image_processor(images=A , return_tensors="""pt""" ) _SCREAMING_SNAKE_CASE = inputs.pixel_values.to(A ) # forward pass to make sure inference works in fp16 with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(A )
58
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": operator.gt, } def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ) ->Tuple: if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) ->None: _SCREAMING_SNAKE_CASE = F'\n{hint}' if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = requirement, None, None else: _SCREAMING_SNAKE_CASE = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F' got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE = {} for w in want_range: _SCREAMING_SNAKE_CASE = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F' but got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->str: _SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
58
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowerCamelCase ( __lowerCamelCase : str ) ->List[str]: _SCREAMING_SNAKE_CASE = SwinvaConfig() _SCREAMING_SNAKE_CASE = swinva_name.split("""_""" ) _SCREAMING_SNAKE_CASE = name_split[1] if "to" in name_split[3]: _SCREAMING_SNAKE_CASE = int(name_split[3][-3:] ) else: _SCREAMING_SNAKE_CASE = int(name_split[3] ) if "to" in name_split[2]: _SCREAMING_SNAKE_CASE = int(name_split[2][-2:] ) else: _SCREAMING_SNAKE_CASE = int(name_split[2][6:] ) if model_size == "tiny": _SCREAMING_SNAKE_CASE = 96 _SCREAMING_SNAKE_CASE = (2, 2, 6, 2) _SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "small": _SCREAMING_SNAKE_CASE = 96 _SCREAMING_SNAKE_CASE = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE = (3, 6, 12, 24) elif model_size == "base": _SCREAMING_SNAKE_CASE = 128 _SCREAMING_SNAKE_CASE = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE = (4, 8, 16, 32) else: _SCREAMING_SNAKE_CASE = 192 _SCREAMING_SNAKE_CASE = (2, 2, 18, 2) _SCREAMING_SNAKE_CASE = (6, 12, 24, 48) if "to" in swinva_name: _SCREAMING_SNAKE_CASE = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): _SCREAMING_SNAKE_CASE = 2_1841 _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = """imagenet-22k-id2label.json""" _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE = idalabel _SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} else: _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = img_size _SCREAMING_SNAKE_CASE = num_classes _SCREAMING_SNAKE_CASE = embed_dim _SCREAMING_SNAKE_CASE = depths _SCREAMING_SNAKE_CASE = num_heads _SCREAMING_SNAKE_CASE = window_size return config def lowerCamelCase ( __lowerCamelCase : int ) ->Union[str, Any]: if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE = name.replace("""patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "patch_embed.norm" in name: _SCREAMING_SNAKE_CASE = name.replace("""patch_embed.norm""" , """embeddings.norm""" ) if "layers" in name: _SCREAMING_SNAKE_CASE = """encoder.""" + name if "attn.proj" in name: _SCREAMING_SNAKE_CASE = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: _SCREAMING_SNAKE_CASE = name.replace("""attn""" , """attention.self""" ) 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 "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 "q_bias" in name: _SCREAMING_SNAKE_CASE = name.replace("""q_bias""" , """query.bias""" ) if "k_bias" in name: _SCREAMING_SNAKE_CASE = name.replace("""k_bias""" , """key.bias""" ) if "v_bias" in name: _SCREAMING_SNAKE_CASE = name.replace("""v_bias""" , """value.bias""" ) if "cpb_mlp" in name: _SCREAMING_SNAKE_CASE = name.replace("""cpb_mlp""" , """continuous_position_bias_mlp""" ) if name == "norm.weight": _SCREAMING_SNAKE_CASE = """layernorm.weight""" if name == "norm.bias": _SCREAMING_SNAKE_CASE = """layernorm.bias""" if "head" in name: _SCREAMING_SNAKE_CASE = name.replace("""head""" , """classifier""" ) else: _SCREAMING_SNAKE_CASE = """swinv2.""" + name return name def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ) ->Optional[Any]: for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE = orig_state_dict.pop(__lowerCamelCase ) if "mask" in key: continue elif "qkv" in key: _SCREAMING_SNAKE_CASE = key.split(""".""" ) _SCREAMING_SNAKE_CASE = int(key_split[1] ) _SCREAMING_SNAKE_CASE = int(key_split[3] ) _SCREAMING_SNAKE_CASE = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _SCREAMING_SNAKE_CASE = val[:dim, :] _SCREAMING_SNAKE_CASE = val[dim : dim * 2, :] _SCREAMING_SNAKE_CASE = val[-dim:, :] else: _SCREAMING_SNAKE_CASE = val[:dim] _SCREAMING_SNAKE_CASE = val[ dim : dim * 2 ] _SCREAMING_SNAKE_CASE = val[-dim:] else: _SCREAMING_SNAKE_CASE = val return orig_state_dict def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ) ->Tuple: _SCREAMING_SNAKE_CASE = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ) timm_model.eval() _SCREAMING_SNAKE_CASE = get_swinva_config(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = SwinvaForImageClassification(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = convert_state_dict(timm_model.state_dict() , __lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""microsoft/{}""".format(swinva_name.replace("""_""" , """-""" ) ) ) _SCREAMING_SNAKE_CASE = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ) _SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ) _SCREAMING_SNAKE_CASE = timm_model(inputs["""pixel_values"""] ) _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ).logits assert torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) print(F'Saving model {swinva_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCamelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__lowerCamelCase ) model.push_to_hub( repo_path_or_name=Path(__lowerCamelCase , __lowerCamelCase ) , organization="""nandwalritik""" , commit_message="""Add model""" , ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--swinv2_name""", default="""swinv2_tiny_patch4_window8_256""", type=str, help="""Name of the Swinv2 timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) lowercase_ = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
58
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _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]: _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_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(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 lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , 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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , 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 ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = { """task_specific_params""": { """summarization""": {"""length_penalty""": 1.0, """max_length""": 128, """min_length""": 12, """num_beams""": 4}, """summarization_cnn""": {"""length_penalty""": 2.0, """max_length""": 142, """min_length""": 56, """num_beams""": 4}, """summarization_xsum""": {"""length_penalty""": 1.0, """max_length""": 62, """min_length""": 11, """num_beams""": 6}, } } _SCREAMING_SNAKE_CASE = { """task_specific_params.summarization.length_penalty""": 1.0, """task_specific_params.summarization.max_length""": 128, """task_specific_params.summarization.min_length""": 12, """task_specific_params.summarization.num_beams""": 4, """task_specific_params.summarization_cnn.length_penalty""": 2.0, """task_specific_params.summarization_cnn.max_length""": 142, """task_specific_params.summarization_cnn.min_length""": 56, """task_specific_params.summarization_cnn.num_beams""": 4, """task_specific_params.summarization_xsum.length_penalty""": 1.0, """task_specific_params.summarization_xsum.max_length""": 62, """task_specific_params.summarization_xsum.min_length""": 11, """task_specific_params.summarization_xsum.num_beams""": 6, } self.assertEqual(flatten_dict(A ) , A ) def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(A ) , x.transpose() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(A , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(transpose(A ) , transpose(A ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(transpose(A , axes=(1, 2, 0) ) , transpose(A , axes=(1, 2, 0) ).numpy() ) ) @require_tf def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(transpose(A ) , transpose(A ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(transpose(A , axes=(1, 2, 0) ) , transpose(A , axes=(1, 2, 0) ).numpy() ) ) @require_flax def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(transpose(A ) , np.asarray(transpose(A ) ) ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(transpose(A , axes=(1, 2, 0) ) , np.asarray(transpose(A , axes=(1, 2, 0) ) ) ) ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(A , (4, 3) ) , np.reshape(A , (4, 3) ) ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(A , (12, 5) ) , np.reshape(A , (12, 5) ) ) ) @require_torch def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(reshape(A , (4, 3) ) , reshape(A , (4, 3) ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(reshape(A , (12, 5) ) , reshape(A , (12, 5) ).numpy() ) ) @require_tf def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(reshape(A , (4, 3) ) , reshape(A , (4, 3) ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(reshape(A , (12, 5) ) , reshape(A , (12, 5) ).numpy() ) ) @require_flax def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(reshape(A , (4, 3) ) , np.asarray(reshape(A , (4, 3) ) ) ) ) _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(reshape(A , (12, 5) ) , np.asarray(reshape(A , (12, 5) ) ) ) ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(A ) , np.squeeze(A ) ) ) _SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(A , axis=2 ) , np.squeeze(A , axis=2 ) ) ) @require_torch def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(squeeze(A ) , squeeze(A ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(squeeze(A , axis=2 ) , squeeze(A , axis=2 ).numpy() ) ) @require_tf def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(squeeze(A ) , squeeze(A ).numpy() ) ) _SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(squeeze(A , axis=2 ) , squeeze(A , axis=2 ).numpy() ) ) @require_flax def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(squeeze(A ) , np.asarray(squeeze(A ) ) ) ) _SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(squeeze(A , axis=2 ) , np.asarray(squeeze(A , axis=2 ) ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(A , axis=1 ) , np.expand_dims(A , axis=1 ) ) ) @require_torch def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = torch.tensor(A ) self.assertTrue(np.allclose(expand_dims(A , axis=1 ) , expand_dims(A , axis=1 ).numpy() ) ) @require_tf def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = tf.constant(A ) self.assertTrue(np.allclose(expand_dims(A , axis=1 ) , expand_dims(A , axis=1 ).numpy() ) ) @require_flax def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) _SCREAMING_SNAKE_CASE = jnp.array(A ) self.assertTrue(np.allclose(expand_dims(A , axis=1 ) , np.asarray(expand_dims(A , axis=1 ) ) ) )
58
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: 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(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
1
'''simple docstring''' import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VivitImageProcessor class a_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , A , A=7 , A=3 , A=10 , A=18 , A=30 , A=400 , A=True , A=None , A=True , A=[0.5, 0.5, 0.5] , A=[0.5, 0.5, 0.5] , A=None , ) -> List[Any]: _SCREAMING_SNAKE_CASE = size if size is not None else {"""shortest_edge""": 18} _SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {"""height""": 18, """width""": 18} _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = num_frames _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = min_resolution _SCREAMING_SNAKE_CASE = max_resolution _SCREAMING_SNAKE_CASE = do_resize _SCREAMING_SNAKE_CASE = size _SCREAMING_SNAKE_CASE = do_normalize _SCREAMING_SNAKE_CASE = image_mean _SCREAMING_SNAKE_CASE = image_std _SCREAMING_SNAKE_CASE = crop_size def snake_case_( self ) -> str: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_size": self.crop_size, } @require_torch @require_vision class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = VivitImageProcessor if is_vision_available() else None def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = VivitImageProcessingTester(self ) @property def snake_case_( self ) -> Any: return self.image_processor_tester.prepare_image_processor_dict() def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(A , """image_mean""" ) ) self.assertTrue(hasattr(A , """image_std""" ) ) self.assertTrue(hasattr(A , """do_normalize""" ) ) self.assertTrue(hasattr(A , """do_resize""" ) ) self.assertTrue(hasattr(A , """do_center_crop""" ) ) self.assertTrue(hasattr(A , """size""" ) ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18} ) self.assertEqual(image_processor.crop_size , {"""height""": 18, """width""": 18} ) _SCREAMING_SNAKE_CASE = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42} ) self.assertEqual(image_processor.crop_size , {"""height""": 84, """width""": 84} ) def snake_case_( self ) -> Optional[int]: # Initialize image_processing _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PIL videos _SCREAMING_SNAKE_CASE = prepare_video_inputs(self.image_processor_tester , equal_resolution=A ) for video in video_inputs: self.assertIsInstance(A , A ) self.assertIsInstance(video[0] , Image.Image ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(A , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def snake_case_( self ) -> List[str]: # Initialize image_processing _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _SCREAMING_SNAKE_CASE = prepare_video_inputs(self.image_processor_tester , equal_resolution=A , numpify=A ) for video in video_inputs: self.assertIsInstance(A , A ) self.assertIsInstance(video[0] , np.ndarray ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(A , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) def snake_case_( self ) -> str: # Initialize image_processing _SCREAMING_SNAKE_CASE = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _SCREAMING_SNAKE_CASE = prepare_video_inputs(self.image_processor_tester , equal_resolution=A , torchify=A ) for video in video_inputs: self.assertIsInstance(A , A ) self.assertIsInstance(video[0] , torch.Tensor ) # Test not batched input _SCREAMING_SNAKE_CASE = image_processing(video_inputs[0] , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( 1, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , ) # Test batched _SCREAMING_SNAKE_CASE = image_processing(A , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_videos.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_frames, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["""height"""], self.image_processor_tester.crop_size["""width"""], ) , )
58
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase_ = None lowercase_ = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase_ = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class a_ : '''simple docstring''' UpperCamelCase = True UpperCamelCase = None # Automatically constructed UpperCamelCase = "PIL.Image.Image" UpperCamelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCamelCase = field(default='''Image''' , init=snake_case_ , repr=snake_case_ ) def __call__( self ) -> Tuple: return self.pa_type def snake_case_( self , A ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(A , A ): _SCREAMING_SNAKE_CASE = np.array(A ) if isinstance(A , A ): return {"path": value, "bytes": None} elif isinstance(A , A ): return {"path": None, "bytes": value} elif isinstance(A , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(A ) elif isinstance(A , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(A ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def snake_case_( self , A , A=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(A ): _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) else: _SCREAMING_SNAKE_CASE = path.split("""::""" )[-1] try: _SCREAMING_SNAKE_CASE = string_to_dict(A , config.HUB_DATASETS_URL )["""repo_id"""] _SCREAMING_SNAKE_CASE = token_per_repo_id.get(A ) except ValueError: _SCREAMING_SNAKE_CASE = None with xopen(A , """rb""" , use_auth_token=A ) as f: _SCREAMING_SNAKE_CASE = BytesIO(f.read() ) _SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: _SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case_( self , A ) -> pa.StructArray: if pa.types.is_string(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""bytes""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""path""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(A ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def snake_case_( self , A ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(A ): with xopen(A , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() return bytes_ _SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(A ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def lowerCamelCase ( ) ->List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() _SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->bytes: _SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): _SCREAMING_SNAKE_CASE = image.format else: _SCREAMING_SNAKE_CASE = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->dict: if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : np.ndarray ) ->dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) _SCREAMING_SNAKE_CASE = array.dtype _SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER _SCREAMING_SNAKE_CASE = dtype.kind _SCREAMING_SNAKE_CASE = dtype.itemsize _SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _SCREAMING_SNAKE_CASE = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: _SCREAMING_SNAKE_CASE = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: _SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.dtype(__lowerCamelCase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) _SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) ->List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
58
1
'''simple docstring''' lowercase_ = { """Pillow""": """Pillow<10.0.0""", """accelerate""": """accelerate>=0.20.3""", """av""": """av==9.2.0""", """beautifulsoup4""": """beautifulsoup4""", """black""": """black~=23.1""", """codecarbon""": """codecarbon==1.2.0""", """cookiecutter""": """cookiecutter==1.7.3""", """dataclasses""": """dataclasses""", """datasets""": """datasets!=2.5.0""", """decord""": """decord==0.6.0""", """deepspeed""": """deepspeed>=0.9.3""", """diffusers""": """diffusers""", """dill""": """dill<0.3.5""", """evaluate""": """evaluate>=0.2.0""", """fairscale""": """fairscale>0.3""", """faiss-cpu""": """faiss-cpu""", """fastapi""": """fastapi""", """filelock""": """filelock""", """flax""": """flax>=0.4.1,<=0.7.0""", """ftfy""": """ftfy""", """fugashi""": """fugashi>=1.0""", """GitPython""": """GitPython<3.1.19""", """hf-doc-builder""": """hf-doc-builder>=0.3.0""", """huggingface-hub""": """huggingface-hub>=0.14.1,<1.0""", """importlib_metadata""": """importlib_metadata""", """ipadic""": """ipadic>=1.0.0,<2.0""", """isort""": """isort>=5.5.4""", """jax""": """jax>=0.2.8,!=0.3.2,<=0.4.13""", """jaxlib""": """jaxlib>=0.1.65,<=0.4.13""", """jieba""": """jieba""", """kenlm""": """kenlm""", """keras-nlp""": """keras-nlp>=0.3.1""", """librosa""": """librosa""", """nltk""": """nltk""", """natten""": """natten>=0.14.6""", """numpy""": """numpy>=1.17""", """onnxconverter-common""": """onnxconverter-common""", """onnxruntime-tools""": """onnxruntime-tools>=1.4.2""", """onnxruntime""": """onnxruntime>=1.4.0""", """opencv-python""": """opencv-python""", """optuna""": """optuna""", """optax""": """optax>=0.0.8,<=0.1.4""", """packaging""": """packaging>=20.0""", """parameterized""": """parameterized""", """phonemizer""": """phonemizer""", """protobuf""": """protobuf""", """psutil""": """psutil""", """pyyaml""": """pyyaml>=5.1""", """pydantic""": """pydantic<2""", """pytest""": """pytest>=7.2.0""", """pytest-timeout""": """pytest-timeout""", """pytest-xdist""": """pytest-xdist""", """python""": """python>=3.8.0""", """ray[tune]""": """ray[tune]""", """regex""": """regex!=2019.12.17""", """requests""": """requests""", """rhoknp""": """rhoknp>=1.1.0,<1.3.1""", """rjieba""": """rjieba""", """rouge-score""": """rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1""", """ruff""": """ruff>=0.0.241,<=0.0.259""", """sacrebleu""": """sacrebleu>=1.4.12,<2.0.0""", """sacremoses""": """sacremoses""", """safetensors""": """safetensors>=0.3.1""", """sagemaker""": """sagemaker>=2.31.0""", """scikit-learn""": """scikit-learn""", """sentencepiece""": """sentencepiece>=0.1.91,!=0.1.92""", """sigopt""": """sigopt""", """starlette""": """starlette""", """sudachipy""": """sudachipy>=0.6.6""", """sudachidict_core""": """sudachidict_core>=20220729""", """tensorflow-cpu""": """tensorflow-cpu>=2.6,<2.14""", """tensorflow""": """tensorflow>=2.6,<2.14""", """tensorflow-text""": """tensorflow-text<2.14""", """tf2onnx""": """tf2onnx""", """timeout-decorator""": """timeout-decorator""", """timm""": """timm""", """tokenizers""": """tokenizers>=0.11.1,!=0.11.3,<0.14""", """torch""": """torch>=1.9,!=1.12.0""", """torchaudio""": """torchaudio""", """torchvision""": """torchvision""", """pyctcdecode""": """pyctcdecode>=0.4.0""", """tqdm""": """tqdm>=4.27""", """unidic""": """unidic>=1.0.2""", """unidic_lite""": """unidic_lite>=1.0.7""", """urllib3""": """urllib3<2.0.0""", """uvicorn""": """uvicorn""", }
58
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''data2vec-text''' def __init__( self , A=3_0522 , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=1 , A=0 , A=2 , A="absolute" , A=True , A=None , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = classifier_dropout class a_ ( snake_case_ ): '''simple docstring''' @property def snake_case_( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
58
1
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ) ->Union[str, Any]: for attribute in key.split(""".""" ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: _SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE = value elif weight_type == "bias": _SCREAMING_SNAKE_CASE = value else: _SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowerCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ) ->Any: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = fairseq_model.state_dict() _SCREAMING_SNAKE_CASE = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) _SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): _SCREAMING_SNAKE_CASE = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): _SCREAMING_SNAKE_CASE = True if "*" in mapped_key: _SCREAMING_SNAKE_CASE = name.split(__lowerCamelCase )[0].split(""".""" )[-2] _SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: _SCREAMING_SNAKE_CASE = """weight_v""" elif "weight" in name: _SCREAMING_SNAKE_CASE = """weight""" elif "bias" in name: _SCREAMING_SNAKE_CASE = """bias""" else: _SCREAMING_SNAKE_CASE = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(F'Unused weights: {unused_weights}' ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] _SCREAMING_SNAKE_CASE = name.split(""".""" ) _SCREAMING_SNAKE_CASE = int(items[0] ) _SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Union[str, Any]=True ) ->Optional[int]: if config_path is not None: _SCREAMING_SNAKE_CASE = HubertConfig.from_pretrained(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertConfig() if is_finetuned: if dict_path: _SCREAMING_SNAKE_CASE = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _SCREAMING_SNAKE_CASE = target_dict.pad_index _SCREAMING_SNAKE_CASE = target_dict.bos_index _SCREAMING_SNAKE_CASE = target_dict.eos_index _SCREAMING_SNAKE_CASE = len(target_dict.symbols ) _SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == """layer""" else False _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = HubertForCTC(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertModel(__lowerCamelCase ) if is_finetuned: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _SCREAMING_SNAKE_CASE = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowercase_ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
58
1
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class a_ ( snake_case_ ): '''simple docstring''' def __lt__( self , A ) -> Tuple: return self[-1] < other[-1] def __eq__( self , A ) -> List[str]: return self[-1] == other[-1] def lowerCamelCase ( __lowerCamelCase : list ) ->list: _SCREAMING_SNAKE_CASE = [] # sort into stacks for element in collection: _SCREAMING_SNAKE_CASE = Stack([element] ) _SCREAMING_SNAKE_CASE = bisect_left(__lowerCamelCase , __lowerCamelCase ) if i != len(__lowerCamelCase ): stacks[i].append(__lowerCamelCase ) else: stacks.append(__lowerCamelCase ) # use a heap-based merge to merge stack efficiently _SCREAMING_SNAKE_CASE = merge(*(reversed(__lowerCamelCase ) for stack in stacks) ) return collection if __name__ == "__main__": lowercase_ = input("""Enter numbers separated by a comma:\n""").strip() lowercase_ = [int(item) for item in user_input.split(""",""")] print(patience_sort(unsorted))
58
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def lowerCamelCase ( __lowerCamelCase : str ) ->str: if not sentence: return "" _SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , __lowerCamelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
58
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase_ = logging.get_logger(__name__) # TODO: upload to AWS lowercase_ = { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''retribert''' def __init__( self , A=3_0522 , A=768 , A=8 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=True , A=128 , A=0 , **A , ) -> Union[str, Any]: super().__init__(pad_token_id=A , **A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_encoders _SCREAMING_SNAKE_CASE = projection_dim
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
1
'''simple docstring''' from __future__ import annotations import queue class a_ : '''simple docstring''' def __init__( self , A ) -> Any: _SCREAMING_SNAKE_CASE = data _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None def lowerCamelCase ( ) ->TreeNode: print("""\n********Press N to stop entering at any point of time********\n""" ) _SCREAMING_SNAKE_CASE = input("""Enter the value of the root node: """ ).strip().lower() _SCREAMING_SNAKE_CASE = queue.Queue() _SCREAMING_SNAKE_CASE = TreeNode(int(__lowerCamelCase ) ) q.put(__lowerCamelCase ) while not q.empty(): _SCREAMING_SNAKE_CASE = q.get() _SCREAMING_SNAKE_CASE = F'Enter the left node of {node_found.data}: ' _SCREAMING_SNAKE_CASE = input(__lowerCamelCase ).strip().lower() or """n""" if check == "n": return tree_node _SCREAMING_SNAKE_CASE = TreeNode(int(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = left_node q.put(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = F'Enter the right node of {node_found.data}: ' _SCREAMING_SNAKE_CASE = input(__lowerCamelCase ).strip().lower() or """n""" if check == "n": return tree_node _SCREAMING_SNAKE_CASE = TreeNode(int(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = right_node q.put(__lowerCamelCase ) raise def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return print(node.data , end=""",""" ) pre_order(node.left ) pre_order(node.right ) def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return in_order(node.left ) print(node.data , end=""",""" ) in_order(node.right ) def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=""",""" ) def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return _SCREAMING_SNAKE_CASE = queue.Queue() q.put(__lowerCamelCase ) while not q.empty(): _SCREAMING_SNAKE_CASE = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return _SCREAMING_SNAKE_CASE = queue.Queue() q.put(__lowerCamelCase ) while not q.empty(): _SCREAMING_SNAKE_CASE = [] while not q.empty(): _SCREAMING_SNAKE_CASE = q.get() print(node_dequeued.data , end=""",""" ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = node while n or stack: while n: # start from root node, find its left child print(n.data , end=""",""" ) stack.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = n.left # end of while means current node doesn't have left child _SCREAMING_SNAKE_CASE = stack.pop() # start to traverse its right child _SCREAMING_SNAKE_CASE = n.right def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = node while n or stack: while n: stack.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = n.left _SCREAMING_SNAKE_CASE = stack.pop() print(n.data , end=""",""" ) _SCREAMING_SNAKE_CASE = n.right def lowerCamelCase ( __lowerCamelCase : TreeNode ) ->None: if not isinstance(__lowerCamelCase , __lowerCamelCase ) or not node: return _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = [], [] _SCREAMING_SNAKE_CASE = node stacka.append(__lowerCamelCase ) while stacka: # to find the reversed order of post order, store it in stack2 _SCREAMING_SNAKE_CASE = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(__lowerCamelCase ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=""",""" ) def lowerCamelCase ( __lowerCamelCase : str = "" , __lowerCamelCase : List[Any]=50 , __lowerCamelCase : List[str]="*" ) ->str: if not s: return "\n" + width * char _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = divmod(width - len(__lowerCamelCase ) - 2 , 2 ) return F'{left * char} {s} {(left + extra) * char}' if __name__ == "__main__": import doctest doctest.testmod() print(prompt("""Binary Tree Traversals""")) lowercase_ = build_tree() print(prompt("""Pre Order Traversal""")) pre_order(node) print(prompt() + """\n""") print(prompt("""In Order Traversal""")) in_order(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal""")) post_order(node) print(prompt() + """\n""") print(prompt("""Level Order Traversal""")) level_order(node) print(prompt() + """\n""") print(prompt("""Actual Level Order Traversal""")) level_order_actual(node) print("""*""" * 50 + """\n""") print(prompt("""Pre Order Traversal - Iteration Version""")) pre_order_iter(node) print(prompt() + """\n""") print(prompt("""In Order Traversal - Iteration Version""")) in_order_iter(node) print(prompt() + """\n""") print(prompt("""Post Order Traversal - Iteration Version""")) post_order_iter(node) print(prompt())
58
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any]=8 ) ->Tuple: _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A , A , ) -> Union[str, Any]: super().__init__() self.register_modules( unet=A , scheduler=A , movq=A , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_( self , A , A , A , A , A , A ) -> Union[str, Any]: if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A , device=A , dtype=A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(A ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_( self , A=0 ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A , A ) def snake_case_( self , A=0 ) -> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(A , A , prev_module_hook=A ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_( self ) -> Tuple: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self , A , A , A = 512 , A = 512 , A = 100 , A = 4.0 , A = 1 , A = None , A = None , A = "pil" , A = True , ) -> List[str]: _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A ) self.scheduler.set_timesteps(A , device=A ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(A , A , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A , A , A , self.scheduler , ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE = self.unet( sample=A , timestep=A , encoder_hidden_states=A , added_cond_kwargs=A , return_dict=A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( A , A , A , generator=A , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(A , force_not_quantize=A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
58
1
'''simple docstring''' from .imports import is_tqdm_available if is_tqdm_available(): from tqdm.auto import tqdm as _tqdm from ..state import PartialState def lowerCamelCase ( __lowerCamelCase : bool = True , *__lowerCamelCase : Any , **__lowerCamelCase : Union[str, Any] ) ->Optional[Any]: if not is_tqdm_available(): raise ImportError("""Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.""" ) _SCREAMING_SNAKE_CASE = False if main_process_only: _SCREAMING_SNAKE_CASE = PartialState().local_process_index == 0 return _tqdm(*__lowerCamelCase , **__lowerCamelCase , disable=__lowerCamelCase )
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class a_ ( unittest.TestCase ): '''simple docstring''' @slow def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained("""google/mt5-small""" , return_dict=A ).to(A ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""google/mt5-small""" ) _SCREAMING_SNAKE_CASE = tokenizer("""Hello there""" , return_tensors="""pt""" ).input_ids _SCREAMING_SNAKE_CASE = tokenizer("""Hi I am""" , return_tensors="""pt""" ).input_ids _SCREAMING_SNAKE_CASE = model(input_ids.to(A ) , labels=labels.to(A ) ).loss _SCREAMING_SNAKE_CASE = -(labels.shape[-1] * loss.item()) _SCREAMING_SNAKE_CASE = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
58
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """PoolFormerConfig""" # Base docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = [1, 512, 7, 7] # Image classification docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : float = 0.0 , __lowerCamelCase : bool = False ) ->int: if drop_prob == 0.0 or not training: return input _SCREAMING_SNAKE_CASE = 1 - drop_prob _SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _SCREAMING_SNAKE_CASE = keep_prob + torch.rand(__lowerCamelCase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _SCREAMING_SNAKE_CASE = input.div(__lowerCamelCase ) * random_tensor return output class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A = None ) -> None: super().__init__() _SCREAMING_SNAKE_CASE = drop_prob def snake_case_( self , A ) -> torch.Tensor: return drop_path(A , self.drop_prob , self.training ) def snake_case_( self ) -> str: return "p={}".format(self.drop_prob ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A=None ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = patch_size if isinstance(A , collections.abc.Iterable ) else (patch_size, patch_size) _SCREAMING_SNAKE_CASE = stride if isinstance(A , collections.abc.Iterable ) else (stride, stride) _SCREAMING_SNAKE_CASE = padding if isinstance(A , collections.abc.Iterable ) else (padding, padding) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , kernel_size=A , stride=A , padding=A ) _SCREAMING_SNAKE_CASE = norm_layer(A ) if norm_layer else nn.Identity() def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.projection(A ) _SCREAMING_SNAKE_CASE = self.norm(A ) return embeddings class a_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self , A , **A ) -> Union[str, Any]: super().__init__(1 , A , **A ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.AvgPoolad(A , stride=1 , padding=pool_size // 2 , count_include_pad=A ) def snake_case_( self , A ) -> Union[str, Any]: return self.pool(A ) - hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if isinstance(config.hidden_act , A ): _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: _SCREAMING_SNAKE_CASE = config.hidden_act def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.act_fn(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) return hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = PoolFormerPooling(A ) _SCREAMING_SNAKE_CASE = PoolFormerOutput(A , A , A , A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) # Useful for training neural nets _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() _SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) def snake_case_( self , A ) -> Optional[Any]: if self.use_layer_scale: _SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = () _SCREAMING_SNAKE_CASE = self.output(self.after_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: _SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection _SCREAMING_SNAKE_CASE = pooling_output + hidden_states _SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block _SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(A ) ) ) _SCREAMING_SNAKE_CASE = hidden_states + layer_output _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE = config # stochastic depth decay rule _SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) # Transformer blocks _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(A ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) def snake_case_( self , A , A=False , A=True ) -> List[Any]: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None _SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states _SCREAMING_SNAKE_CASE = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): _SCREAMING_SNAKE_CASE = blk(A ) _SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: _SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = PoolFormerConfig UpperCamelCase = '''poolformer''' UpperCamelCase = '''pixel_values''' UpperCamelCase = True def snake_case_( self , A ) -> int: if isinstance(A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_( self , A , A=False ) -> Dict: if isinstance(A , A ): _SCREAMING_SNAKE_CASE = value lowercase_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> int: super().__init__(A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def snake_case_( self ) -> Any: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A = None , A = None , A = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A , hidden_states=encoder_outputs.hidden_states , ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> Optional[Any]: super().__init__(A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = PoolFormerModel(A ) # Final norm _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.poolformer( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = outputs[0] _SCREAMING_SNAKE_CASE = self.classifier(self.norm(A ).mean([-2, -1] ) ) _SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE = """single_label_classification""" else: _SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE = loss_fct(A , A ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE = CrossEntropyLoss() _SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE = loss_fct(A , A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 def __init__( self , A , A ) -> Optional[Any]: super().__init__() self.register_modules(unet=A , scheduler=A ) @torch.no_grad() def __call__( self , A = 1 , A = 2000 , A = None , A = "pil" , A = True , **A , ) -> Union[ImagePipelineOutput, Tuple]: _SCREAMING_SNAKE_CASE = self.unet.config.sample_size _SCREAMING_SNAKE_CASE = (batch_size, 3, img_size, img_size) _SCREAMING_SNAKE_CASE = self.unet _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A ) * self.scheduler.init_noise_sigma _SCREAMING_SNAKE_CASE = sample.to(self.device ) self.scheduler.set_timesteps(A ) self.scheduler.set_sigmas(A ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): _SCREAMING_SNAKE_CASE = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): _SCREAMING_SNAKE_CASE = self.unet(A , A ).sample _SCREAMING_SNAKE_CASE = self.scheduler.step_correct(A , A , generator=A ).prev_sample # prediction step _SCREAMING_SNAKE_CASE = model(A , A ).sample _SCREAMING_SNAKE_CASE = self.scheduler.step_pred(A , A , A , generator=A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = output.prev_sample, output.prev_sample_mean _SCREAMING_SNAKE_CASE = sample_mean.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (sample,) return ImagePipelineOutput(images=A )
58
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase_ = logging.getLogger(__name__) lowercase_ = """Hello world! cécé herlolip""" lowercase_ = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir=""".""" , finetune_bert=__lowerCamelCase , large=__lowerCamelCase , share_emb=__lowerCamelCase , use_bert_emb=__lowerCamelCase , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , lambda __lowerCamelCase , __lowerCamelCase : storage ) _SCREAMING_SNAKE_CASE = AbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) , __lowerCamelCase ) original.eval() _SCREAMING_SNAKE_CASE = BertAbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass _SCREAMING_SNAKE_CASE = encoder_input_ids _SCREAMING_SNAKE_CASE = decoder_input_ids _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical _SCREAMING_SNAKE_CASE = original(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = original.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = new_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = new_model.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) lowercase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
58
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class a_ ( metaclass=snake_case_ ): '''simple docstring''' UpperCamelCase = ['''torch''', '''torchsde'''] def __init__( self , *A , **A ) -> Union[str, Any]: requires_backends(self , ["""torch""", """torchsde"""] ) @classmethod def snake_case_( cls , *A , **A ) -> int: requires_backends(cls , ["""torch""", """torchsde"""] ) @classmethod def snake_case_( cls , *A , **A ) -> int: requires_backends(cls , ["""torch""", """torchsde"""] )
58
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
1
'''simple docstring''' import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") lowercase_ = get_tests_dir("""fixtures/test_sentencepiece_bpe.model""") lowercase_ = """pt""" if is_torch_available() else """tf""" @require_sentencepiece @require_tokenizers class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = CamembertTokenizer UpperCamelCase = CamembertTokenizerFast UpperCamelCase = True UpperCamelCase = True def snake_case_( self ) -> List[str]: super().setUp() # We have a SentencePiece fixture for testing _SCREAMING_SNAKE_CASE = CamembertTokenizer(A ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case_( self ) -> List[Any]: _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 ) -> str: _SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>NOTUSED""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(vocab_keys[-1] , """<mask>""" ) self.assertEqual(len(A ) , 1004 ) def snake_case_( self ) -> str: self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = CamembertTokenizer(A ) tokenizer.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" _SCREAMING_SNAKE_CASE = tokenizer.encode(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A ) self.assertListEqual(A , A ) _SCREAMING_SNAKE_CASE = tokenizer.encode(A , add_special_tokens=A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A , add_special_tokens=A ) self.assertListEqual(A , A ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) _SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(A ) self.assertListEqual(A , A ) def snake_case_( self ) -> Any: if not self.test_rust_tokenizer: return _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" _SCREAMING_SNAKE_CASE = tokenizer.tokenize(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(A ) self.assertListEqual(A , A ) _SCREAMING_SNAKE_CASE = tokenizer.encode(A , add_special_tokens=A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A , add_special_tokens=A ) self.assertListEqual(A , A ) _SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE = tokenizer.encode(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A ) self.assertListEqual(A , A ) @slow def snake_case_( self ) -> Optional[int]: # fmt: off _SCREAMING_SNAKE_CASE = {"""input_ids""": [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], """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, 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, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. _SCREAMING_SNAKE_CASE = [ """Le transformeur est un modèle d'apprentissage profond introduit en 2017, """ """utilisé principalement dans le domaine du traitement automatique des langues (TAL).""", """À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus """ """pour gérer des données séquentielles, telles que le langage naturel, pour des tâches """ """telles que la traduction et la synthèse de texte.""", ] self.tokenizer_integration_test_util( expected_encoding=A , model_name="""camembert-base""" , revision="""3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf""" , sequences=A , )
58
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" , __lowerCamelCase ).groups()[0] class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=None , A=None ) -> int: _SCREAMING_SNAKE_CASE = file_names _SCREAMING_SNAKE_CASE = image_transform _SCREAMING_SNAKE_CASE = label_to_id def __len__( self ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.file_names[idx] _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) _SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ) if self.image_transform is not None: _SCREAMING_SNAKE_CASE = self.image_transform(A ) _SCREAMING_SNAKE_CASE = extract_label(A ) if self.label_to_id is not None: _SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) ->str: # Initialize accelerator if args.with_tracking: _SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = config["""image_size"""] if not isinstance(__lowerCamelCase , (list, tuple) ): _SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , """isdigit""" ): if args.checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _SCREAMING_SNAKE_CASE = int(args.checkpointing_steps ) else: raise ValueError( F'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _SCREAMING_SNAKE_CASE = os.path.split(__lowerCamelCase )[-1].split(""".""" )[0] accelerator.init_trackers(__lowerCamelCase , __lowerCamelCase ) # Grab all the image filenames _SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , __lowerCamelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences _SCREAMING_SNAKE_CASE = [extract_label(__lowerCamelCase ) for fname in file_names] _SCREAMING_SNAKE_CASE = list(set(__lowerCamelCase ) ) id_to_label.sort() _SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(__lowerCamelCase )} # Set the seed before splitting the data. np.random.seed(__lowerCamelCase ) torch.manual_seed(__lowerCamelCase ) torch.cuda.manual_seed_all(__lowerCamelCase ) # Split our filenames between train and validation _SCREAMING_SNAKE_CASE = np.random.permutation(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = int(0.8 * len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = random_perm[:cut] _SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop _SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(__lowerCamelCase , scale=(0.5, 1.0) ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # For evaluation, we use a deterministic Resize _SCREAMING_SNAKE_CASE = Compose([Resize(__lowerCamelCase ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = create_model("""resnet50d""" , pretrained=__lowerCamelCase , num_classes=len(__lowerCamelCase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): _SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=__lowerCamelCase , max_lr=__lowerCamelCase , epochs=__lowerCamelCase , steps_per_epoch=len(__lowerCamelCase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # We need to keep track of how many total steps we have iterated over _SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly _SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _SCREAMING_SNAKE_CASE = os.path.splitext(__lowerCamelCase )[0] if "epoch" in training_difference: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""epoch_""" , """""" ) ) + 1 _SCREAMING_SNAKE_CASE = None else: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""step_""" , """""" ) ) _SCREAMING_SNAKE_CASE = resume_step // len(__lowerCamelCase ) resume_step -= starting_epoch * len(__lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase , __lowerCamelCase ): model.train() if args.with_tracking: _SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(__lowerCamelCase , __lowerCamelCase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(__lowerCamelCase , batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowerCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = F'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) _SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 100 * eval_metric, """train_loss""": total_loss.item() / len(__lowerCamelCase ), """epoch""": epoch, } , step=__lowerCamelCase , ) if checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = F'epoch_{epoch}' if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) if args.with_tracking: accelerator.end_training() def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" , required=__lowerCamelCase , help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , ) parser.add_argument( """--output_dir""" , type=__lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=__lowerCamelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
1
'''simple docstring''' import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model lowercase_ = """0.12""" # assumed parallelism: 8 if is_torch_available(): import torch def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int]=None ) ->Tuple: if rng is None: _SCREAMING_SNAKE_CASE = random.Random() _SCREAMING_SNAKE_CASE = 1 for dim in shape: total_dims *= dim _SCREAMING_SNAKE_CASE = [] for _ in range(__lowerCamelCase ): values.append(rng.randint(0 , vocab_size - 1 ) ) _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase , dtype=jnp.intaa ).reshape(__lowerCamelCase ) return output def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any]=None ) ->List[Any]: _SCREAMING_SNAKE_CASE = ids_tensor(__lowerCamelCase , vocab_size=2 , rng=__lowerCamelCase ) # make sure that at least one token is attended to for each batch _SCREAMING_SNAKE_CASE = 1 return attn_mask @require_flax class a_ : '''simple docstring''' UpperCamelCase = None UpperCamelCase = () def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = inputs["""input_ids"""].shape[-1] // 2 _SCREAMING_SNAKE_CASE = inputs["""input_ids"""][:max_batch_size, :sequence_length] _SCREAMING_SNAKE_CASE = jnp.ones_like(A ) _SCREAMING_SNAKE_CASE = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens _SCREAMING_SNAKE_CASE = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` _SCREAMING_SNAKE_CASE = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 0 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model_class.__name__[4:] # Skip the "Flax" at the beginning _SCREAMING_SNAKE_CASE = getattr(A , A ) _SCREAMING_SNAKE_CASE = pt_model_class(A ).eval() _SCREAMING_SNAKE_CASE = load_flax_weights_in_pytorch_model(A , flax_model.params ) _SCREAMING_SNAKE_CASE = flax_model.generate(A ).sequences _SCREAMING_SNAKE_CASE = pt_model.generate(torch.tensor(A , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: _SCREAMING_SNAKE_CASE = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 2 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = 2 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 0.8 _SCREAMING_SNAKE_CASE = 10 _SCREAMING_SNAKE_CASE = 0.3 _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = 8 _SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = 8 _SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() _SCREAMING_SNAKE_CASE = max_length _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = 8 _SCREAMING_SNAKE_CASE = 9 for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left _SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A , attention_mask=A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A , attention_mask=A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left _SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A , attention_mask=A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A , attention_mask=A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_input_ids_and_config() # pad attention mask on the left _SCREAMING_SNAKE_CASE = attention_mask.at[(0, 0)].set(0 ) _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = max_length for model_class in self.all_generative_model_classes: _SCREAMING_SNAKE_CASE = model_class(A ) _SCREAMING_SNAKE_CASE = model.generate(A , attention_mask=A ).sequences self.assertEqual(generation_outputs.shape[-1] , A ) _SCREAMING_SNAKE_CASE = jit(model.generate ) _SCREAMING_SNAKE_CASE = jit_generate(A , attention_mask=A ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) _SCREAMING_SNAKE_CASE = FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) _SCREAMING_SNAKE_CASE = """Hello world""" _SCREAMING_SNAKE_CASE = tokenizer(A , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(A , """do_samples""" ): model.generate(A , do_samples=A ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(A , """foo""" ): _SCREAMING_SNAKE_CASE = {"""foo""": """bar"""} model.generate(A , **A )
58
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = """Usage of script: script_name <size_of_canvas:int>""" lowercase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase ( __lowerCamelCase : int ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCamelCase )] for j in range(__lowerCamelCase )] return canvas def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->None: for i, row in enumerate(__lowerCamelCase ): for j, _ in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCamelCase ): for c, pt in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = __judge_point( __lowerCamelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) _SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. _SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def lowerCamelCase ( __lowerCamelCase : bool , __lowerCamelCase : list[list[bool]] ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. _SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: _SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: _SCREAMING_SNAKE_CASE = True elif alive > 3: _SCREAMING_SNAKE_CASE = False else: if alive == 3: _SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ , lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(["""w""", """k"""]) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
58
1
'''simple docstring''' import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowercase_ = 16 lowercase_ = 32 def lowerCamelCase ( __lowerCamelCase : Accelerator , __lowerCamelCase : int = 16 ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""bert-base-cased""" ) _SCREAMING_SNAKE_CASE = load_dataset("""glue""" , """mrpc""" ) def tokenize_function(__lowerCamelCase : int ): # max_length=None => use the model max length (it's actually the default) _SCREAMING_SNAKE_CASE = tokenizer(examples["""sentence1"""] , examples["""sentence2"""] , truncation=__lowerCamelCase , max_length=__lowerCamelCase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): _SCREAMING_SNAKE_CASE = datasets.map( __lowerCamelCase , batched=__lowerCamelCase , remove_columns=["""idx""", """sentence1""", """sentence2"""] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library _SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column("""label""" , """labels""" ) def collate_fn(__lowerCamelCase : Union[str, Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. _SCREAMING_SNAKE_CASE = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": _SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": _SCREAMING_SNAKE_CASE = 8 else: _SCREAMING_SNAKE_CASE = None return tokenizer.pad( __lowerCamelCase , padding="""longest""" , max_length=__lowerCamelCase , pad_to_multiple_of=__lowerCamelCase , return_tensors="""pt""" , ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["""train"""] , shuffle=__lowerCamelCase , collate_fn=__lowerCamelCase , batch_size=__lowerCamelCase , drop_last=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["""validation"""] , shuffle=__lowerCamelCase , collate_fn=__lowerCamelCase , batch_size=__lowerCamelCase , drop_last=(accelerator.mixed_precision == """fp8""") , ) return train_dataloader, eval_dataloader def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : str ) ->str: # Initialize accelerator _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = evaluate.load("""glue""" , """mrpc""" ) # If the batch size is too big we use gradient accumulation _SCREAMING_SNAKE_CASE = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: _SCREAMING_SNAKE_CASE = batch_size // MAX_GPU_BATCH_SIZE _SCREAMING_SNAKE_CASE = MAX_GPU_BATCH_SIZE set_seed(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = get_dataloaders(__lowerCamelCase , __lowerCamelCase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("""bert-base-cased""" , return_dict=__lowerCamelCase ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=__lowerCamelCase ) # Instantiate scheduler _SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=__lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(__lowerCamelCase ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase ): model.train() for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.loss _SCREAMING_SNAKE_CASE = loss / gradient_accumulation_steps accelerator.backward(__lowerCamelCase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""labels"""]) ) metric.add_batch( predictions=__lowerCamelCase , references=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}:' , __lowerCamelCase ) def lowerCamelCase ( ) ->List[str]: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase_ = HUGGINGFACE_HUB_CACHE lowercase_ = """config.json""" lowercase_ = """diffusion_pytorch_model.bin""" lowercase_ = """diffusion_flax_model.msgpack""" lowercase_ = """model.onnx""" lowercase_ = """diffusion_pytorch_model.safetensors""" lowercase_ = """weights.pb""" lowercase_ = """https://huggingface.co""" lowercase_ = default_cache_path lowercase_ = """diffusers_modules""" lowercase_ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowercase_ = ["""fp16""", """non-ema"""] lowercase_ = """.self_attn"""
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) lowercase_ = { """configuration_encodec""": [ """ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP""", """EncodecConfig""", ], """feature_extraction_encodec""": ["""EncodecFeatureExtractor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST""", """EncodecModel""", """EncodecPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_encodec import ( ENCODEC_PRETRAINED_CONFIG_ARCHIVE_MAP, EncodecConfig, ) from .feature_extraction_encodec import EncodecFeatureExtractor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_encodec import ( ENCODEC_PRETRAINED_MODEL_ARCHIVE_LIST, EncodecModel, EncodecPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
1
'''simple docstring''' import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class a_ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ("""foo.json""",)] ) def snake_case_( self , A ) -> Dict: _SCREAMING_SNAKE_CASE = GenerationConfig( do_sample=A , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(A , config_name=A ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained(A , config_name=A ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , A ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , A ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("""gpt2""" ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_model_config(A ) _SCREAMING_SNAKE_CASE = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(A , A ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = GenerationConfig() _SCREAMING_SNAKE_CASE = { """max_new_tokens""": 1024, """foo""": """bar""", } _SCREAMING_SNAKE_CASE = copy.deepcopy(A ) _SCREAMING_SNAKE_CASE = generation_config.update(**A ) # update_kwargs was not modified (no side effects) self.assertEqual(A , A ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(A , {"""foo""": """bar"""} ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = GenerationConfig() _SCREAMING_SNAKE_CASE = """bar""" with tempfile.TemporaryDirectory("""test-generation-config""" ) as tmp_dir: generation_config.save_pretrained(A ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained(A ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , """bar""" ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_model_config(A ) assert not hasattr(A , """foo""" ) # no new kwargs should be initialized if from config def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , A ) self.assertEqual(default_config.num_beams , 1 ) _SCREAMING_SNAKE_CASE = GenerationConfig( do_sample=A , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , A ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(A ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained(A , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , A ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class a_ ( unittest.TestCase ): '''simple docstring''' @classmethod def snake_case_( cls ) -> Optional[int]: _SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(A ) @classmethod def snake_case_( cls ) -> Optional[Any]: try: delete_repo(token=cls._token , repo_id="""test-generation-config""" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="""valid_org/test-generation-config-org""" ) except HTTPError: pass def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = GenerationConfig( do_sample=A , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("""test-generation-config""" , use_auth_token=self._token ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A , getattr(A , A ) ) # Reset repo delete_repo(token=self._token , repo_id="""test-generation-config""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( A , repo_id="""test-generation-config""" , push_to_hub=A , use_auth_token=self._token ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained(f'{USER}/test-generation-config' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A , getattr(A , A ) ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = GenerationConfig( do_sample=A , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("""valid_org/test-generation-config-org""" , use_auth_token=self._token ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained("""valid_org/test-generation-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A , getattr(A , A ) ) # Reset repo delete_repo(token=self._token , repo_id="""valid_org/test-generation-config-org""" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( A , repo_id="""valid_org/test-generation-config-org""" , push_to_hub=A , use_auth_token=self._token ) _SCREAMING_SNAKE_CASE = GenerationConfig.from_pretrained("""valid_org/test-generation-config-org""" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(A , getattr(A , A ) )
58
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
1
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[int]: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += [key] setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator def lowerCamelCase ( *__lowerCamelCase : List[str] ) ->Dict: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += keys setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator class a_ ( snake_case_ ): '''simple docstring''' def __new__( cls , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = super().__new__(cls , A , A , A ) if not hasattr(A , """key_handler""" ): setattr(A , """key_handler""" , {} ) setattr(A , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE = getattr(A , """handle_key""" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def snake_case_( cls ) -> str: _SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE = ord(A ) _SCREAMING_SNAKE_CASE = cls.key_handler.get(A ) if handler: _SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def lowerCamelCase ( cls : Any ) ->Dict: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
58
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowercase_ = logging.getLogger(__name__) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) lowercase_ = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, """rb""") as fp: lowercase_ = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowercase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowercase_ = [0] * args.vocab_size for k, v in counter.items(): lowercase_ = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TapasForMaskedLM""", """TapasForQuestionAnswering""", """TapasForSequenceClassification""", """TapasModel""", """TapasPreTrainedModel""", """load_tf_weights_in_tapas""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFTapasForMaskedLM""", """TFTapasForQuestionAnswering""", """TFTapasForSequenceClassification""", """TFTapasModel""", """TFTapasPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
58
1
'''simple docstring''' lowercase_ = 65_521 def lowerCamelCase ( __lowerCamelCase : str ) ->int: _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = 0 for plain_chr in plain_text: _SCREAMING_SNAKE_CASE = (a + ord(__lowerCamelCase )) % MOD_ADLER _SCREAMING_SNAKE_CASE = (b + a) % MOD_ADLER return (b << 16) | a
58
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(A , nn.Convad ) or isinstance(A , nn.BatchNormad ) if has_not_submodules: self.traced.append(A ) def __call__( self , A ) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(A ) [x.remove() for x in self.handles] return self @property def snake_case_( self ) -> str: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 0 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def __call__( self , A ) -> List[str]: _SCREAMING_SNAKE_CASE = Tracker(self.dest )(A ).parametrized _SCREAMING_SNAKE_CASE = Tracker(self.src )(A ).parametrized _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.src_skip , A ) ) _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.dest_skip , A ) ) if len(A ) != len(A ): raise Exception( f'Numbers of operations are different. Source module has {len(A )} operations while' f' destination module has {len(A )}.' ) for dest_m, src_m in zip(A , A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : ResNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True ) ->int: print(F'Converting {name}...' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ResNetForImageClassification(__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) assert torch.allclose(from_model(__lowerCamelCase ) , our_model(__lowerCamelCase ).logits ), "The model logits don't match the original one." _SCREAMING_SNAKE_CASE = F'resnet{"-".join(name.split("resnet" ) )}' print(__lowerCamelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=__lowerCamelCase , ) # we can use the convnext one _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=__lowerCamelCase , ) print(F'Pushed {checkpoint_name}' ) def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ) ->Any: _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = (1, num_labels) _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(__lowerCamelCase , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
58
1
'''simple docstring''' from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """RegNetConfig""" # Base docstring lowercase_ = """facebook/regnet-y-040""" lowercase_ = [1, 1_088, 7, 7] # Image classification docstring lowercase_ = """facebook/regnet-y-040""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """facebook/regnet-y-040""", # See all regnet models at https://huggingface.co/models?filter=regnet ] class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A = 3 , A = 1 , A = 1 , A = "relu" , **A , ) -> Optional[Any]: super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb _SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) _SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=A , kernel_size=A , strides=A , padding="""VALID""" , groups=A , use_bias=A , name="""convolution""" , ) _SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) _SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.convolution(self.padding(A ) ) _SCREAMING_SNAKE_CASE = self.normalization(A ) _SCREAMING_SNAKE_CASE = self.activation(A ) return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , **A ) -> Optional[int]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = config.num_channels _SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="""embedder""" , ) def snake_case_( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( """Make sure that the channel dimension of the pixel values match with the one set in the configuration.""" ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) _SCREAMING_SNAKE_CASE = tf.transpose(A , perm=(0, 2, 3, 1) ) _SCREAMING_SNAKE_CASE = self.embedder(A ) return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A = 2 , **A ) -> List[str]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=A , kernel_size=1 , strides=A , use_bias=A , name="""convolution""" ) _SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name="""normalization""" ) def snake_case_( self , A , A = False ) -> tf.Tensor: return self.normalization(self.convolution(A ) , training=A ) class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A , **A ) -> str: super().__init__(**A ) _SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A , name="""pooler""" ) _SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=A , kernel_size=1 , activation="""relu""" , name="""attention.0""" ), tf.keras.layers.ConvaD(filters=A , kernel_size=1 , activation="""sigmoid""" , name="""attention.2""" ), ] def snake_case_( self , A ) -> Dict: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] _SCREAMING_SNAKE_CASE = self.pooler(A ) for layer_module in self.attention: _SCREAMING_SNAKE_CASE = layer_module(A ) _SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A , A , A = 1 , **A ) -> int: super().__init__(**A ) _SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 _SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) _SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(A , stride=A , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. _SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(A , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( A , stride=A , groups=A , activation=config.hidden_act , name="""layer.1""" ), TFRegNetConvLayer(A , kernel_size=1 , activation=A , name="""layer.2""" ), ] _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def snake_case_( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: _SCREAMING_SNAKE_CASE = layer_module(A ) _SCREAMING_SNAKE_CASE = self.shortcut(A ) hidden_state += residual _SCREAMING_SNAKE_CASE = self.activation(A ) return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A , A , A = 1 , **A ) -> Tuple: super().__init__(**A ) _SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 _SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) _SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(A , stride=A , name="""shortcut""" ) if should_apply_shortcut else tf.keras.layers.Activation("""linear""" , name="""shortcut""" ) ) _SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(A , kernel_size=1 , activation=config.hidden_act , name="""layer.0""" ), TFRegNetConvLayer( A , stride=A , groups=A , activation=config.hidden_act , name="""layer.1""" ), TFRegNetSELayer(A , reduced_channels=int(round(in_channels / 4 ) ) , name="""layer.2""" ), TFRegNetConvLayer(A , kernel_size=1 , activation=A , name="""layer.3""" ), ] _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: _SCREAMING_SNAKE_CASE = layer_module(A ) _SCREAMING_SNAKE_CASE = self.shortcut(A ) hidden_state += residual _SCREAMING_SNAKE_CASE = self.activation(A ) return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , A , A , A = 2 , A = 2 , **A ) -> int: super().__init__(**A ) _SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer _SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(A , A , A , stride=A , name="""layers.0""" ), *[layer(A , A , A , name=f'layers.{i+1}' ) for i in range(depth - 1 )], ] def snake_case_( self , A ) -> Optional[Any]: for layer_module in self.layers: _SCREAMING_SNAKE_CASE = layer_module(A ) return hidden_state class a_ ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self , A , **A ) -> Tuple: super().__init__(**A ) _SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="""stages.0""" , ) ) _SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A , config.depths[1:] ) ): self.stages.append(TFRegNetStage(A , A , A , depth=A , name=f'stages.{i+1}' ) ) def snake_case_( self , A , A = False , A = True ) -> TFBaseModelOutputWithNoAttention: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) _SCREAMING_SNAKE_CASE = stage_module(A ) if output_hidden_states: _SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) @keras_serializable class a_ ( tf.keras.layers.Layer ): '''simple docstring''' UpperCamelCase = RegNetConfig def __init__( self , A , **A ) -> Any: super().__init__(**A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(A , name="""embedder""" ) _SCREAMING_SNAKE_CASE = TFRegNetEncoder(A , name="""encoder""" ) _SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A , name="""pooler""" ) @unpack_inputs def snake_case_( self , A , A = None , A = None , A = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.embedder(A , training=A ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , training=A ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] _SCREAMING_SNAKE_CASE = self.pooler(A ) # Change to NCHW output format have uniformity in the modules _SCREAMING_SNAKE_CASE = tf.transpose(A , perm=(0, 3, 1, 2) ) _SCREAMING_SNAKE_CASE = tf.transpose(A , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: _SCREAMING_SNAKE_CASE = tuple([tf.transpose(A , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A , pooler_output=A , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = RegNetConfig UpperCamelCase = '''regnet''' UpperCamelCase = '''pixel_values''' @property def snake_case_( self ) -> str: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa )} lowercase_ = R""" Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( '''The bare RegNet model outputting raw features without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , *A , **A ) -> Any: super().__init__(A , *A , **A ) _SCREAMING_SNAKE_CASE = TFRegNetMainLayer(A , name="""regnet""" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A , A = None , A = None , A=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.regnet( pixel_values=A , output_hidden_states=A , return_dict=A , training=A , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( ''' RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , snake_case_ , ) class a_ ( snake_case_ , snake_case_ ): '''simple docstring''' def __init__( self , A , *A , **A ) -> str: super().__init__(A , *A , **A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = TFRegNetMainLayer(A , name="""regnet""" ) # classification head _SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="""classifier.1""" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , A=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.regnet( A , output_hidden_states=A , return_dict=A , training=A ) _SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] _SCREAMING_SNAKE_CASE = self.classifier[0](A ) _SCREAMING_SNAKE_CASE = self.classifier[1](A ) _SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=A , logits=A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[int]: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += [key] setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator def lowerCamelCase ( *__lowerCamelCase : List[str] ) ->Dict: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += keys setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator class a_ ( snake_case_ ): '''simple docstring''' def __new__( cls , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = super().__new__(cls , A , A , A ) if not hasattr(A , """key_handler""" ): setattr(A , """key_handler""" , {} ) setattr(A , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE = getattr(A , """handle_key""" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def snake_case_( cls ) -> str: _SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE = ord(A ) _SCREAMING_SNAKE_CASE = cls.key_handler.get(A ) if handler: _SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def lowerCamelCase ( cls : Any ) ->Dict: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
58
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": operator.gt, } def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ) ->Tuple: if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) ->None: _SCREAMING_SNAKE_CASE = F'\n{hint}' if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = requirement, None, None else: _SCREAMING_SNAKE_CASE = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F' got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE = {} for w in want_range: _SCREAMING_SNAKE_CASE = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F' but got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->str: _SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
58
1
'''simple docstring''' import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib lowercase_ = { """debug""": logging.DEBUG, """info""": logging.INFO, """warning""": logging.WARNING, """error""": logging.ERROR, """critical""": logging.CRITICAL, } lowercase_ = logging.WARNING def lowerCamelCase ( ) ->Dict: _SCREAMING_SNAKE_CASE = os.getenv("""DATASETS_VERBOSITY""" , __lowerCamelCase ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F'Unknown option DATASETS_VERBOSITY={env_level_str}, ' F'has to be one of: { ", ".join(log_levels.keys() ) }' ) return _default_log_level def lowerCamelCase ( ) ->str: return __name__.split(""".""" )[0] def lowerCamelCase ( ) ->logging.Logger: return logging.getLogger(_get_library_name() ) def lowerCamelCase ( ) ->None: # Apply our default configuration to the library root logger. _SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def lowerCamelCase ( ) ->None: _SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def lowerCamelCase ( __lowerCamelCase : Optional[str] = None ) ->logging.Logger: if name is None: _SCREAMING_SNAKE_CASE = _get_library_name() return logging.getLogger(__lowerCamelCase ) def lowerCamelCase ( ) ->int: return _get_library_root_logger().getEffectiveLevel() def lowerCamelCase ( __lowerCamelCase : int ) ->None: _get_library_root_logger().setLevel(__lowerCamelCase ) def lowerCamelCase ( ) ->Optional[Any]: return set_verbosity(__lowerCamelCase ) def lowerCamelCase ( ) ->List[str]: return set_verbosity(__lowerCamelCase ) def lowerCamelCase ( ) ->Optional[int]: return set_verbosity(__lowerCamelCase ) def lowerCamelCase ( ) ->List[Any]: return set_verbosity(__lowerCamelCase ) def lowerCamelCase ( ) ->None: _SCREAMING_SNAKE_CASE = False def lowerCamelCase ( ) ->None: _SCREAMING_SNAKE_CASE = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class a_ : '''simple docstring''' def __init__( self , *A , **A ) -> int: # pylint: disable=unused-argument _SCREAMING_SNAKE_CASE = args[0] if args else None def __iter__( self ) -> List[Any]: return iter(self._iterator ) def __getattr__( self , A ) -> Dict: def empty_fn(*A , **A ): # pylint: disable=unused-argument return return empty_fn def __enter__( self ) -> Dict: return self def __exit__( self , A , A , A ) -> List[str]: return lowercase_ = True class a_ : '''simple docstring''' def __call__( self , *A , A=False , **A ) -> Optional[Any]: if _tqdm_active and not disable: return tqdm_lib.tqdm(*A , **A ) else: return EmptyTqdm(*A , **A ) def snake_case_( self , *A , **A ) -> Dict: _SCREAMING_SNAKE_CASE = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*A , **A ) def snake_case_( self ) -> Dict: if _tqdm_active: return tqdm_lib.tqdm.get_lock() lowercase_ = _tqdm_cls() def lowerCamelCase ( ) ->bool: global _tqdm_active return bool(_tqdm_active ) def lowerCamelCase ( ) ->Optional[int]: global _tqdm_active _SCREAMING_SNAKE_CASE = True def lowerCamelCase ( ) ->str: global _tqdm_active _SCREAMING_SNAKE_CASE = False
58
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _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]: _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_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(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 lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , 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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , 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 ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
1
'''simple docstring''' from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(snake_case_ ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , **A ) -> Any: super().__init__(**A ) requires_backends(self , """vision""" ) requires_backends(self , """torch""" ) if self.framework != "pt": raise ValueError(f'The {self.__class__} is only available in PyTorch.' ) self.check_model_type(A ) def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = {} # preprocess args if "points_per_batch" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""points_per_batch"""] if "points_per_crop" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""points_per_crop"""] if "crops_n_layers" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""crops_n_layers"""] if "crop_overlap_ratio" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""crop_overlap_ratio"""] if "crop_n_points_downscale_factor" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""crop_n_points_downscale_factor"""] # postprocess args if "pred_iou_thresh" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""pred_iou_thresh"""] if "stability_score_offset" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""stability_score_offset"""] if "mask_threshold" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""mask_threshold"""] if "stability_score_thresh" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""stability_score_thresh"""] if "crops_nms_thresh" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""crops_nms_thresh"""] if "output_rle_mask" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""output_rle_mask"""] if "output_bboxes_mask" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""output_bboxes_mask"""] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self , A , *A , A=None , A=None , **A ) -> List[Any]: return super().__call__(A , *A , num_workers=A , batch_size=A , **A ) def snake_case_( self , A , A=64 , A = 0 , A = 512 / 1500 , A = 32 , A = 1 , ) -> Tuple: _SCREAMING_SNAKE_CASE = load_image(A ) _SCREAMING_SNAKE_CASE = self.image_processor.size["""longest_edge"""] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.image_processor.generate_crop_boxes( A , A , A , A , A , A ) _SCREAMING_SNAKE_CASE = self.image_processor(images=A , return_tensors="""pt""" ) with self.device_placement(): if self.framework == "pt": _SCREAMING_SNAKE_CASE = self.get_inference_context() with inference_context(): _SCREAMING_SNAKE_CASE = self._ensure_tensor_on_device(A , device=self.device ) _SCREAMING_SNAKE_CASE = self.model.get_image_embeddings(model_inputs.pop("""pixel_values""" ) ) _SCREAMING_SNAKE_CASE = image_embeddings _SCREAMING_SNAKE_CASE = grid_points.shape[1] _SCREAMING_SNAKE_CASE = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( """Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. """ """To return all points at once, set points_per_batch to None""" ) for i in range(0 , A , A ): _SCREAMING_SNAKE_CASE = grid_points[:, i : i + points_per_batch, :, :] _SCREAMING_SNAKE_CASE = input_labels[:, i : i + points_per_batch] _SCREAMING_SNAKE_CASE = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def snake_case_( self , A , A=0.88 , A=0.95 , A=0 , A=1 , ) -> Optional[int]: _SCREAMING_SNAKE_CASE = model_inputs.pop("""input_boxes""" ) _SCREAMING_SNAKE_CASE = model_inputs.pop("""is_last""" ) _SCREAMING_SNAKE_CASE = model_inputs.pop("""original_sizes""" ).tolist() _SCREAMING_SNAKE_CASE = model_inputs.pop("""reshaped_input_sizes""" ).tolist() _SCREAMING_SNAKE_CASE = self.model(**A ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks _SCREAMING_SNAKE_CASE = model_outputs["""pred_masks"""] _SCREAMING_SNAKE_CASE = self.image_processor.post_process_masks( A , A , A , A , binarize=A ) _SCREAMING_SNAKE_CASE = model_outputs["""iou_scores"""] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , A , A , A , A , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def snake_case_( self , A , A=False , A=False , A=0.7 , ) -> str: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] for model_output in model_outputs: all_scores.append(model_output.pop("""iou_scores""" ) ) all_masks.extend(model_output.pop("""masks""" ) ) all_boxes.append(model_output.pop("""boxes""" ) ) _SCREAMING_SNAKE_CASE = torch.cat(A ) _SCREAMING_SNAKE_CASE = torch.cat(A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.image_processor.post_process_for_mask_generation( A , A , A , A ) _SCREAMING_SNAKE_CASE = defaultdict(A ) for output in model_outputs: for k, v in output.items(): extra[k].append(A ) _SCREAMING_SNAKE_CASE = {} if output_rle_mask: _SCREAMING_SNAKE_CASE = rle_mask if output_bboxes_mask: _SCREAMING_SNAKE_CASE = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
58
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: 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(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
1
'''simple docstring''' from math import log from scipy.constants import Boltzmann, physical_constants lowercase_ = 300 # TEMPERATURE (unit = K) def lowerCamelCase ( __lowerCamelCase : float , __lowerCamelCase : float , __lowerCamelCase : float , ) ->float: if donor_conc <= 0: raise ValueError("""Donor concentration should be positive""" ) elif acceptor_conc <= 0: raise ValueError("""Acceptor concentration should be positive""" ) elif intrinsic_conc <= 0: raise ValueError("""Intrinsic concentration should be positive""" ) elif donor_conc <= intrinsic_conc: raise ValueError( """Donor concentration should be greater than intrinsic concentration""" ) elif acceptor_conc <= intrinsic_conc: raise ValueError( """Acceptor concentration should be greater than intrinsic concentration""" ) else: return ( Boltzmann * T * log((donor_conc * acceptor_conc) / intrinsic_conc**2 ) / physical_constants["electron volt"][0] ) if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase_ = None lowercase_ = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase_ = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class a_ : '''simple docstring''' UpperCamelCase = True UpperCamelCase = None # Automatically constructed UpperCamelCase = "PIL.Image.Image" UpperCamelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCamelCase = field(default='''Image''' , init=snake_case_ , repr=snake_case_ ) def __call__( self ) -> Tuple: return self.pa_type def snake_case_( self , A ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(A , A ): _SCREAMING_SNAKE_CASE = np.array(A ) if isinstance(A , A ): return {"path": value, "bytes": None} elif isinstance(A , A ): return {"path": None, "bytes": value} elif isinstance(A , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(A ) elif isinstance(A , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(A ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def snake_case_( self , A , A=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(A ): _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) else: _SCREAMING_SNAKE_CASE = path.split("""::""" )[-1] try: _SCREAMING_SNAKE_CASE = string_to_dict(A , config.HUB_DATASETS_URL )["""repo_id"""] _SCREAMING_SNAKE_CASE = token_per_repo_id.get(A ) except ValueError: _SCREAMING_SNAKE_CASE = None with xopen(A , """rb""" , use_auth_token=A ) as f: _SCREAMING_SNAKE_CASE = BytesIO(f.read() ) _SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: _SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case_( self , A ) -> pa.StructArray: if pa.types.is_string(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""bytes""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""path""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(A ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def snake_case_( self , A ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(A ): with xopen(A , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() return bytes_ _SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(A ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def lowerCamelCase ( ) ->List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() _SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->bytes: _SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): _SCREAMING_SNAKE_CASE = image.format else: _SCREAMING_SNAKE_CASE = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->dict: if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : np.ndarray ) ->dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) _SCREAMING_SNAKE_CASE = array.dtype _SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER _SCREAMING_SNAKE_CASE = dtype.kind _SCREAMING_SNAKE_CASE = dtype.itemsize _SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _SCREAMING_SNAKE_CASE = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: _SCREAMING_SNAKE_CASE = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: _SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.dtype(__lowerCamelCase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) _SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) ->List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->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 , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = min(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ugly_nums.append(__lowerCamelCase ) 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) = }""")
58
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''data2vec-text''' def __init__( self , A=3_0522 , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=1 , A=0 , A=2 , A="absolute" , A=True , A=None , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = classifier_dropout class a_ ( snake_case_ ): '''simple docstring''' @property def snake_case_( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
58
1
'''simple docstring''' import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process lowercase_ = logging.getLogger(__name__) lowercase_ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) lowercase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a_ : '''simple docstring''' UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) UpperCamelCase = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def snake_case_( self ) -> str: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCamelCase = field(default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) UpperCamelCase = field( default=5 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) UpperCamelCase = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) } , ) def snake_case_( self ) -> Optional[int]: if self.train_file is not None: _SCREAMING_SNAKE_CASE = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: _SCREAMING_SNAKE_CASE = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ) ->Tuple: with open(__lowerCamelCase , """r""" , encoding="""utf-8""" ) as f: _SCREAMING_SNAKE_CASE = [json.loads(__lowerCamelCase ) for line in f.read().splitlines() if (len(__lowerCamelCase ) > 0 and not line.isspace())] assert len(__lowerCamelCase ) == len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = {c: dataset[c] for c in dataset.column_names} _SCREAMING_SNAKE_CASE = refs return Dataset.from_dict(__lowerCamelCase ) def lowerCamelCase ( ) ->Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Detecting last checkpoint. _SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , __lowerCamelCase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. _SCREAMING_SNAKE_CASE = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[:{data_args.validation_split_percentage}%]' , ) _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[{data_args.validation_split_percentage}%:]' , ) else: _SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: _SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: _SCREAMING_SNAKE_CASE = data_args.validation_file _SCREAMING_SNAKE_CASE = data_args.train_file.split(""".""" )[-1] if extension == "txt": _SCREAMING_SNAKE_CASE = """text""" _SCREAMING_SNAKE_CASE = load_dataset(__lowerCamelCase , data_files=__lowerCamelCase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.config_name , **__lowerCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.model_name_or_path , **__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) _SCREAMING_SNAKE_CASE = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **__lowerCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **__lowerCamelCase ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_config(__lowerCamelCase ) model.resize_token_embeddings(len(__lowerCamelCase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: _SCREAMING_SNAKE_CASE = datasets["""train"""].column_names else: _SCREAMING_SNAKE_CASE = datasets["""validation"""].column_names _SCREAMING_SNAKE_CASE = """text""" if """text""" in column_names else column_names[0] _SCREAMING_SNAKE_CASE = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(__lowerCamelCase : List[str] ): # Remove empty lines _SCREAMING_SNAKE_CASE = [line for line in examples["""text"""] if len(__lowerCamelCase ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=data_args.max_seq_length ) _SCREAMING_SNAKE_CASE = datasets.map( __lowerCamelCase , batched=__lowerCamelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: _SCREAMING_SNAKE_CASE = add_chinese_references(tokenized_datasets["""train"""] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: _SCREAMING_SNAKE_CASE = add_chinese_references( tokenized_datasets["""validation"""] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer _SCREAMING_SNAKE_CASE = data_args.train_ref_file or data_args.validation_ref_file if has_ref: _SCREAMING_SNAKE_CASE = False # Data collator # This one will take care of randomly masking the tokens. _SCREAMING_SNAKE_CASE = DataCollatorForWholeWordMask(tokenizer=__lowerCamelCase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _SCREAMING_SNAKE_CASE = Trainer( model=__lowerCamelCase , args=__lowerCamelCase , train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None , eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None , tokenizer=__lowerCamelCase , data_collator=__lowerCamelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: _SCREAMING_SNAKE_CASE = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): _SCREAMING_SNAKE_CASE = model_args.model_name_or_path else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=__lowerCamelCase ) trainer.save_model() # Saves the tokenizer too for easy upload _SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , """train_results.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCamelCase , """w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , """trainer_state.json""" ) ) # Evaluation _SCREAMING_SNAKE_CASE = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _SCREAMING_SNAKE_CASE = trainer.evaluate() _SCREAMING_SNAKE_CASE = math.exp(eval_output["""eval_loss"""] ) _SCREAMING_SNAKE_CASE = perplexity _SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , """eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) return results def lowerCamelCase ( __lowerCamelCase : List[str] ) ->Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
58
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ) ->Union[str, Any]: for attribute in key.split(""".""" ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: _SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE = value elif weight_type == "bias": _SCREAMING_SNAKE_CASE = value else: _SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowerCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ) ->Any: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = fairseq_model.state_dict() _SCREAMING_SNAKE_CASE = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) _SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): _SCREAMING_SNAKE_CASE = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): _SCREAMING_SNAKE_CASE = True if "*" in mapped_key: _SCREAMING_SNAKE_CASE = name.split(__lowerCamelCase )[0].split(""".""" )[-2] _SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: _SCREAMING_SNAKE_CASE = """weight_v""" elif "weight" in name: _SCREAMING_SNAKE_CASE = """weight""" elif "bias" in name: _SCREAMING_SNAKE_CASE = """bias""" else: _SCREAMING_SNAKE_CASE = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(F'Unused weights: {unused_weights}' ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] _SCREAMING_SNAKE_CASE = name.split(""".""" ) _SCREAMING_SNAKE_CASE = int(items[0] ) _SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Union[str, Any]=True ) ->Optional[int]: if config_path is not None: _SCREAMING_SNAKE_CASE = HubertConfig.from_pretrained(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertConfig() if is_finetuned: if dict_path: _SCREAMING_SNAKE_CASE = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _SCREAMING_SNAKE_CASE = target_dict.pad_index _SCREAMING_SNAKE_CASE = target_dict.bos_index _SCREAMING_SNAKE_CASE = target_dict.eos_index _SCREAMING_SNAKE_CASE = len(target_dict.symbols ) _SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == """layer""" else False _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = HubertForCTC(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertModel(__lowerCamelCase ) if is_finetuned: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _SCREAMING_SNAKE_CASE = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowercase_ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
58
1
'''simple docstring''' import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : str , __lowerCamelCase : List[Any] ) ->Tuple: _SCREAMING_SNAKE_CASE = UniSpeechSatForSequenceClassification.from_pretrained(__lowerCamelCase , config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = downstream_dict["""projector.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""projector.bias"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.post_net.linear.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.post_net.linear.bias"""] return model def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Union[str, Any] ) ->List[str]: _SCREAMING_SNAKE_CASE = UniSpeechSatForAudioFrameClassification.from_pretrained(__lowerCamelCase , config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = downstream_dict["""model.linear.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.linear.bias"""] return model def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict ) ->Dict: _SCREAMING_SNAKE_CASE = UniSpeechSatForXVector.from_pretrained(__lowerCamelCase , config=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = downstream_dict["""connector.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): _SCREAMING_SNAKE_CASE = downstream_dict[ F'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] _SCREAMING_SNAKE_CASE = downstream_dict[F'model.framelevel_feature_extractor.module.{i}.kernel.bias'] _SCREAMING_SNAKE_CASE = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] _SCREAMING_SNAKE_CASE = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] _SCREAMING_SNAKE_CASE = downstream_dict["""objective.W"""] return model @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple ) ->List[str]: _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = checkpoint["""Downstream"""] _SCREAMING_SNAKE_CASE = UniSpeechSatConfig.from_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor.from_pretrained( __lowerCamelCase , return_attention_mask=__lowerCamelCase , do_normalize=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): _SCREAMING_SNAKE_CASE = convert_classification(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) elif arch.endswith("""ForAudioFrameClassification""" ): _SCREAMING_SNAKE_CASE = convert_diarization(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) elif arch.endswith("""ForXVector""" ): _SCREAMING_SNAKE_CASE = convert_xvector(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) else: raise NotImplementedError(F'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: _SCREAMING_SNAKE_CASE = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(__lowerCamelCase ) hf_model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model.""" ) parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""") parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""") lowercase_ = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
58
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def lowerCamelCase ( __lowerCamelCase : str ) ->str: if not sentence: return "" _SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , __lowerCamelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
58
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a_ ( snake_case_ , snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = StableDiffusionInpaintPipeline UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS UpperCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS UpperCamelCase = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase = frozenset([] ) def snake_case_( self ) -> str: torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=9 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=A , ) _SCREAMING_SNAKE_CASE = PNDMScheduler(skip_prk_steps=A ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="""gelu""" , projection_dim=512 , ) _SCREAMING_SNAKE_CASE = CLIPTextModel(A ) _SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _SCREAMING_SNAKE_CASE = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def snake_case_( self , A , A=0 ) -> Optional[Any]: # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched _SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 32, 32) , rng=random.Random(A ) ).to(A ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 )[0] _SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(A ) ).convert("""RGB""" ).resize((64, 64) ) _SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(image + 4 ) ).convert("""RGB""" ).resize((64, 64) ) 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""": """A painting of a squirrel eating a burger""", """image""": init_image, """mask_image""": mask_image, """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 6.0, """output_type""": """numpy""", } return inputs def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = """cpu""" # ensure determinism for the device-dependent torch.Generator _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline(**A ) _SCREAMING_SNAKE_CASE = sd_pipe.to(A ) sd_pipe.set_progress_bar_config(disable=A ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(A ) _SCREAMING_SNAKE_CASE = sd_pipe(**A ).images _SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _SCREAMING_SNAKE_CASE = np.array([0.4727, 0.5735, 0.3941, 0.5446, 0.5926, 0.4394, 0.5062, 0.4654, 0.4476] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_( self ) -> Any: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench.npy""" ) _SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" _SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained(A , safety_checker=A ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=A , image=A , mask_image=A , generator=A , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 9e-3 def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint""" """/yellow_cat_sitting_on_a_park_bench_fp16.npy""" ) _SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" _SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( A , torch_dtype=torch.floataa , safety_checker=A , ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) pipe.enable_attention_slicing() _SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=A , image=A , mask_image=A , generator=A , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 5e-1 def snake_case_( self ) -> int: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/sd2-inpaint/init_image.png""" ) _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png""" ) _SCREAMING_SNAKE_CASE = """stabilityai/stable-diffusion-2-inpainting""" _SCREAMING_SNAKE_CASE = PNDMScheduler.from_pretrained(A , subfolder="""scheduler""" ) _SCREAMING_SNAKE_CASE = StableDiffusionInpaintPipeline.from_pretrained( A , safety_checker=A , scheduler=A , torch_dtype=torch.floataa , ) pipe.to(A ) pipe.set_progress_bar_config(disable=A ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() _SCREAMING_SNAKE_CASE = """Face of a yellow cat, high resolution, sitting on a park bench""" _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe( prompt=A , image=A , mask_image=A , generator=A , num_inference_steps=2 , output_type="""np""" , ) _SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.65 GB is allocated assert mem_bytes < 2.65 * 10**9
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _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]: _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_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(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 lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , 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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , 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 ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any]=8 ) ->Tuple: _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A , A , ) -> Union[str, Any]: super().__init__() self.register_modules( unet=A , scheduler=A , movq=A , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_( self , A , A , A , A , A , A ) -> Union[str, Any]: if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A , device=A , dtype=A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(A ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_( self , A=0 ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A , A ) def snake_case_( self , A=0 ) -> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(A , A , prev_module_hook=A ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_( self ) -> Tuple: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self , A , A , A = 512 , A = 512 , A = 100 , A = 4.0 , A = 1 , A = None , A = None , A = "pil" , A = True , ) -> List[str]: _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A ) self.scheduler.set_timesteps(A , device=A ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(A , A , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A , A , A , self.scheduler , ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE = self.unet( sample=A , timestep=A , encoder_hidden_states=A , added_cond_kwargs=A , return_dict=A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( A , A , A , generator=A , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(A , force_not_quantize=A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
58
1
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
'''simple docstring''' import operator as op lowercase_ = """scaler.pt""" lowercase_ = """pytorch_model""" lowercase_ = """random_states""" lowercase_ = """optimizer""" lowercase_ = """scheduler""" lowercase_ = """pytorch_model.bin""" lowercase_ = """pytorch_model.bin.index.json""" lowercase_ = """model.safetensors""" lowercase_ = """model.safetensors.index.json""" lowercase_ = """1.10.2""" lowercase_ = """py38""" lowercase_ = """4.17.0""" lowercase_ = ["""ml.p3.16xlarge""", """ml.p3dn.24xlarge""", """ml.p4dn.24xlarge"""] lowercase_ = ["""FULL_SHARD""", """SHARD_GRAD_OP""", """NO_SHARD""", """HYBRID_SHARD""", """HYBRID_SHARD_ZERO2"""] lowercase_ = ["""TRANSFORMER_BASED_WRAP""", """SIZE_BASED_WRAP""", """NO_WRAP"""] lowercase_ = ["""BACKWARD_PRE""", """BACKWARD_POST""", """NO_PREFETCH"""] lowercase_ = ["""FULL_STATE_DICT""", """LOCAL_STATE_DICT""", """SHARDED_STATE_DICT"""] lowercase_ = """2.0.1""" lowercase_ = ["""pdsh""", """standard""", """openmpi""", """mvapich"""] lowercase_ = ["""default""", """reduce-overhead""", """max-autotune"""] lowercase_ = {""">""": op.gt, """>=""": op.ge, """==""": op.eq, """!=""": op.ne, """<=""": op.le, """<""": op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 lowercase_ = [ """nnodes""", """nproc_per_node""", """rdzv_backend""", """rdzv_endpoint""", """rdzv_id""", """rdzv_conf""", """standalone""", """max_restarts""", """monitor_interval""", """start_method""", """role""", """module""", """m""", """no_python""", """run_path""", """log_dir""", """r""", """redirects""", """t""", """tee""", """node_rank""", """master_addr""", """master_port""", ] lowercase_ = ["""DEEPSPEED""", """MULTI_GPU""", """FSDP""", """MEGATRON_LM"""] lowercase_ = ["""DEEPSPEED""", """MULTI_XPU""", """FSDP"""]
58
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """PoolFormerConfig""" # Base docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = [1, 512, 7, 7] # Image classification docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : float = 0.0 , __lowerCamelCase : bool = False ) ->int: if drop_prob == 0.0 or not training: return input _SCREAMING_SNAKE_CASE = 1 - drop_prob _SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _SCREAMING_SNAKE_CASE = keep_prob + torch.rand(__lowerCamelCase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _SCREAMING_SNAKE_CASE = input.div(__lowerCamelCase ) * random_tensor return output class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A = None ) -> None: super().__init__() _SCREAMING_SNAKE_CASE = drop_prob def snake_case_( self , A ) -> torch.Tensor: return drop_path(A , self.drop_prob , self.training ) def snake_case_( self ) -> str: return "p={}".format(self.drop_prob ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A=None ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = patch_size if isinstance(A , collections.abc.Iterable ) else (patch_size, patch_size) _SCREAMING_SNAKE_CASE = stride if isinstance(A , collections.abc.Iterable ) else (stride, stride) _SCREAMING_SNAKE_CASE = padding if isinstance(A , collections.abc.Iterable ) else (padding, padding) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , kernel_size=A , stride=A , padding=A ) _SCREAMING_SNAKE_CASE = norm_layer(A ) if norm_layer else nn.Identity() def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.projection(A ) _SCREAMING_SNAKE_CASE = self.norm(A ) return embeddings class a_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self , A , **A ) -> Union[str, Any]: super().__init__(1 , A , **A ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.AvgPoolad(A , stride=1 , padding=pool_size // 2 , count_include_pad=A ) def snake_case_( self , A ) -> Union[str, Any]: return self.pool(A ) - hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if isinstance(config.hidden_act , A ): _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: _SCREAMING_SNAKE_CASE = config.hidden_act def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.act_fn(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) return hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = PoolFormerPooling(A ) _SCREAMING_SNAKE_CASE = PoolFormerOutput(A , A , A , A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) # Useful for training neural nets _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() _SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) def snake_case_( self , A ) -> Optional[Any]: if self.use_layer_scale: _SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = () _SCREAMING_SNAKE_CASE = self.output(self.after_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: _SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection _SCREAMING_SNAKE_CASE = pooling_output + hidden_states _SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block _SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(A ) ) ) _SCREAMING_SNAKE_CASE = hidden_states + layer_output _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE = config # stochastic depth decay rule _SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) # Transformer blocks _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(A ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) def snake_case_( self , A , A=False , A=True ) -> List[Any]: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None _SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states _SCREAMING_SNAKE_CASE = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): _SCREAMING_SNAKE_CASE = blk(A ) _SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: _SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = PoolFormerConfig UpperCamelCase = '''poolformer''' UpperCamelCase = '''pixel_values''' UpperCamelCase = True def snake_case_( self , A ) -> int: if isinstance(A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_( self , A , A=False ) -> Dict: if isinstance(A , A ): _SCREAMING_SNAKE_CASE = value lowercase_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> int: super().__init__(A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def snake_case_( self ) -> Any: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A = None , A = None , A = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A , hidden_states=encoder_outputs.hidden_states , ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> Optional[Any]: super().__init__(A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = PoolFormerModel(A ) # Final norm _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.poolformer( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = outputs[0] _SCREAMING_SNAKE_CASE = self.classifier(self.norm(A ).mean([-2, -1] ) ) _SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE = """single_label_classification""" else: _SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE = loss_fct(A , A ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE = CrossEntropyLoss() _SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE = loss_fct(A , A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ShapEImgaImgPipeline UpperCamelCase = ['''image'''] UpperCamelCase = ['''image'''] UpperCamelCase = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] UpperCamelCase = False @property def snake_case_( self ) -> Optional[Any]: return 32 @property def snake_case_( self ) -> Union[str, Any]: return 32 @property def snake_case_( self ) -> int: return self.time_input_dim * 4 @property def snake_case_( self ) -> Tuple: return 8 @property def snake_case_( self ) -> List[Any]: torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) _SCREAMING_SNAKE_CASE = CLIPVisionModel(A ) return model @property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = CLIPImageProcessor( crop_size=224 , do_center_crop=A , do_normalize=A , do_resize=A , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , ) return image_processor @property def snake_case_( self ) -> Optional[int]: 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""", """embedding_proj_norm_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } _SCREAMING_SNAKE_CASE = PriorTransformer(**A ) return model @property def snake_case_( self ) -> Any: 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 ) -> Any: _SCREAMING_SNAKE_CASE = self.dummy_prior _SCREAMING_SNAKE_CASE = self.dummy_image_encoder _SCREAMING_SNAKE_CASE = self.dummy_image_processor _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, """image_encoder""": image_encoder, """image_processor""": image_processor, """renderer""": renderer, """scheduler""": scheduler, } return components def snake_case_( self , A , A=0 ) -> Tuple: _SCREAMING_SNAKE_CASE = floats_tensor((1, 3, 64, 64) , rng=random.Random(A ) ).to(A ) 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 = { """image""": input_image, """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def snake_case_( self ) -> Any: _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.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, 0.0003_9216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def snake_case_( self ) -> List[Any]: # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def snake_case_( self ) -> Optional[Any]: _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 ) -> Optional[int]: _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 a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/corgi.png""" ) _SCREAMING_SNAKE_CASE = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_img2img_out.npy""" ) _SCREAMING_SNAKE_CASE = ShapEImgaImgPipeline.from_pretrained("""openai/shap-e-img2img""" ) _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 , generator=A , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(A , A )
58
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase_ = logging.getLogger(__name__) lowercase_ = """Hello world! cécé herlolip""" lowercase_ = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir=""".""" , finetune_bert=__lowerCamelCase , large=__lowerCamelCase , share_emb=__lowerCamelCase , use_bert_emb=__lowerCamelCase , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , lambda __lowerCamelCase , __lowerCamelCase : storage ) _SCREAMING_SNAKE_CASE = AbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) , __lowerCamelCase ) original.eval() _SCREAMING_SNAKE_CASE = BertAbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass _SCREAMING_SNAKE_CASE = encoder_input_ids _SCREAMING_SNAKE_CASE = decoder_input_ids _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical _SCREAMING_SNAKE_CASE = original(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = original.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = new_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = new_model.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) lowercase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
58
1
'''simple docstring''' import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser lowercase_ = re.compile(R"""\s+""") def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[Any]: return {"hash": hashlib.mda(re.sub(__lowerCamelCase , """""" , example["""content"""] ).encode("""utf-8""" ) ).hexdigest()} def lowerCamelCase ( __lowerCamelCase : Optional[int] ) ->Dict: _SCREAMING_SNAKE_CASE = [len(__lowerCamelCase ) for line in example["""content"""].splitlines()] return {"line_mean": np.mean(__lowerCamelCase ), "line_max": max(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Any ) ->Any: _SCREAMING_SNAKE_CASE = np.mean([c.isalnum() for c in example["""content"""]] ) return {"alpha_frac": alpha_frac} def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] ) ->Union[str, Any]: if example["hash"] in uniques: uniques.remove(example["""hash"""] ) return True else: return False def lowerCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any]=5 ) ->str: _SCREAMING_SNAKE_CASE = ["""auto-generated""", """autogenerated""", """automatically generated"""] _SCREAMING_SNAKE_CASE = example["""content"""].splitlines() for _, line in zip(range(__lowerCamelCase ) , __lowerCamelCase ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any]=5 , __lowerCamelCase : Union[str, Any]=0.05 ) ->Dict: _SCREAMING_SNAKE_CASE = ["""unit tests""", """test file""", """configuration file"""] _SCREAMING_SNAKE_CASE = example["""content"""].splitlines() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # first test for _, line in zip(range(__lowerCamelCase ) , __lowerCamelCase ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test _SCREAMING_SNAKE_CASE = example["""content"""].count("""\n""" ) _SCREAMING_SNAKE_CASE = int(coeff * nlines ) for line in lines: count_config += line.lower().count("""config""" ) count_test += line.lower().count("""test""" ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def lowerCamelCase ( __lowerCamelCase : List[str] ) ->str: _SCREAMING_SNAKE_CASE = ["""def """, """class """, """for """, """while """] _SCREAMING_SNAKE_CASE = example["""content"""].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int]=4 ) ->List[Any]: _SCREAMING_SNAKE_CASE = example["""content"""].splitlines() _SCREAMING_SNAKE_CASE = 0 for line in lines: counter += line.lower().count("""=""" ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def lowerCamelCase ( __lowerCamelCase : str ) ->str: _SCREAMING_SNAKE_CASE = tokenizer(example["""content"""] , truncation=__lowerCamelCase )["""input_ids"""] _SCREAMING_SNAKE_CASE = len(example["""content"""] ) / len(__lowerCamelCase ) return {"ratio": ratio} def lowerCamelCase ( __lowerCamelCase : List[Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = {} results.update(get_hash(__lowerCamelCase ) ) results.update(line_stats(__lowerCamelCase ) ) results.update(alpha_stats(__lowerCamelCase ) ) results.update(char_token_ratio(__lowerCamelCase ) ) results.update(is_autogenerated(__lowerCamelCase ) ) results.update(is_config_or_test(__lowerCamelCase ) ) results.update(has_no_keywords(__lowerCamelCase ) ) results.update(has_few_assignments(__lowerCamelCase ) ) return results def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : int , __lowerCamelCase : str ) ->Tuple: if not check_uniques(__lowerCamelCase , __lowerCamelCase ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def lowerCamelCase ( __lowerCamelCase : Dict ) ->Optional[int]: with open(__lowerCamelCase , """rb""" ) as f_in: with gzip.open(str(__lowerCamelCase ) + """.gz""" , """wb""" , compresslevel=6 ) as f_out: shutil.copyfileobj(__lowerCamelCase , __lowerCamelCase ) os.unlink(__lowerCamelCase ) # Settings lowercase_ = HfArgumentParser(PreprocessingArguments) lowercase_ = parser.parse_args() if args.num_workers is None: lowercase_ = multiprocessing.cpu_count() lowercase_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset lowercase_ = time.time() lowercase_ = load_dataset(args.dataset_name, split="""train""") print(f"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing lowercase_ = time.time() lowercase_ = ds.map(preprocess, num_proc=args.num_workers) print(f"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes lowercase_ = set(ds.unique("""hash""")) lowercase_ = len(uniques) / len(ds) print(f"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics lowercase_ = time.time() lowercase_ = ds.filter(filter, fn_kwargs={"""uniques""": uniques, """args""": args}) print(f"""Time to filter dataset: {time.time()-t_start:.2f}""") print(f"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: lowercase_ = time.time() lowercase_ , lowercase_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(f"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(f"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file lowercase_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / """duplicate_clusters.json""", """w""") as f: json.dump(duplicate_clusters, f) lowercase_ = output_dir / """data""" data_dir.mkdir(exist_ok=True) lowercase_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): lowercase_ = str(data_dir / f"""file-{file_number+1:012}.json""") lowercase_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(f"""Time to save dataset: {time.time()-t_start:.2f}""")
58
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
1
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING lowercase_ = logging.get_logger(__name__) @add_end_docstrings(snake_case_ ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , **A ) -> List[Any]: super().__init__(**A ) if self.framework == "tf": raise ValueError(f'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type(A ) def __call__( self , A , A = None , **A , ) -> List[Any]: if "text_queries" in kwargs: _SCREAMING_SNAKE_CASE = kwargs.pop("""text_queries""" ) if isinstance(A , (str, Image.Image) ): _SCREAMING_SNAKE_CASE = {"""image""": image, """candidate_labels""": candidate_labels} else: _SCREAMING_SNAKE_CASE = image _SCREAMING_SNAKE_CASE = super().__call__(A , **A ) return results def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = {} if "threshold" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""threshold"""] if "top_k" in kwargs: _SCREAMING_SNAKE_CASE = kwargs["""top_k"""] return {}, {}, postprocess_params def snake_case_( self , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = load_image(inputs["""image"""] ) _SCREAMING_SNAKE_CASE = inputs["""candidate_labels"""] if isinstance(A , A ): _SCREAMING_SNAKE_CASE = candidate_labels.split(""",""" ) _SCREAMING_SNAKE_CASE = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(A ): _SCREAMING_SNAKE_CASE = self.tokenizer(A , return_tensors=self.framework ) _SCREAMING_SNAKE_CASE = self.image_processor(A , return_tensors=self.framework ) yield { "is_last": i == len(A ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = model_inputs.pop("""target_size""" ) _SCREAMING_SNAKE_CASE = model_inputs.pop("""candidate_label""" ) _SCREAMING_SNAKE_CASE = model_inputs.pop("""is_last""" ) _SCREAMING_SNAKE_CASE = self.model(**A ) _SCREAMING_SNAKE_CASE = {"""target_size""": target_size, """candidate_label""": candidate_label, """is_last""": is_last, **outputs} return model_outputs def snake_case_( self , A , A=0.1 , A=None ) -> str: _SCREAMING_SNAKE_CASE = [] for model_output in model_outputs: _SCREAMING_SNAKE_CASE = model_output["""candidate_label"""] _SCREAMING_SNAKE_CASE = BaseModelOutput(A ) _SCREAMING_SNAKE_CASE = self.image_processor.post_process_object_detection( outputs=A , threshold=A , target_sizes=model_output["""target_size"""] )[0] for index in outputs["scores"].nonzero(): _SCREAMING_SNAKE_CASE = outputs["""scores"""][index].item() _SCREAMING_SNAKE_CASE = self._get_bounding_box(outputs["""boxes"""][index][0] ) _SCREAMING_SNAKE_CASE = {"""score""": score, """label""": label, """box""": box} results.append(A ) _SCREAMING_SNAKE_CASE = sorted(A , key=lambda A : x["score"] , reverse=A ) if top_k: _SCREAMING_SNAKE_CASE = results[:top_k] return results def snake_case_( self , A ) -> Dict[str, int]: if self.framework != "pt": raise ValueError("""The ZeroShotObjectDetectionPipeline is only available in PyTorch.""" ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = box.int().tolist() _SCREAMING_SNAKE_CASE = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
58
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" , __lowerCamelCase ).groups()[0] class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=None , A=None ) -> int: _SCREAMING_SNAKE_CASE = file_names _SCREAMING_SNAKE_CASE = image_transform _SCREAMING_SNAKE_CASE = label_to_id def __len__( self ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.file_names[idx] _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) _SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ) if self.image_transform is not None: _SCREAMING_SNAKE_CASE = self.image_transform(A ) _SCREAMING_SNAKE_CASE = extract_label(A ) if self.label_to_id is not None: _SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) ->str: # Initialize accelerator if args.with_tracking: _SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = config["""image_size"""] if not isinstance(__lowerCamelCase , (list, tuple) ): _SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , """isdigit""" ): if args.checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _SCREAMING_SNAKE_CASE = int(args.checkpointing_steps ) else: raise ValueError( F'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _SCREAMING_SNAKE_CASE = os.path.split(__lowerCamelCase )[-1].split(""".""" )[0] accelerator.init_trackers(__lowerCamelCase , __lowerCamelCase ) # Grab all the image filenames _SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , __lowerCamelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences _SCREAMING_SNAKE_CASE = [extract_label(__lowerCamelCase ) for fname in file_names] _SCREAMING_SNAKE_CASE = list(set(__lowerCamelCase ) ) id_to_label.sort() _SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(__lowerCamelCase )} # Set the seed before splitting the data. np.random.seed(__lowerCamelCase ) torch.manual_seed(__lowerCamelCase ) torch.cuda.manual_seed_all(__lowerCamelCase ) # Split our filenames between train and validation _SCREAMING_SNAKE_CASE = np.random.permutation(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = int(0.8 * len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = random_perm[:cut] _SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop _SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(__lowerCamelCase , scale=(0.5, 1.0) ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # For evaluation, we use a deterministic Resize _SCREAMING_SNAKE_CASE = Compose([Resize(__lowerCamelCase ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = create_model("""resnet50d""" , pretrained=__lowerCamelCase , num_classes=len(__lowerCamelCase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): _SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=__lowerCamelCase , max_lr=__lowerCamelCase , epochs=__lowerCamelCase , steps_per_epoch=len(__lowerCamelCase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # We need to keep track of how many total steps we have iterated over _SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly _SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _SCREAMING_SNAKE_CASE = os.path.splitext(__lowerCamelCase )[0] if "epoch" in training_difference: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""epoch_""" , """""" ) ) + 1 _SCREAMING_SNAKE_CASE = None else: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""step_""" , """""" ) ) _SCREAMING_SNAKE_CASE = resume_step // len(__lowerCamelCase ) resume_step -= starting_epoch * len(__lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase , __lowerCamelCase ): model.train() if args.with_tracking: _SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(__lowerCamelCase , __lowerCamelCase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(__lowerCamelCase , batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowerCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = F'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) _SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 100 * eval_metric, """train_loss""": total_loss.item() / len(__lowerCamelCase ), """epoch""": epoch, } , step=__lowerCamelCase , ) if checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = F'epoch_{epoch}' if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) if args.with_tracking: accelerator.end_training() def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" , required=__lowerCamelCase , help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , ) parser.add_argument( """--output_dir""" , type=__lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=__lowerCamelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/resolve/main/config.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/config.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/config.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bloom''' UpperCamelCase = ['''past_key_values'''] UpperCamelCase = { '''num_hidden_layers''': '''n_layer''', '''num_attention_heads''': '''n_head''', } def __init__( self , A=25_0880 , A=64 , A=2 , A=8 , A=1e-5 , A=0.02 , A=True , A=1 , A=2 , A=False , A=0.0 , A=0.0 , A=1 , A=False , **A , ) -> Tuple: _SCREAMING_SNAKE_CASE = vocab_size # Backward compatibility with n_embed kwarg _SCREAMING_SNAKE_CASE = kwargs.pop("""n_embed""" , A ) _SCREAMING_SNAKE_CASE = hidden_size if n_embed is None else n_embed _SCREAMING_SNAKE_CASE = n_layer _SCREAMING_SNAKE_CASE = n_head _SCREAMING_SNAKE_CASE = layer_norm_epsilon _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pretraining_tp _SCREAMING_SNAKE_CASE = apply_residual_connection_post_layernorm _SCREAMING_SNAKE_CASE = hidden_dropout _SCREAMING_SNAKE_CASE = attention_dropout _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id _SCREAMING_SNAKE_CASE = slow_but_exact super().__init__(bos_token_id=A , eos_token_id=A , **A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = version.parse('''1.12''' ) def __init__( self , A , A = "default" , A = None , A = False , ) -> str: 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 ) -> Mapping[str, Mapping[int, str]]: _SCREAMING_SNAKE_CASE = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(A , direction="""inputs""" , inverted_values_shape=A ) _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 ) -> int: return self._config.n_layer @property def snake_case_( self ) -> int: return self._config.n_head @property def snake_case_( self ) -> float: return 1e-3 def snake_case_( self , A , A = -1 , A = -1 , A = False , A = None , ) -> Mapping[str, Any]: _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 = self._config.hidden_size // self.num_attention_heads _SCREAMING_SNAKE_CASE = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) _SCREAMING_SNAKE_CASE = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) _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 ) -> int: return 13
58
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = """Usage of script: script_name <size_of_canvas:int>""" lowercase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase ( __lowerCamelCase : int ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCamelCase )] for j in range(__lowerCamelCase )] return canvas def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->None: for i, row in enumerate(__lowerCamelCase ): for j, _ in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCamelCase ): for c, pt in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = __judge_point( __lowerCamelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) _SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. _SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def lowerCamelCase ( __lowerCamelCase : bool , __lowerCamelCase : list[list[bool]] ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. _SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: _SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: _SCREAMING_SNAKE_CASE = True elif alive > 3: _SCREAMING_SNAKE_CASE = False else: if alive == 3: _SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ , lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(["""w""", """k"""]) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
58
1
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowercase_ = datasets.logging.get_logger(__name__) lowercase_ = """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ lowercase_ = """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ lowercase_ = """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ lowercase_ = { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): '''simple docstring''' def snake_case_( self ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , ) def snake_case_( self , A ) -> Optional[Any]: # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( """Using default BLEURT-Base checkpoint for sequence maximum length 128. """ """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" ) _SCREAMING_SNAKE_CASE = """bleurt-base-128""" if self.config_name.lower() in CHECKPOINT_URLS: _SCREAMING_SNAKE_CASE = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: _SCREAMING_SNAKE_CASE = self.config_name.upper() else: raise KeyError( f'{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}' ) # download the model checkpoint specified by self.config_name and set up the scorer _SCREAMING_SNAKE_CASE = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) _SCREAMING_SNAKE_CASE = score.BleurtScorer(os.path.join(A , A ) ) def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = self.scorer.score(references=A , candidates=A ) return {"scores": scores}
58
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase_ = HUGGINGFACE_HUB_CACHE lowercase_ = """config.json""" lowercase_ = """diffusion_pytorch_model.bin""" lowercase_ = """diffusion_flax_model.msgpack""" lowercase_ = """model.onnx""" lowercase_ = """diffusion_pytorch_model.safetensors""" lowercase_ = """weights.pb""" lowercase_ = """https://huggingface.co""" lowercase_ = default_cache_path lowercase_ = """diffusers_modules""" lowercase_ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowercase_ = ["""fp16""", """non-ema"""] lowercase_ = """.self_attn"""
58
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
1
'''simple docstring''' from collections import deque def lowerCamelCase ( __lowerCamelCase : str ) ->List[str]: _SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = deque() _SCREAMING_SNAKE_CASE = [False for _ in range(__lowerCamelCase )] _SCREAMING_SNAKE_CASE = [-1 for _ in range(__lowerCamelCase )] _SCREAMING_SNAKE_CASE = index_of[:] def strong_connect(__lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Optional[Any] ): _SCREAMING_SNAKE_CASE = index # the number when this node is seen _SCREAMING_SNAKE_CASE = index # lowest rank node reachable from here index += 1 stack.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = True for w in g[v]: if index_of[w] == -1: _SCREAMING_SNAKE_CASE = strong_connect(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: _SCREAMING_SNAKE_CASE = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = stack.pop() _SCREAMING_SNAKE_CASE = False component.append(__lowerCamelCase ) while w != v: _SCREAMING_SNAKE_CASE = stack.pop() _SCREAMING_SNAKE_CASE = False component.append(__lowerCamelCase ) components.append(__lowerCamelCase ) return index _SCREAMING_SNAKE_CASE = [] for v in range(__lowerCamelCase ): if index_of[v] == -1: strong_connect(__lowerCamelCase , 0 , __lowerCamelCase ) return components def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] ) ->str: _SCREAMING_SNAKE_CASE = [[] for _ in range(__lowerCamelCase )] for u, v in edges: g[u].append(__lowerCamelCase ) return g if __name__ == "__main__": # Test lowercase_ = 7 lowercase_ = [0, 0, 1, 2, 3, 3, 4, 4, 6] lowercase_ = [1, 3, 2, 0, 1, 4, 5, 6, 5] lowercase_ = [(u, v) for u, v in zip(source, target)] lowercase_ = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
58
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = {"""openai-gpt""": """https://huggingface.co/openai-gpt/resolve/main/config.json"""} class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''openai-gpt''' UpperCamelCase = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self , A=4_0478 , A=512 , A=768 , A=12 , A=12 , A="gelu" , A=0.1 , A=0.1 , A=0.1 , A=1e-5 , A=0.02 , A="cls_index" , A=True , A=None , A=True , A=0.1 , **A , ) -> Optional[int]: _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 = afn _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 = summary_type _SCREAMING_SNAKE_CASE = summary_use_proj _SCREAMING_SNAKE_CASE = summary_activation _SCREAMING_SNAKE_CASE = summary_first_dropout _SCREAMING_SNAKE_CASE = summary_proj_to_labels super().__init__(**A )
58
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowercase_ = logging.getLogger(__name__) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) lowercase_ = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, """rb""") as fp: lowercase_ = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowercase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowercase_ = [0] * args.vocab_size for k, v in counter.items(): lowercase_ = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int = 1000 ) ->int: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 1, 1 _SCREAMING_SNAKE_CASE = [] for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE = prev_numerator + 2 * prev_denominator _SCREAMING_SNAKE_CASE = prev_numerator + prev_denominator if len(str(__lowerCamelCase ) ) > len(str(__lowerCamelCase ) ): result.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = numerator _SCREAMING_SNAKE_CASE = denominator return len(__lowerCamelCase ) if __name__ == "__main__": print(f"""{solution() = }""")
58
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
58
1
'''simple docstring''' import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration lowercase_ = 500_000 lowercase_ , lowercase_ = os.path.split(__file__) lowercase_ = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json""")) @get_duration def lowerCamelCase ( __lowerCamelCase : datasets.Dataset , **__lowerCamelCase : Any ) ->Optional[int]: _SCREAMING_SNAKE_CASE = dataset.map(**__lowerCamelCase ) @get_duration def lowerCamelCase ( __lowerCamelCase : datasets.Dataset , **__lowerCamelCase : Tuple ) ->List[str]: _SCREAMING_SNAKE_CASE = dataset.filter(**__lowerCamelCase ) def lowerCamelCase ( ) ->Any: _SCREAMING_SNAKE_CASE = {"""num examples""": SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: _SCREAMING_SNAKE_CASE = datasets.Features({"""text""": datasets.Value("""string""" ), """numbers""": datasets.Value("""float32""" )} ) _SCREAMING_SNAKE_CASE = generate_example_dataset( os.path.join(__lowerCamelCase , """dataset.arrow""" ) , __lowerCamelCase , num_examples=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = transformers.AutoTokenizer.from_pretrained("""bert-base-cased""" , use_fast=__lowerCamelCase ) def tokenize(__lowerCamelCase : List[Any] ): return tokenizer(examples["""text"""] ) _SCREAMING_SNAKE_CASE = map(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=lambda __lowerCamelCase : None , batched=__lowerCamelCase ) with dataset.formatted_as(type="""numpy""" ): _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=lambda __lowerCamelCase : None , batched=__lowerCamelCase ) with dataset.formatted_as(type="""pandas""" ): _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=lambda __lowerCamelCase : None , batched=__lowerCamelCase ) with dataset.formatted_as(type="""torch""" , columns="""numbers""" ): _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=lambda __lowerCamelCase : None , batched=__lowerCamelCase ) with dataset.formatted_as(type="""tensorflow""" , columns="""numbers""" ): _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=lambda __lowerCamelCase : None , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = map(__lowerCamelCase , function=__lowerCamelCase , batched=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = filter(__lowerCamelCase ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(__lowerCamelCase , """wb""" ) as f: f.write(json.dumps(__lowerCamelCase ).encode("""utf-8""" ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
58
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(A , nn.Convad ) or isinstance(A , nn.BatchNormad ) if has_not_submodules: self.traced.append(A ) def __call__( self , A ) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(A ) [x.remove() for x in self.handles] return self @property def snake_case_( self ) -> str: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 0 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def __call__( self , A ) -> List[str]: _SCREAMING_SNAKE_CASE = Tracker(self.dest )(A ).parametrized _SCREAMING_SNAKE_CASE = Tracker(self.src )(A ).parametrized _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.src_skip , A ) ) _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.dest_skip , A ) ) if len(A ) != len(A ): raise Exception( f'Numbers of operations are different. Source module has {len(A )} operations while' f' destination module has {len(A )}.' ) for dest_m, src_m in zip(A , A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : ResNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True ) ->int: print(F'Converting {name}...' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ResNetForImageClassification(__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) assert torch.allclose(from_model(__lowerCamelCase ) , our_model(__lowerCamelCase ).logits ), "The model logits don't match the original one." _SCREAMING_SNAKE_CASE = F'resnet{"-".join(name.split("resnet" ) )}' print(__lowerCamelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=__lowerCamelCase , ) # we can use the convnext one _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=__lowerCamelCase , ) print(F'Pushed {checkpoint_name}' ) def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ) ->Any: _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = (1, num_labels) _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(__lowerCamelCase , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
58
1
'''simple docstring''' import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class a_ : '''simple docstring''' @staticmethod def snake_case_( *A , **A ) -> Dict: pass def lowerCamelCase ( __lowerCamelCase : Image ) ->str: _SCREAMING_SNAKE_CASE = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = DepthEstimationPipeline(model=A , image_processor=A ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def snake_case_( self , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = depth_estimator("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) self.assertEqual({"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )} , A ) import datasets _SCREAMING_SNAKE_CASE = datasets.load_dataset("""hf-internal-testing/fixtures_image_utils""" , """image""" , split="""test""" ) _SCREAMING_SNAKE_CASE = depth_estimator( [ Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ), """http://images.cocodataset.org/val2017/000000039769.jpg""", # RGBA dataset[0]["""file"""], # LA dataset[1]["""file"""], # L dataset[2]["""file"""], ] ) self.assertEqual( [ {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, {"""predicted_depth""": ANY(torch.Tensor ), """depth""": ANY(Image.Image )}, ] , A , ) @require_tf @unittest.skip("""Depth estimation is not implemented in TF""" ) def snake_case_( self ) -> Optional[int]: pass @slow @require_torch def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = """Intel/dpt-large""" _SCREAMING_SNAKE_CASE = pipeline("""depth-estimation""" , model=A ) _SCREAMING_SNAKE_CASE = depth_estimator("""http://images.cocodataset.org/val2017/000000039769.jpg""" ) _SCREAMING_SNAKE_CASE = hashimage(outputs["""depth"""] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs["""predicted_depth"""].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs["""predicted_depth"""].min().item() ) , 2.662 ) @require_torch def snake_case_( self ) -> int: # This is highly irregular to have no small tests. self.skipTest("""There is not hf-internal-testing tiny model for either GLPN nor DPT""" )
58
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[int]: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += [key] setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator def lowerCamelCase ( *__lowerCamelCase : List[str] ) ->Dict: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += keys setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator class a_ ( snake_case_ ): '''simple docstring''' def __new__( cls , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = super().__new__(cls , A , A , A ) if not hasattr(A , """key_handler""" ): setattr(A , """key_handler""" , {} ) setattr(A , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE = getattr(A , """handle_key""" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def snake_case_( cls ) -> str: _SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE = ord(A ) _SCREAMING_SNAKE_CASE = cls.key_handler.get(A ) if handler: _SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def lowerCamelCase ( cls : Any ) ->Dict: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
58
1
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def snake_case_( self , A , A , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(A , nn.Convad ) or isinstance(A , nn.BatchNormad ) if has_not_submodules: self.traced.append(A ) def __call__( self , A ) -> int: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(A ) [x.remove() for x in self.handles] return self @property def snake_case_( self ) -> List[Any]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 1 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = True def __call__( self , A ) -> int: _SCREAMING_SNAKE_CASE = Tracker(self.dest )(A ).parametrized _SCREAMING_SNAKE_CASE = Tracker(self.src )(A ).parametrized _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.src_skip , A ) ) _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.dest_skip , A ) ) if len(A ) != len(A ) and self.raise_if_mismatch: raise Exception( f'Numbers of operations are different. Source module has {len(A )} operations while' f' destination module has {len(A )}.' ) for dest_m, src_m in zip(A , A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> List[str]: super().__init__() _SCREAMING_SNAKE_CASE = [] # - get the stem feature_blocks.append(("""conv1""", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("""block""" ), f'Unexpected layer name {k}' _SCREAMING_SNAKE_CASE = len(A ) + 1 feature_blocks.append((f'res{block_index}', v) ) _SCREAMING_SNAKE_CASE = nn.ModuleDict(A ) def snake_case_( self , A ) -> Tuple: return get_trunk_forward_outputs( A , out_feat_keys=A , feature_blocks=self._feature_blocks , ) class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = x.split("""-""" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self , A ) -> Callable[[], Tuple[nn.Module, Dict]]: # default to timm! if x not in self: _SCREAMING_SNAKE_CASE = self.convert_name_to_timm(A ) _SCREAMING_SNAKE_CASE = partial(lambda: (timm.create_model(A , pretrained=A ).eval(), None) ) else: _SCREAMING_SNAKE_CASE = super().__getitem__(A ) return val class a_ ( snake_case_ ): '''simple docstring''' def __getitem__( self , A ) -> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: _SCREAMING_SNAKE_CASE = RegNetModel else: _SCREAMING_SNAKE_CASE = RegNetForImageClassification return val def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : List[Tuple[str, str]] ) ->Tuple: for from_key, to_key in keys: _SCREAMING_SNAKE_CASE = from_state_dict[from_key].clone() print(F'Copied key={from_key} to={to_key}' ) return to_state_dict def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Callable[[], nn.Module] , __lowerCamelCase : Callable[[], nn.Module] , __lowerCamelCase : RegNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True , ) ->Dict: print(F'Converting {name}...' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = from_model_func() _SCREAMING_SNAKE_CASE = our_model_func(__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase , raise_if_mismatch=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) if from_state_dict is not None: _SCREAMING_SNAKE_CASE = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: _SCREAMING_SNAKE_CASE = [("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")] _SCREAMING_SNAKE_CASE = manually_copy_vissl_head(__lowerCamelCase , our_model.state_dict() , __lowerCamelCase ) our_model.load_state_dict(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = our_model(__lowerCamelCase , output_hidden_states=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = ( our_outputs.logits if isinstance(__lowerCamelCase , __lowerCamelCase ) else our_outputs.last_hidden_state ) _SCREAMING_SNAKE_CASE = from_model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = from_output[-1] if type(__lowerCamelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: _SCREAMING_SNAKE_CASE = our_outputs.hidden_states[-1] assert torch.allclose(__lowerCamelCase , __lowerCamelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="""Add model""" , use_temp_dir=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = 224 if """seer""" not in name else 384 # we can use the convnext one _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" , size=__lowerCamelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="""Add image processor""" , use_temp_dir=__lowerCamelCase , ) print(F'Pushed {name}' ) def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ) ->List[Any]: _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = (1, num_labels) _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = json.load(open(cached_download(hf_hub_url(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = { """regnet-x-002""": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="""x""" ), """regnet-x-004""": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="""x""" ), """regnet-x-006""": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="""x""" ), """regnet-x-008""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="""x""" ), """regnet-x-016""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="""x""" ), """regnet-x-032""": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="""x""" ), """regnet-x-040""": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="""x""" ), """regnet-x-064""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="""x""" ), """regnet-x-080""": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="""x""" ), """regnet-x-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="""x""" ), """regnet-x-160""": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="""x""" ), """regnet-x-320""": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="""x""" ), # y variant """regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), """regnet-y-004""": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), """regnet-y-006""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), """regnet-y-008""": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), """regnet-y-016""": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), """regnet-y-032""": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), """regnet-y-040""": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), """regnet-y-064""": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), """regnet-y-080""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), """regnet-y-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), """regnet-y-160""": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), """regnet-y-320""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 """regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer""": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer""": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), # finetuned on imagenet """regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), } _SCREAMING_SNAKE_CASE = NameToOurModelFuncMap() _SCREAMING_SNAKE_CASE = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(__lowerCamelCase : str , __lowerCamelCase : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: _SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(__lowerCamelCase , model_dir=str(__lowerCamelCase ) , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = model_func() # check if we have a head, if yes add it _SCREAMING_SNAKE_CASE = files["""classy_state_dict"""]["""base_model"""]["""model"""] _SCREAMING_SNAKE_CASE = model_state_dict["""trunk"""] model.load_state_dict(__lowerCamelCase ) return model.eval(), model_state_dict["heads"] # pretrained _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch""" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch""" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) _SCREAMING_SNAKE_CASE = partial( __lowerCamelCase , """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch""" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( __lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( __lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported regnet* architecture,""" """ currently: regnetx-*, regnety-*. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
58
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": operator.gt, } def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ) ->Tuple: if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) ->None: _SCREAMING_SNAKE_CASE = F'\n{hint}' if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = requirement, None, None else: _SCREAMING_SNAKE_CASE = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F' got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE = {} for w in want_range: _SCREAMING_SNAKE_CASE = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F' but got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->str: _SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
58
1
'''simple docstring''' from __future__ import annotations lowercase_ = 10 def lowerCamelCase ( __lowerCamelCase : list[int] ) ->list[int]: _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = max(__lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _SCREAMING_SNAKE_CASE = [[] for _ in range(__lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _SCREAMING_SNAKE_CASE = int((i / placement) % RADIX ) buckets[tmp].append(__lowerCamelCase ) # put each buckets' contents into list_of_ints _SCREAMING_SNAKE_CASE = 0 for b in range(__lowerCamelCase ): for i in buckets[b]: _SCREAMING_SNAKE_CASE = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _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]: _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_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(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 lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , 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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , 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 ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
1
'''simple docstring''' from sklearn.metrics import matthews_corrcoef import datasets lowercase_ = """ Compute the Matthews correlation coefficient (MCC) The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary and multiclass classifications. It takes into account true and false positives and negatives and is generally regarded as a balanced measure which can be used even if the classes are of very different sizes. The MCC is in essence a correlation coefficient value between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 an average random prediction and -1 an inverse prediction. The statistic is also known as the phi coefficient. [source: Wikipedia] """ lowercase_ = """ Args: predictions (list of int): Predicted labels, as returned by a model. references (list of int): Ground truth labels. sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`. Returns: matthews_correlation (dict containing float): Matthews correlation. Examples: Example 1, a basic example with only predictions and references as inputs: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3]) >>> print(round(results['matthews_correlation'], 2)) 0.54 Example 2, the same example as above, but also including sample weights: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 3, 1, 1, 1, 2]) >>> print(round(results['matthews_correlation'], 2)) 0.1 Example 3, the same example as above, but with sample weights that cause a negative correlation: >>> matthews_metric = datasets.load_metric(\"matthews_correlation\") >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2], ... predictions=[1, 2, 2, 0, 3, 3], ... sample_weight=[0.5, 1, 0, 0, 0, 1]) >>> print(round(results['matthews_correlation'], 2)) -0.25 """ lowercase_ = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): '''simple docstring''' def snake_case_( self ) -> Any: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""int32""" ), """references""": datasets.Value("""int32""" ), } ) , reference_urls=[ """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html""" ] , ) def snake_case_( self , A , A , A=None ) -> Tuple: return { "matthews_correlation": float(matthews_corrcoef(A , A , sample_weight=A ) ), }
58
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: 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(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
1
'''simple docstring''' import mpmath # for roots of unity import numpy as np class a_ : '''simple docstring''' def __init__( self , A=None , A=None ) -> Optional[int]: # Input as list _SCREAMING_SNAKE_CASE = list(poly_a or [0] )[:] _SCREAMING_SNAKE_CASE = list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() _SCREAMING_SNAKE_CASE = len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() _SCREAMING_SNAKE_CASE = len(self.polyB ) # Add 0 to make lengths equal a power of 2 _SCREAMING_SNAKE_CASE = int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform _SCREAMING_SNAKE_CASE = complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product _SCREAMING_SNAKE_CASE = self.__multiply() def snake_case_( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = [[x] for x in self.polyA] if which == """A""" else [[x] for x in self.polyB] # Corner case if len(A ) <= 1: return dft[0] # _SCREAMING_SNAKE_CASE = self.c_max_length // 2 while next_ncol > 0: _SCREAMING_SNAKE_CASE = [[] for i in range(A )] _SCREAMING_SNAKE_CASE = self.root**next_ncol # First half of next step _SCREAMING_SNAKE_CASE = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(A ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step _SCREAMING_SNAKE_CASE = 1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(A ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update _SCREAMING_SNAKE_CASE = new_dft _SCREAMING_SNAKE_CASE = next_ncol // 2 return dft[0] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.__dft("""A""" ) _SCREAMING_SNAKE_CASE = self.__dft("""B""" ) _SCREAMING_SNAKE_CASE = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT _SCREAMING_SNAKE_CASE = 2 while next_ncol <= self.c_max_length: _SCREAMING_SNAKE_CASE = [[] for i in range(A )] _SCREAMING_SNAKE_CASE = self.root ** (next_ncol // 2) _SCREAMING_SNAKE_CASE = 1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update _SCREAMING_SNAKE_CASE = new_inverse_c next_ncol *= 2 # Unpack _SCREAMING_SNAKE_CASE = [round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self ) -> Tuple: _SCREAMING_SNAKE_CASE = """A = """ + """ + """.join( f'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A] ) ) _SCREAMING_SNAKE_CASE = """B = """ + """ + """.join( f'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B] ) ) _SCREAMING_SNAKE_CASE = """A*B = """ + """ + """.join( f'{coef}*x^{i}' for coef, i in enumerate(self.product ) ) return f'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase_ = None lowercase_ = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase_ = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class a_ : '''simple docstring''' UpperCamelCase = True UpperCamelCase = None # Automatically constructed UpperCamelCase = "PIL.Image.Image" UpperCamelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCamelCase = field(default='''Image''' , init=snake_case_ , repr=snake_case_ ) def __call__( self ) -> Tuple: return self.pa_type def snake_case_( self , A ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(A , A ): _SCREAMING_SNAKE_CASE = np.array(A ) if isinstance(A , A ): return {"path": value, "bytes": None} elif isinstance(A , A ): return {"path": None, "bytes": value} elif isinstance(A , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(A ) elif isinstance(A , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(A ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def snake_case_( self , A , A=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(A ): _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) else: _SCREAMING_SNAKE_CASE = path.split("""::""" )[-1] try: _SCREAMING_SNAKE_CASE = string_to_dict(A , config.HUB_DATASETS_URL )["""repo_id"""] _SCREAMING_SNAKE_CASE = token_per_repo_id.get(A ) except ValueError: _SCREAMING_SNAKE_CASE = None with xopen(A , """rb""" , use_auth_token=A ) as f: _SCREAMING_SNAKE_CASE = BytesIO(f.read() ) _SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: _SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case_( self , A ) -> pa.StructArray: if pa.types.is_string(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""bytes""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""path""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(A ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def snake_case_( self , A ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(A ): with xopen(A , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() return bytes_ _SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(A ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def lowerCamelCase ( ) ->List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() _SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->bytes: _SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): _SCREAMING_SNAKE_CASE = image.format else: _SCREAMING_SNAKE_CASE = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->dict: if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : np.ndarray ) ->dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) _SCREAMING_SNAKE_CASE = array.dtype _SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER _SCREAMING_SNAKE_CASE = dtype.kind _SCREAMING_SNAKE_CASE = dtype.itemsize _SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _SCREAMING_SNAKE_CASE = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: _SCREAMING_SNAKE_CASE = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: _SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.dtype(__lowerCamelCase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) _SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) ->List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
58
1
'''simple docstring''' import argparse import hashlib # hashlib is only used inside the Test class import struct class a_ : '''simple docstring''' def __init__( self , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = data _SCREAMING_SNAKE_CASE = [0X6745_2301, 0Xefcd_ab89, 0X98ba_dcfe, 0X1032_5476, 0Xc3d2_e1f0] @staticmethod def snake_case_( A , A ) -> List[str]: return ((n << b) | (n >> (32 - b))) & 0Xffff_ffff def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = b"""\x80""" + b"""\x00""" * (63 - (len(self.data ) + 8) % 64) _SCREAMING_SNAKE_CASE = self.data + padding + struct.pack(""">Q""" , 8 * len(self.data ) ) return padded_data def snake_case_( self ) -> str: return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def snake_case_( self , A ) -> int: _SCREAMING_SNAKE_CASE = list(struct.unpack(""">16L""" , A ) ) + [0] * 64 for i in range(16 , 80 ): _SCREAMING_SNAKE_CASE = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.padding() _SCREAMING_SNAKE_CASE = self.split_blocks() for block in self.blocks: _SCREAMING_SNAKE_CASE = self.expand_block(A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.h for i in range(0 , 80 ): if 0 <= i < 20: _SCREAMING_SNAKE_CASE = (b & c) | ((~b) & d) _SCREAMING_SNAKE_CASE = 0X5a82_7999 elif 20 <= i < 40: _SCREAMING_SNAKE_CASE = b ^ c ^ d _SCREAMING_SNAKE_CASE = 0X6ed9_eba1 elif 40 <= i < 60: _SCREAMING_SNAKE_CASE = (b & c) | (b & d) | (c & d) _SCREAMING_SNAKE_CASE = 0X8f1b_bcdc elif 60 <= i < 80: _SCREAMING_SNAKE_CASE = b ^ c ^ d _SCREAMING_SNAKE_CASE = 0Xca62_c1d6 _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( self.rotate(A , 5 ) + f + e + k + expanded_block[i] & 0Xffff_ffff, a, self.rotate(A , 30 ), c, d, ) _SCREAMING_SNAKE_CASE = ( self.h[0] + a & 0Xffff_ffff, self.h[1] + b & 0Xffff_ffff, self.h[2] + c & 0Xffff_ffff, self.h[3] + d & 0Xffff_ffff, self.h[4] + e & 0Xffff_ffff, ) return ("{:08x}" * 5).format(*self.h ) def lowerCamelCase ( ) ->Optional[Any]: _SCREAMING_SNAKE_CASE = B"""Test String""" assert SHAaHash(__lowerCamelCase ).final_hash() == hashlib.shaa(__lowerCamelCase ).hexdigest() # noqa: S324 def lowerCamelCase ( ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Process some strings or files""" ) parser.add_argument( """--string""" , dest="""input_string""" , default="""Hello World!! Welcome to Cryptography""" , help="""Hash the string""" , ) parser.add_argument("""--file""" , dest="""input_file""" , help="""Hash contents of a file""" ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() else: _SCREAMING_SNAKE_CASE = bytes(__lowerCamelCase , """utf-8""" ) print(SHAaHash(__lowerCamelCase ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
58
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''data2vec-text''' def __init__( self , A=3_0522 , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=1 , A=0 , A=2 , A="absolute" , A=True , A=None , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = classifier_dropout class a_ ( snake_case_ ): '''simple docstring''' @property def snake_case_( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
58
1
'''simple docstring''' import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = XGLMTokenizer UpperCamelCase = XGLMTokenizerFast UpperCamelCase = True UpperCamelCase = True def snake_case_( self ) -> Tuple: super().setUp() # We have a SentencePiece fixture for testing _SCREAMING_SNAKE_CASE = XGLMTokenizer(A , keep_accents=A ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case_( self ) -> Optional[int]: _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 ) -> Dict: _SCREAMING_SNAKE_CASE = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<s>""" ) self.assertEqual(vocab_keys[1] , """<pad>""" ) self.assertEqual(len(A ) , 1008 ) def snake_case_( self ) -> Union[str, Any]: self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = XGLMTokenizer(A , keep_accents=A ) _SCREAMING_SNAKE_CASE = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(A , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _SCREAMING_SNAKE_CASE = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) self.assertListEqual( A , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """9""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """é""", """.""", ] , ) _SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(A ) self.assertListEqual( A , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) _SCREAMING_SNAKE_CASE = tokenizer.convert_ids_to_tokens(A ) self.assertListEqual( A , [ SPIECE_UNDERLINE + """I""", SPIECE_UNDERLINE + """was""", SPIECE_UNDERLINE + """b""", """or""", """n""", SPIECE_UNDERLINE + """in""", SPIECE_UNDERLINE + """""", """<unk>""", """2""", """0""", """0""", """0""", """,""", SPIECE_UNDERLINE + """and""", SPIECE_UNDERLINE + """this""", SPIECE_UNDERLINE + """is""", SPIECE_UNDERLINE + """f""", """al""", """s""", """<unk>""", """.""", ] , ) @cached_property def snake_case_( self ) -> str: return XGLMTokenizer.from_pretrained("""facebook/xglm-564M""" ) def snake_case_( self ) -> int: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(A , f.name ) _SCREAMING_SNAKE_CASE = XGLMTokenizer(f.name , keep_accents=A ) _SCREAMING_SNAKE_CASE = pickle.dumps(A ) pickle.loads(A ) def snake_case_( self ) -> List[str]: if not self.test_rust_tokenizer: return _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE = """I was born in 92000, and this is falsé.""" _SCREAMING_SNAKE_CASE = tokenizer.tokenize(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(A ) self.assertListEqual(A , A ) _SCREAMING_SNAKE_CASE = tokenizer.encode(A , add_special_tokens=A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A , add_special_tokens=A ) self.assertListEqual(A , A ) _SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() _SCREAMING_SNAKE_CASE = tokenizer.encode(A ) _SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A ) self.assertListEqual(A , A ) @slow def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = """Hello World!""" _SCREAMING_SNAKE_CASE = [2, 3_1227, 4447, 35] self.assertListEqual(A , self.big_tokenizer.encode(A ) ) @slow def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = ( """This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will""" """ add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth""" ) # fmt: off _SCREAMING_SNAKE_CASE = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 7_1630, 2_8085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 1_3675, 377, 652, 7580, 1_0341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 20_2277, 1_7892, 33, 60, 87, 4, 3234, 157, 61, 2667, 5_2376, 19, 88, 23, 735] # fmt: on self.assertListEqual(A , self.big_tokenizer.encode(A ) ) @slow def snake_case_( self ) -> List[str]: # fmt: off _SCREAMING_SNAKE_CASE = { """input_ids""": [[2, 10_8825, 1163, 15, 8_8010, 473, 1_5898, 157, 1_3672, 1857, 312, 8, 23_8021, 1163, 53, 1_3672, 1857, 312, 8, 5_3283, 18_2396, 8, 1_8566, 16, 3_6733, 4101, 8, 230, 24_4017, 12_2553, 7, 15, 13_2597, 4, 293, 1_2511, 7610, 4, 3414, 13_2597, 9, 4, 3_2361, 362, 4, 734, 2_8512, 3_2569, 18, 4, 3_2361, 2_6096, 1_4982, 73, 1_8715, 2_1433, 23_5261, 15, 492, 1_2427, 16, 53, 1_8715, 2_1433, 6_5454, 15, 2_3659, 563, 16, 278, 597, 2843, 595, 7931, 18_2396, 6_4186, 22, 886, 595, 13_2981, 53, 2_5540, 3449, 4_3982, 3_9901, 5951, 878, 330, 4, 2_7694, 8_0269, 312, 53, 6517, 1_1780, 611, 2_0408, 5], [2, 6, 13_2597, 67, 4_2897, 33, 592, 8, 16_3729, 2_5540, 361, 13_6997, 10_9514, 17_3230, 7, 501, 60, 10_2913, 196, 5631, 235, 6_3243, 473, 6, 23_1757, 74, 5277, 7905, 53, 3095, 3_7317, 22, 454, 18_3874, 5], [2, 268, 3_1298, 4_6530, 6, 13_2935, 4_3831, 7, 597, 32, 24, 3688, 9865, 5]], """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]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A , model_name="""facebook/xglm-564M""" , padding=A , )
58
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ) ->Union[str, Any]: for attribute in key.split(""".""" ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: _SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE = value elif weight_type == "bias": _SCREAMING_SNAKE_CASE = value else: _SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowerCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ) ->Any: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = fairseq_model.state_dict() _SCREAMING_SNAKE_CASE = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) _SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): _SCREAMING_SNAKE_CASE = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): _SCREAMING_SNAKE_CASE = True if "*" in mapped_key: _SCREAMING_SNAKE_CASE = name.split(__lowerCamelCase )[0].split(""".""" )[-2] _SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: _SCREAMING_SNAKE_CASE = """weight_v""" elif "weight" in name: _SCREAMING_SNAKE_CASE = """weight""" elif "bias" in name: _SCREAMING_SNAKE_CASE = """bias""" else: _SCREAMING_SNAKE_CASE = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(F'Unused weights: {unused_weights}' ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] _SCREAMING_SNAKE_CASE = name.split(""".""" ) _SCREAMING_SNAKE_CASE = int(items[0] ) _SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Union[str, Any]=True ) ->Optional[int]: if config_path is not None: _SCREAMING_SNAKE_CASE = HubertConfig.from_pretrained(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertConfig() if is_finetuned: if dict_path: _SCREAMING_SNAKE_CASE = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _SCREAMING_SNAKE_CASE = target_dict.pad_index _SCREAMING_SNAKE_CASE = target_dict.bos_index _SCREAMING_SNAKE_CASE = target_dict.eos_index _SCREAMING_SNAKE_CASE = len(target_dict.symbols ) _SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == """layer""" else False _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = HubertForCTC(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertModel(__lowerCamelCase ) if is_finetuned: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _SCREAMING_SNAKE_CASE = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowercase_ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
58
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB 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 # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowercase_ = { """configuration_cpmant""": ["""CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CpmAntConfig"""], """tokenization_cpmant""": ["""CpmAntTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST""", """CpmAntForCausalLM""", """CpmAntModel""", """CpmAntPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def lowerCamelCase ( __lowerCamelCase : str ) ->str: if not sentence: return "" _SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , __lowerCamelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int = 400_0000 ) ->int: _SCREAMING_SNAKE_CASE = [0, 1] _SCREAMING_SNAKE_CASE = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 _SCREAMING_SNAKE_CASE = 0 for j in range(len(__lowerCamelCase ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
1
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any]=0.999 , __lowerCamelCase : Dict="cosine" , ) ->Tuple: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCamelCase : int ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCamelCase : List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) _SCREAMING_SNAKE_CASE = [] for i in range(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = i / num_diffusion_timesteps _SCREAMING_SNAKE_CASE = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCamelCase ) / alpha_bar_fn(__lowerCamelCase ) , __lowerCamelCase ) ) return torch.tensor(__lowerCamelCase , dtype=torch.floataa ) class a_ ( snake_case_ , snake_case_ ): '''simple docstring''' UpperCamelCase = [e.name for e in KarrasDiffusionSchedulers] UpperCamelCase = 2 @register_to_config def __init__( self , A = 1000 , A = 0.0_0085 , A = 0.012 , A = "linear" , A = None , A = "epsilon" , A = "linspace" , A = 0 , ) -> Dict: if trained_betas is not None: _SCREAMING_SNAKE_CASE = torch.tensor(A , dtype=torch.floataa ) elif beta_schedule == "linear": _SCREAMING_SNAKE_CASE = torch.linspace(A , A , A , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _SCREAMING_SNAKE_CASE = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , A , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _SCREAMING_SNAKE_CASE = betas_for_alpha_bar(A ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) _SCREAMING_SNAKE_CASE = 1.0 - self.betas _SCREAMING_SNAKE_CASE = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(A , A , A ) def snake_case_( self , A , A=None ) -> Union[str, Any]: if schedule_timesteps is None: _SCREAMING_SNAKE_CASE = self.timesteps _SCREAMING_SNAKE_CASE = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _SCREAMING_SNAKE_CASE = 1 if len(A ) > 1 else 0 else: _SCREAMING_SNAKE_CASE = timestep.cpu().item() if torch.is_tensor(A ) else timestep _SCREAMING_SNAKE_CASE = self._index_counter[timestep_int] return indices[pos].item() @property def snake_case_( self ) -> Tuple: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def snake_case_( self , A , A , ) -> torch.FloatTensor: _SCREAMING_SNAKE_CASE = self.index_for_timestep(A ) if self.state_in_first_order: _SCREAMING_SNAKE_CASE = self.sigmas[step_index] else: _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index] _SCREAMING_SNAKE_CASE = sample / ((sigma**2 + 1) ** 0.5) return sample def snake_case_( self , A , A = None , A = None , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = num_inference_steps _SCREAMING_SNAKE_CASE = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _SCREAMING_SNAKE_CASE = np.linspace(0 , num_train_timesteps - 1 , A , dtype=A )[::-1].copy() elif self.config.timestep_spacing == "leading": _SCREAMING_SNAKE_CASE = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _SCREAMING_SNAKE_CASE = (np.arange(0 , A ) * step_ratio).round()[::-1].copy().astype(A ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _SCREAMING_SNAKE_CASE = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _SCREAMING_SNAKE_CASE = (np.arange(A , 0 , -step_ratio )).round().copy().astype(A ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) _SCREAMING_SNAKE_CASE = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _SCREAMING_SNAKE_CASE = torch.from_numpy(np.log(A ) ).to(A ) _SCREAMING_SNAKE_CASE = np.interp(A , np.arange(0 , len(A ) ) , A ) _SCREAMING_SNAKE_CASE = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(device=A ) # interpolate sigmas _SCREAMING_SNAKE_CASE = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() _SCREAMING_SNAKE_CASE = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) _SCREAMING_SNAKE_CASE = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(A ).startswith("""mps""" ): # mps does not support float64 _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(A , dtype=torch.floataa ) else: _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(A ) # interpolate timesteps _SCREAMING_SNAKE_CASE = self.sigma_to_t(A ).to(A , dtype=timesteps.dtype ) _SCREAMING_SNAKE_CASE = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() _SCREAMING_SNAKE_CASE = torch.cat([timesteps[:1], interleaved_timesteps] ) _SCREAMING_SNAKE_CASE = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _SCREAMING_SNAKE_CASE = defaultdict(A ) def snake_case_( self , A ) -> Optional[Any]: # get log sigma _SCREAMING_SNAKE_CASE = sigma.log() # get distribution _SCREAMING_SNAKE_CASE = log_sigma - self.log_sigmas[:, None] # get sigmas range _SCREAMING_SNAKE_CASE = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) _SCREAMING_SNAKE_CASE = low_idx + 1 _SCREAMING_SNAKE_CASE = self.log_sigmas[low_idx] _SCREAMING_SNAKE_CASE = self.log_sigmas[high_idx] # interpolate sigmas _SCREAMING_SNAKE_CASE = (low - log_sigma) / (low - high) _SCREAMING_SNAKE_CASE = w.clamp(0 , 1 ) # transform interpolation to time range _SCREAMING_SNAKE_CASE = (1 - w) * low_idx + w * high_idx _SCREAMING_SNAKE_CASE = t.view(sigma.shape ) return t @property def snake_case_( self ) -> int: return self.sample is None def snake_case_( self , A , A , A , A = True , ) -> Union[SchedulerOutput, Tuple]: _SCREAMING_SNAKE_CASE = self.index_for_timestep(A ) # advance index counter by 1 _SCREAMING_SNAKE_CASE = timestep.cpu().item() if torch.is_tensor(A ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _SCREAMING_SNAKE_CASE = self.sigmas[step_index] _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index + 1] _SCREAMING_SNAKE_CASE = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method _SCREAMING_SNAKE_CASE = self.sigmas[step_index - 1] _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index] _SCREAMING_SNAKE_CASE = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _SCREAMING_SNAKE_CASE = sigma_hat if self.state_in_first_order else sigma_interpol _SCREAMING_SNAKE_CASE = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _SCREAMING_SNAKE_CASE = sigma_hat if self.state_in_first_order else sigma_interpol _SCREAMING_SNAKE_CASE = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("""prediction_type not implemented yet: sample""" ) else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _SCREAMING_SNAKE_CASE = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _SCREAMING_SNAKE_CASE = sigma_interpol - sigma_hat # store for 2nd order step _SCREAMING_SNAKE_CASE = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order _SCREAMING_SNAKE_CASE = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep _SCREAMING_SNAKE_CASE = sigma_next - sigma_hat _SCREAMING_SNAKE_CASE = self.sample _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A ) def snake_case_( self , A , A , A , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples _SCREAMING_SNAKE_CASE = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A ): # mps does not support float64 _SCREAMING_SNAKE_CASE = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _SCREAMING_SNAKE_CASE = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _SCREAMING_SNAKE_CASE = self.timesteps.to(original_samples.device ) _SCREAMING_SNAKE_CASE = timesteps.to(original_samples.device ) _SCREAMING_SNAKE_CASE = [self.index_for_timestep(A , A ) for t in timesteps] _SCREAMING_SNAKE_CASE = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _SCREAMING_SNAKE_CASE = sigma.unsqueeze(-1 ) _SCREAMING_SNAKE_CASE = original_samples + noise * sigma return noisy_samples def __len__( self ) -> str: return self.config.num_train_timesteps
58
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any]=8 ) ->Tuple: _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A , A , ) -> Union[str, Any]: super().__init__() self.register_modules( unet=A , scheduler=A , movq=A , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_( self , A , A , A , A , A , A ) -> Union[str, Any]: if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A , device=A , dtype=A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(A ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_( self , A=0 ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A , A ) def snake_case_( self , A=0 ) -> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(A , A , prev_module_hook=A ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_( self ) -> Tuple: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self , A , A , A = 512 , A = 512 , A = 100 , A = 4.0 , A = 1 , A = None , A = None , A = "pil" , A = True , ) -> List[str]: _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A ) self.scheduler.set_timesteps(A , device=A ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(A , A , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A , A , A , self.scheduler , ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE = self.unet( sample=A , timestep=A , encoder_hidden_states=A , added_cond_kwargs=A , return_dict=A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( A , A , A , generator=A , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(A , force_not_quantize=A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
58
1
'''simple docstring''' from copy import deepcopy from typing import Optional, Union import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, is_tf_available, is_torch_available if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = ['''image_processor'''] UpperCamelCase = '''SamImageProcessor''' def __init__( self , A ) -> Any: super().__init__(A ) _SCREAMING_SNAKE_CASE = self.image_processor _SCREAMING_SNAKE_CASE = -10 _SCREAMING_SNAKE_CASE = self.image_processor.size["""longest_edge"""] def __call__( self , A=None , A=None , A=None , A=None , A = None , **A , ) -> BatchEncoding: _SCREAMING_SNAKE_CASE = self.image_processor( A , return_tensors=A , **A , ) # pop arguments that are not used in the foward but used nevertheless _SCREAMING_SNAKE_CASE = encoding_image_processor["""original_sizes"""] if hasattr(A , """numpy""" ): # Checks if Torch or TF tensor _SCREAMING_SNAKE_CASE = original_sizes.numpy() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._check_and_preprocess_points( input_points=A , input_labels=A , input_boxes=A , ) _SCREAMING_SNAKE_CASE = self._normalize_and_convert( A , A , input_points=A , input_labels=A , input_boxes=A , return_tensors=A , ) return encoding_image_processor def snake_case_( self , A , A , A=None , A=None , A=None , A="pt" , ) -> int: if input_points is not None: if len(A ) != len(A ): _SCREAMING_SNAKE_CASE = [ self._normalize_coordinates(self.target_size , A , original_sizes[0] ) for point in input_points ] else: _SCREAMING_SNAKE_CASE = [ self._normalize_coordinates(self.target_size , A , A ) for point, original_size in zip(A , A ) ] # check that all arrays have the same shape if not all(point.shape == input_points[0].shape for point in input_points ): if input_labels is not None: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._pad_points_and_labels(A , A ) _SCREAMING_SNAKE_CASE = np.array(A ) if input_labels is not None: _SCREAMING_SNAKE_CASE = np.array(A ) if input_boxes is not None: if len(A ) != len(A ): _SCREAMING_SNAKE_CASE = [ self._normalize_coordinates(self.target_size , A , original_sizes[0] , is_bounding_box=A ) for box in input_boxes ] else: _SCREAMING_SNAKE_CASE = [ self._normalize_coordinates(self.target_size , A , A , is_bounding_box=A ) for box, original_size in zip(A , A ) ] _SCREAMING_SNAKE_CASE = np.array(A ) if input_boxes is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE = torch.from_numpy(A ) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE = input_boxes.unsqueeze(1 ) if len(input_boxes.shape ) != 3 else input_boxes elif return_tensors == "tf": _SCREAMING_SNAKE_CASE = tf.convert_to_tensor(A ) # boxes batch size of 1 by default _SCREAMING_SNAKE_CASE = tf.expand_dims(A , 1 ) if len(input_boxes.shape ) != 3 else input_boxes encoding_image_processor.update({"""input_boxes""": input_boxes} ) if input_points is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE = torch.from_numpy(A ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE = input_points.unsqueeze(1 ) if len(input_points.shape ) != 4 else input_points elif return_tensors == "tf": _SCREAMING_SNAKE_CASE = tf.convert_to_tensor(A ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE = tf.expand_dims(A , 1 ) if len(input_points.shape ) != 4 else input_points encoding_image_processor.update({"""input_points""": input_points} ) if input_labels is not None: if return_tensors == "pt": _SCREAMING_SNAKE_CASE = torch.from_numpy(A ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE = input_labels.unsqueeze(1 ) if len(input_labels.shape ) != 3 else input_labels elif return_tensors == "tf": _SCREAMING_SNAKE_CASE = tf.convert_to_tensor(A ) # point batch size of 1 by default _SCREAMING_SNAKE_CASE = tf.expand_dims(A , 1 ) if len(input_labels.shape ) != 3 else input_labels encoding_image_processor.update({"""input_labels""": input_labels} ) return encoding_image_processor def snake_case_( self , A , A ) -> Dict: _SCREAMING_SNAKE_CASE = max([point.shape[0] for point in input_points] ) _SCREAMING_SNAKE_CASE = [] for i, point in enumerate(A ): if point.shape[0] != expected_nb_points: _SCREAMING_SNAKE_CASE = np.concatenate( [point, np.zeros((expected_nb_points - point.shape[0], 2) ) + self.point_pad_value] , axis=0 ) _SCREAMING_SNAKE_CASE = np.append(input_labels[i] , [self.point_pad_value] ) processed_input_points.append(A ) _SCREAMING_SNAKE_CASE = processed_input_points return input_points, input_labels def snake_case_( self , A , A , A , A=False ) -> np.ndarray: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = original_size _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.image_processor._get_preprocess_shape(A , longest_edge=A ) _SCREAMING_SNAKE_CASE = deepcopy(A ).astype(A ) if is_bounding_box: _SCREAMING_SNAKE_CASE = coords.reshape(-1 , 2 , 2 ) _SCREAMING_SNAKE_CASE = coords[..., 0] * (new_w / old_w) _SCREAMING_SNAKE_CASE = coords[..., 1] * (new_h / old_h) if is_bounding_box: _SCREAMING_SNAKE_CASE = coords.reshape(-1 , 4 ) return coords def snake_case_( self , A=None , A=None , A=None , ) -> List[str]: if input_points is not None: if hasattr(A , """numpy""" ): # Checks for TF or Torch tensor _SCREAMING_SNAKE_CASE = input_points.numpy().tolist() if not isinstance(A , A ) or not isinstance(input_points[0] , A ): raise ValueError("""Input points must be a list of list of floating points.""" ) _SCREAMING_SNAKE_CASE = [np.array(A ) for input_point in input_points] else: _SCREAMING_SNAKE_CASE = None if input_labels is not None: if hasattr(A , """numpy""" ): _SCREAMING_SNAKE_CASE = input_labels.numpy().tolist() if not isinstance(A , A ) or not isinstance(input_labels[0] , A ): raise ValueError("""Input labels must be a list of list integers.""" ) _SCREAMING_SNAKE_CASE = [np.array(A ) for label in input_labels] else: _SCREAMING_SNAKE_CASE = None if input_boxes is not None: if hasattr(A , """numpy""" ): _SCREAMING_SNAKE_CASE = input_boxes.numpy().tolist() if ( not isinstance(A , A ) or not isinstance(input_boxes[0] , A ) or not isinstance(input_boxes[0][0] , A ) ): raise ValueError("""Input boxes must be a list of list of list of floating points.""" ) _SCREAMING_SNAKE_CASE = [np.array(A ).astype(np.floataa ) for box in input_boxes] else: _SCREAMING_SNAKE_CASE = None return input_points, input_labels, input_boxes @property def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.image_processor.model_input_names return list(dict.fromkeys(A ) ) def snake_case_( self , *A , **A ) -> str: return self.image_processor.post_process_masks(*A , **A )
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
'''simple docstring''' import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset lowercase_ = """bert-base-cased""" lowercase_ = """google/pegasus-xsum""" lowercase_ = [""" Sam ate lunch today.""", """Sams lunch ingredients."""] lowercase_ = ["""A very interesting story about what I ate for lunch.""", """Avocado, celery, turkey, coffee"""] lowercase_ = """patrickvonplaten/t5-tiny-random""" lowercase_ = """sshleifer/bart-tiny-random""" lowercase_ = """sshleifer/tiny-mbart""" lowercase_ = """sshleifer/tiny-marian-en-de""" def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : list ) ->Optional[Any]: _SCREAMING_SNAKE_CASE = """\n""".join(__lowerCamelCase ) Path(__lowerCamelCase ).open("""w""" ).writelines(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] ) ->Optional[int]: for split in ["train", "val", "test"]: _dump_articles(os.path.join(__lowerCamelCase , F'{split}.source' ) , __lowerCamelCase ) _dump_articles(os.path.join(__lowerCamelCase , F'{split}.target' ) , __lowerCamelCase ) return tmp_dir class a_ ( snake_case_ ): '''simple docstring''' @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(A ) _SCREAMING_SNAKE_CASE = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _SCREAMING_SNAKE_CASE = max(len(tokenizer.encode(A ) ) for a in ARTICLES ) _SCREAMING_SNAKE_CASE = max(len(tokenizer.encode(A ) ) for a in SUMMARIES ) _SCREAMING_SNAKE_CASE = 4 _SCREAMING_SNAKE_CASE = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = """ro_RO""", """de_DE""" # ignored for all but mbart, but never causes error. _SCREAMING_SNAKE_CASE = SeqaSeqDataset( A , data_dir=A , type_path="""train""" , max_source_length=A , max_target_length=A , src_lang=A , tgt_lang=A , ) _SCREAMING_SNAKE_CASE = DataLoader(A , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(A , A ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place _SCREAMING_SNAKE_CASE = shift_tokens_right(batch["""labels"""] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(A ) _SCREAMING_SNAKE_CASE = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) _SCREAMING_SNAKE_CASE = max(len(tokenizer.encode(A ) ) for a in ARTICLES ) _SCREAMING_SNAKE_CASE = max(len(tokenizer.encode(A ) ) for a in SUMMARIES ) _SCREAMING_SNAKE_CASE = 4 _SCREAMING_SNAKE_CASE = LegacySeqaSeqDataset( A , data_dir=A , type_path="""train""" , max_source_length=20 , max_target_length=A , ) _SCREAMING_SNAKE_CASE = DataLoader(A , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("""facebook/mbart-large-cc25""" ) _SCREAMING_SNAKE_CASE = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) _SCREAMING_SNAKE_CASE = tmp_dir.joinpath("""train.source""" ).open().readlines() _SCREAMING_SNAKE_CASE = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(A , A , 128 , A ) _SCREAMING_SNAKE_CASE = {x.name for x in tmp_dir.iterdir()} _SCREAMING_SNAKE_CASE = {x.name for x in save_dir.iterdir()} _SCREAMING_SNAKE_CASE = save_dir.joinpath("""train.source""" ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(A ) < len(A ) assert len(A ) == 1 assert len(packed_examples[0] ) == sum(len(A ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason="""This test requires fairseq""" ) def snake_case_( self ) -> List[str]: if not FAIRSEQ_AVAILABLE: return _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_dataset(max_len=64 ) _SCREAMING_SNAKE_CASE = 64 _SCREAMING_SNAKE_CASE = ds.make_dynamic_sampler(A , required_batch_size_multiple=A ) _SCREAMING_SNAKE_CASE = [len(A ) for x in batch_sampler] assert len(set(A ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(A ) == len(A ) # no dropped or added examples _SCREAMING_SNAKE_CASE = DataLoader(A , batch_sampler=A , collate_fn=ds.collate_fn , num_workers=2 ) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] for batch in data_loader: _SCREAMING_SNAKE_CASE = batch["""input_ids"""].shape _SCREAMING_SNAKE_CASE = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple _SCREAMING_SNAKE_CASE = np.product(batch["""input_ids"""].shape ) num_src_per_batch.append(A ) if num_src_tokens > (max_tokens * 1.1): failures.append(A ) assert num_src_per_batch[0] == max(A ) if failures: raise AssertionError(f'too many tokens in {len(A )} batches' ) def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_dataset(max_len=512 ) _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = ds.make_sortish_sampler(A , shuffle=A ) _SCREAMING_SNAKE_CASE = DataLoader(A , batch_size=A , collate_fn=ds.collate_fn , num_workers=2 ) _SCREAMING_SNAKE_CASE = DataLoader(A , batch_size=A , collate_fn=ds.collate_fn , num_workers=2 , sampler=A ) _SCREAMING_SNAKE_CASE = tokenizer.pad_token_id def count_pad_tokens(A , A="input_ids" ): return [batch[k].eq(A ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(A , k="""labels""" ) ) < sum(count_pad_tokens(A , k="""labels""" ) ) assert sum(count_pad_tokens(A ) ) < sum(count_pad_tokens(A ) ) assert len(A ) == len(A ) def snake_case_( self , A=1000 , A=128 ) -> Union[str, Any]: if os.getenv("""USE_REAL_DATA""" , A ): _SCREAMING_SNAKE_CASE = """examples/seq2seq/wmt_en_ro""" _SCREAMING_SNAKE_CASE = max_len * 2 * 64 if not Path(A ).joinpath("""train.len""" ).exists(): save_len_file(A , A ) else: _SCREAMING_SNAKE_CASE = """examples/seq2seq/test_data/wmt_en_ro""" _SCREAMING_SNAKE_CASE = max_len * 4 save_len_file(A , A ) _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(A ) _SCREAMING_SNAKE_CASE = SeqaSeqDataset( A , data_dir=A , type_path="""train""" , max_source_length=A , max_target_length=A , n_obs=A , ) return ds, max_tokens, tokenizer def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self._get_dataset() _SCREAMING_SNAKE_CASE = set(DistributedSortishSampler(A , 256 , num_replicas=2 , rank=0 , add_extra_examples=A ) ) _SCREAMING_SNAKE_CASE = set(DistributedSortishSampler(A , 256 , num_replicas=2 , rank=1 , add_extra_examples=A ) ) assert idsa.intersection(A ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(A , use_fast=A ) if tok_name == MBART_TINY: _SCREAMING_SNAKE_CASE = SeqaSeqDataset( A , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , src_lang="""EN""" , tgt_lang="""FR""" , ) _SCREAMING_SNAKE_CASE = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: _SCREAMING_SNAKE_CASE = SeqaSeqDataset( A , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path="""train""" , max_source_length=4 , max_target_length=8 , ) _SCREAMING_SNAKE_CASE = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(A ) == 1 if tok_name == BART_TINY else len(A ) == 0
58
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """PoolFormerConfig""" # Base docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = [1, 512, 7, 7] # Image classification docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : float = 0.0 , __lowerCamelCase : bool = False ) ->int: if drop_prob == 0.0 or not training: return input _SCREAMING_SNAKE_CASE = 1 - drop_prob _SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _SCREAMING_SNAKE_CASE = keep_prob + torch.rand(__lowerCamelCase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _SCREAMING_SNAKE_CASE = input.div(__lowerCamelCase ) * random_tensor return output class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A = None ) -> None: super().__init__() _SCREAMING_SNAKE_CASE = drop_prob def snake_case_( self , A ) -> torch.Tensor: return drop_path(A , self.drop_prob , self.training ) def snake_case_( self ) -> str: return "p={}".format(self.drop_prob ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A=None ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = patch_size if isinstance(A , collections.abc.Iterable ) else (patch_size, patch_size) _SCREAMING_SNAKE_CASE = stride if isinstance(A , collections.abc.Iterable ) else (stride, stride) _SCREAMING_SNAKE_CASE = padding if isinstance(A , collections.abc.Iterable ) else (padding, padding) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , kernel_size=A , stride=A , padding=A ) _SCREAMING_SNAKE_CASE = norm_layer(A ) if norm_layer else nn.Identity() def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.projection(A ) _SCREAMING_SNAKE_CASE = self.norm(A ) return embeddings class a_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self , A , **A ) -> Union[str, Any]: super().__init__(1 , A , **A ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.AvgPoolad(A , stride=1 , padding=pool_size // 2 , count_include_pad=A ) def snake_case_( self , A ) -> Union[str, Any]: return self.pool(A ) - hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if isinstance(config.hidden_act , A ): _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: _SCREAMING_SNAKE_CASE = config.hidden_act def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.act_fn(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) return hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = PoolFormerPooling(A ) _SCREAMING_SNAKE_CASE = PoolFormerOutput(A , A , A , A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) # Useful for training neural nets _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() _SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) def snake_case_( self , A ) -> Optional[Any]: if self.use_layer_scale: _SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = () _SCREAMING_SNAKE_CASE = self.output(self.after_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: _SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection _SCREAMING_SNAKE_CASE = pooling_output + hidden_states _SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block _SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(A ) ) ) _SCREAMING_SNAKE_CASE = hidden_states + layer_output _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE = config # stochastic depth decay rule _SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) # Transformer blocks _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(A ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) def snake_case_( self , A , A=False , A=True ) -> List[Any]: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None _SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states _SCREAMING_SNAKE_CASE = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): _SCREAMING_SNAKE_CASE = blk(A ) _SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: _SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = PoolFormerConfig UpperCamelCase = '''poolformer''' UpperCamelCase = '''pixel_values''' UpperCamelCase = True def snake_case_( self , A ) -> int: if isinstance(A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_( self , A , A=False ) -> Dict: if isinstance(A , A ): _SCREAMING_SNAKE_CASE = value lowercase_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> int: super().__init__(A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def snake_case_( self ) -> Any: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A = None , A = None , A = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A , hidden_states=encoder_outputs.hidden_states , ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> Optional[Any]: super().__init__(A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = PoolFormerModel(A ) # Final norm _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.poolformer( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = outputs[0] _SCREAMING_SNAKE_CASE = self.classifier(self.norm(A ).mean([-2, -1] ) ) _SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE = """single_label_classification""" else: _SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE = loss_fct(A , A ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE = CrossEntropyLoss() _SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE = loss_fct(A , A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
1
'''simple docstring''' import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=13 , A=7 , A=True , A=True , A=False , A=True , A=99 , A=32 , A=5 , A=4 , A=64 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=16 , A=2 , A=0.02 , A=3 , A=4 , A=None , A=2 , A=2 , A=2 , A=2 , A=4 , A=1 , ) -> Optional[Any]: _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 _SCREAMING_SNAKE_CASE = q_groups _SCREAMING_SNAKE_CASE = k_groups _SCREAMING_SNAKE_CASE = v_groups _SCREAMING_SNAKE_CASE = post_attention_groups _SCREAMING_SNAKE_CASE = intermediate_groups _SCREAMING_SNAKE_CASE = output_groups def snake_case_( self ) -> Dict: _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 = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_( self ) -> Optional[int]: return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def snake_case_( self , A , A , A , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = SqueezeBertModel(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A , 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 , A , A , A , A , A , A ) -> Any: _SCREAMING_SNAKE_CASE = SqueezeBertForMaskedLM(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 , A , A , A , A , A , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = SqueezeBertForQuestionAnswering(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model( A , attention_mask=A , start_positions=A , end_positions=A ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def snake_case_( self , A , A , A , A , A , A ) -> Dict: _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification(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.num_labels) ) def snake_case_( self , A , A , A , A , A , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = SqueezeBertForTokenClassification(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.num_labels) ) def snake_case_( self , A , A , A , A , A , A ) -> List[str]: _SCREAMING_SNAKE_CASE = self.num_choices _SCREAMING_SNAKE_CASE = SqueezeBertForMultipleChoice(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _SCREAMING_SNAKE_CASE = model( A , attention_mask=A , labels=A , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def snake_case_( self ) -> Dict: _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_torch class a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) UpperCamelCase = ( { '''feature-extraction''': SqueezeBertModel, '''fill-mask''': SqueezeBertForMaskedLM, '''question-answering''': SqueezeBertForQuestionAnswering, '''text-classification''': SqueezeBertForSequenceClassification, '''token-classification''': SqueezeBertForTokenClassification, '''zero-shot''': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) UpperCamelCase = False UpperCamelCase = True UpperCamelCase = False def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = SqueezeBertModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A , dim=37 ) def snake_case_( self ) -> List[Any]: self.config_tester.run_common_tests() def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*A ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*A ) def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*A ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*A ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*A ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*A ) @slow def snake_case_( self ) -> Optional[Any]: for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = SqueezeBertModel.from_pretrained(A ) self.assertIsNotNone(A ) @require_sentencepiece @require_tokenizers @require_torch class a_ ( unittest.TestCase ): '''simple docstring''' @slow def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) _SCREAMING_SNAKE_CASE = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) _SCREAMING_SNAKE_CASE = model(A )[0] _SCREAMING_SNAKE_CASE = torch.Size((1, 3) ) self.assertEqual(output.shape , A ) _SCREAMING_SNAKE_CASE = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(A , A , atol=1e-4 ) )
58
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase_ = logging.getLogger(__name__) lowercase_ = """Hello world! cécé herlolip""" lowercase_ = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir=""".""" , finetune_bert=__lowerCamelCase , large=__lowerCamelCase , share_emb=__lowerCamelCase , use_bert_emb=__lowerCamelCase , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , lambda __lowerCamelCase , __lowerCamelCase : storage ) _SCREAMING_SNAKE_CASE = AbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) , __lowerCamelCase ) original.eval() _SCREAMING_SNAKE_CASE = BertAbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass _SCREAMING_SNAKE_CASE = encoder_input_ids _SCREAMING_SNAKE_CASE = decoder_input_ids _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical _SCREAMING_SNAKE_CASE = original(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = original.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = new_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = new_model.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) lowercase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
58
1
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase_ = logging.get_logger(__name__) lowercase_ = { """microsoft/conditional-detr-resnet-50""": ( """https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''conditional_detr''' UpperCamelCase = ['''past_key_values'''] UpperCamelCase = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , A=True , A=None , A=3 , A=300 , A=6 , A=2048 , A=8 , A=6 , A=2048 , A=8 , A=0.0 , A=0.0 , A=True , A="relu" , A=256 , A=0.1 , A=0.0 , A=0.0 , A=0.02 , A=1.0 , A=False , A="sine" , A="resnet50" , A=True , A=False , A=2 , A=5 , A=2 , A=1 , A=1 , A=2 , A=5 , A=2 , A=0.25 , **A , ) -> Union[str, Any]: if backbone_config is not None and use_timm_backbone: raise ValueError("""You can't specify both `backbone_config` and `use_timm_backbone`.""" ) if not use_timm_backbone: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.""" ) _SCREAMING_SNAKE_CASE = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(A , A ): _SCREAMING_SNAKE_CASE = backbone_config.get("""model_type""" ) _SCREAMING_SNAKE_CASE = CONFIG_MAPPING[backbone_model_type] _SCREAMING_SNAKE_CASE = config_class.from_dict(A ) _SCREAMING_SNAKE_CASE = use_timm_backbone _SCREAMING_SNAKE_CASE = backbone_config _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = num_queries _SCREAMING_SNAKE_CASE = d_model _SCREAMING_SNAKE_CASE = encoder_ffn_dim _SCREAMING_SNAKE_CASE = encoder_layers _SCREAMING_SNAKE_CASE = encoder_attention_heads _SCREAMING_SNAKE_CASE = decoder_ffn_dim _SCREAMING_SNAKE_CASE = decoder_layers _SCREAMING_SNAKE_CASE = decoder_attention_heads _SCREAMING_SNAKE_CASE = dropout _SCREAMING_SNAKE_CASE = attention_dropout _SCREAMING_SNAKE_CASE = activation_dropout _SCREAMING_SNAKE_CASE = activation_function _SCREAMING_SNAKE_CASE = init_std _SCREAMING_SNAKE_CASE = init_xavier_std _SCREAMING_SNAKE_CASE = encoder_layerdrop _SCREAMING_SNAKE_CASE = decoder_layerdrop _SCREAMING_SNAKE_CASE = encoder_layers _SCREAMING_SNAKE_CASE = auxiliary_loss _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = backbone _SCREAMING_SNAKE_CASE = use_pretrained_backbone _SCREAMING_SNAKE_CASE = dilation # Hungarian matcher _SCREAMING_SNAKE_CASE = class_cost _SCREAMING_SNAKE_CASE = bbox_cost _SCREAMING_SNAKE_CASE = giou_cost # Loss coefficients _SCREAMING_SNAKE_CASE = mask_loss_coefficient _SCREAMING_SNAKE_CASE = dice_loss_coefficient _SCREAMING_SNAKE_CASE = cls_loss_coefficient _SCREAMING_SNAKE_CASE = bbox_loss_coefficient _SCREAMING_SNAKE_CASE = giou_loss_coefficient _SCREAMING_SNAKE_CASE = focal_alpha super().__init__(is_encoder_decoder=A , **A ) @property def snake_case_( self ) -> int: return self.encoder_attention_heads @property def snake_case_( self ) -> int: return self.d_model def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _SCREAMING_SNAKE_CASE = self.backbone_config.to_dict() _SCREAMING_SNAKE_CASE = self.__class__.model_type return output class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = version.parse('''1.11''' ) @property def snake_case_( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def snake_case_( self ) -> float: return 1e-5 @property def snake_case_( self ) -> int: return 12
58
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
1
'''simple docstring''' from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''EncodecFeatureExtractor''' UpperCamelCase = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self , A , A ) -> Tuple: super().__init__(A , A ) _SCREAMING_SNAKE_CASE = self.feature_extractor _SCREAMING_SNAKE_CASE = False def snake_case_( self , A=None , A=None , A=True ) -> Dict: return self.tokenizer.get_decoder_prompt_ids(task=A , language=A , no_timestamps=A ) def __call__( self , *A , **A ) -> Optional[Any]: # For backward compatibility if self._in_target_context_manager: return self.current_processor(*A , **A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""audio""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""sampling_rate""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""text""" , A ) if len(A ) > 0: _SCREAMING_SNAKE_CASE = args[0] _SCREAMING_SNAKE_CASE = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: _SCREAMING_SNAKE_CASE = self.tokenizer(A , **A ) if audio is not None: _SCREAMING_SNAKE_CASE = self.feature_extractor(A , *A , sampling_rate=A , **A ) if audio is None: return inputs elif text is None: return audio_inputs else: _SCREAMING_SNAKE_CASE = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: _SCREAMING_SNAKE_CASE = audio_inputs["""padding_mask"""] return inputs def snake_case_( self , *A , **A ) -> Dict: _SCREAMING_SNAKE_CASE = kwargs.pop("""audio""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""padding_mask""" , A ) if len(A ) > 0: _SCREAMING_SNAKE_CASE = args[0] _SCREAMING_SNAKE_CASE = args[1:] if audio_values is not None: return self._decode_audio(A , padding_mask=A ) else: return self.tokenizer.batch_decode(*A , **A ) def snake_case_( self , *A , **A ) -> Dict: return self.tokenizer.decode(*A , **A ) def snake_case_( self , A , A = None ) -> List[np.ndarray]: _SCREAMING_SNAKE_CASE = to_numpy(A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = audio_values.shape if padding_mask is None: return list(A ) _SCREAMING_SNAKE_CASE = to_numpy(A ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) _SCREAMING_SNAKE_CASE = seq_len - padding_mask.shape[-1] _SCREAMING_SNAKE_CASE = 1 - self.feature_extractor.padding_value _SCREAMING_SNAKE_CASE = np.pad(A , ((0, 0), (0, difference)) , """constant""" , constant_values=A ) _SCREAMING_SNAKE_CASE = audio_values.tolist() for i in range(A ): _SCREAMING_SNAKE_CASE = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] _SCREAMING_SNAKE_CASE = sliced_audio.reshape(A , -1 ) return audio_values
58
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" , __lowerCamelCase ).groups()[0] class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=None , A=None ) -> int: _SCREAMING_SNAKE_CASE = file_names _SCREAMING_SNAKE_CASE = image_transform _SCREAMING_SNAKE_CASE = label_to_id def __len__( self ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.file_names[idx] _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) _SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ) if self.image_transform is not None: _SCREAMING_SNAKE_CASE = self.image_transform(A ) _SCREAMING_SNAKE_CASE = extract_label(A ) if self.label_to_id is not None: _SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) ->str: # Initialize accelerator if args.with_tracking: _SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = config["""image_size"""] if not isinstance(__lowerCamelCase , (list, tuple) ): _SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , """isdigit""" ): if args.checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _SCREAMING_SNAKE_CASE = int(args.checkpointing_steps ) else: raise ValueError( F'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _SCREAMING_SNAKE_CASE = os.path.split(__lowerCamelCase )[-1].split(""".""" )[0] accelerator.init_trackers(__lowerCamelCase , __lowerCamelCase ) # Grab all the image filenames _SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , __lowerCamelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences _SCREAMING_SNAKE_CASE = [extract_label(__lowerCamelCase ) for fname in file_names] _SCREAMING_SNAKE_CASE = list(set(__lowerCamelCase ) ) id_to_label.sort() _SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(__lowerCamelCase )} # Set the seed before splitting the data. np.random.seed(__lowerCamelCase ) torch.manual_seed(__lowerCamelCase ) torch.cuda.manual_seed_all(__lowerCamelCase ) # Split our filenames between train and validation _SCREAMING_SNAKE_CASE = np.random.permutation(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = int(0.8 * len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = random_perm[:cut] _SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop _SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(__lowerCamelCase , scale=(0.5, 1.0) ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # For evaluation, we use a deterministic Resize _SCREAMING_SNAKE_CASE = Compose([Resize(__lowerCamelCase ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = create_model("""resnet50d""" , pretrained=__lowerCamelCase , num_classes=len(__lowerCamelCase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): _SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=__lowerCamelCase , max_lr=__lowerCamelCase , epochs=__lowerCamelCase , steps_per_epoch=len(__lowerCamelCase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # We need to keep track of how many total steps we have iterated over _SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly _SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _SCREAMING_SNAKE_CASE = os.path.splitext(__lowerCamelCase )[0] if "epoch" in training_difference: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""epoch_""" , """""" ) ) + 1 _SCREAMING_SNAKE_CASE = None else: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""step_""" , """""" ) ) _SCREAMING_SNAKE_CASE = resume_step // len(__lowerCamelCase ) resume_step -= starting_epoch * len(__lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase , __lowerCamelCase ): model.train() if args.with_tracking: _SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(__lowerCamelCase , __lowerCamelCase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(__lowerCamelCase , batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowerCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = F'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) _SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 100 * eval_metric, """train_loss""": total_loss.item() / len(__lowerCamelCase ), """epoch""": epoch, } , step=__lowerCamelCase , ) if checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = F'epoch_{epoch}' if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) if args.with_tracking: accelerator.end_training() def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" , required=__lowerCamelCase , help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , ) parser.add_argument( """--output_dir""" , type=__lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=__lowerCamelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
1
'''simple docstring''' lowercase_ = [ """Audio""", """Array2D""", """Array3D""", """Array4D""", """Array5D""", """ClassLabel""", """Features""", """Sequence""", """Value""", """Image""", """Translation""", """TranslationVariableLanguages""", ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
58
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = """Usage of script: script_name <size_of_canvas:int>""" lowercase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase ( __lowerCamelCase : int ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCamelCase )] for j in range(__lowerCamelCase )] return canvas def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->None: for i, row in enumerate(__lowerCamelCase ): for j, _ in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCamelCase ): for c, pt in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = __judge_point( __lowerCamelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) _SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. _SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def lowerCamelCase ( __lowerCamelCase : bool , __lowerCamelCase : list[list[bool]] ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. _SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: _SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: _SCREAMING_SNAKE_CASE = True elif alive > 3: _SCREAMING_SNAKE_CASE = False else: if alive == 3: _SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ , lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(["""w""", """k"""]) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
58
1
'''simple docstring''' import itertools import random import unittest import numpy as np from transformers import ASTFeatureExtractor from transformers.testing_utils import require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin lowercase_ = random.Random() if is_torch_available(): import torch def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Dict=1.0 , __lowerCamelCase : int=None , __lowerCamelCase : List[str]=None ) ->Tuple: if rng is None: _SCREAMING_SNAKE_CASE = global_rng _SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class a_ ( unittest.TestCase ): '''simple docstring''' def __init__( self , A , A=7 , A=400 , A=2000 , A=1 , A=0.0 , A=1_6000 , A=True , A=True , ) -> Tuple: _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = min_seq_length _SCREAMING_SNAKE_CASE = max_seq_length _SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) _SCREAMING_SNAKE_CASE = feature_size _SCREAMING_SNAKE_CASE = padding_value _SCREAMING_SNAKE_CASE = sampling_rate _SCREAMING_SNAKE_CASE = return_attention_mask _SCREAMING_SNAKE_CASE = do_normalize def snake_case_( self ) -> Dict: return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def snake_case_( self , A=False , A=False ) -> str: def _flatten(A ): return list(itertools.chain(*A ) ) if equal_length: _SCREAMING_SNAKE_CASE = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size _SCREAMING_SNAKE_CASE = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: _SCREAMING_SNAKE_CASE = [np.asarray(A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class a_ ( snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ASTFeatureExtractor def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = ASTFeatureExtractionTester(self ) def snake_case_( self ) -> Dict: # Tests that all call wrap to encode_plus and batch_encode_plus _SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 _SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] _SCREAMING_SNAKE_CASE = [np.asarray(A ) for speech_input in speech_inputs] # Test not batched input _SCREAMING_SNAKE_CASE = feat_extract(speech_inputs[0] , return_tensors="""np""" ).input_values _SCREAMING_SNAKE_CASE = feat_extract(np_speech_inputs[0] , return_tensors="""np""" ).input_values self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) # Test batched _SCREAMING_SNAKE_CASE = feat_extract(A , padding=A , return_tensors="""np""" ).input_values _SCREAMING_SNAKE_CASE = feat_extract(A , padding=A , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A , A ): self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. _SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (800, 800, 800)] _SCREAMING_SNAKE_CASE = np.asarray(A ) _SCREAMING_SNAKE_CASE = feat_extract(A , return_tensors="""np""" ).input_values _SCREAMING_SNAKE_CASE = feat_extract(A , return_tensors="""np""" ).input_values for enc_seq_a, enc_seq_a in zip(A , A ): self.assertTrue(np.allclose(A , A , atol=1e-3 ) ) @require_torch def snake_case_( self ) -> List[Any]: import torch _SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) _SCREAMING_SNAKE_CASE = np.random.rand(100 ).astype(np.floataa ) _SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: _SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""np""" ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) _SCREAMING_SNAKE_CASE = feature_extractor.pad([{"""input_values""": inputs}] , return_tensors="""pt""" ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def snake_case_( self , A ) -> Optional[Any]: from datasets import load_dataset _SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" , """clean""" , split="""validation""" ) # automatic decoding with librispeech _SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(A ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] @require_torch def snake_case_( self ) -> Optional[int]: # fmt: off _SCREAMING_SNAKE_CASE = torch.tensor( [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776, -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133, -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936, -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] ) # fmt: on _SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) _SCREAMING_SNAKE_CASE = ASTFeatureExtractor() _SCREAMING_SNAKE_CASE = feature_extractor(A , return_tensors="""pt""" ).input_values self.assertEquals(input_values.shape , (1, 1024, 128) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , A , atol=1e-4 ) )
58
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase_ = HUGGINGFACE_HUB_CACHE lowercase_ = """config.json""" lowercase_ = """diffusion_pytorch_model.bin""" lowercase_ = """diffusion_flax_model.msgpack""" lowercase_ = """model.onnx""" lowercase_ = """diffusion_pytorch_model.safetensors""" lowercase_ = """weights.pb""" lowercase_ = """https://huggingface.co""" lowercase_ = default_cache_path lowercase_ = """diffusers_modules""" lowercase_ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowercase_ = ["""fp16""", """non-ema"""] lowercase_ = """.self_attn"""
58
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase ( __lowerCamelCase : int = 4 ) ->list[list[int]]: _SCREAMING_SNAKE_CASE = abs(__lowerCamelCase ) or 4 return [[1 + x + y * row_size for x in range(__lowerCamelCase )] for y in range(__lowerCamelCase )] def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: return reverse_row(transpose(__lowerCamelCase ) ) # OR.. transpose(reverse_column(matrix)) def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: return reverse_row(reverse_column(__lowerCamelCase ) ) # OR.. reverse_column(reverse_row(matrix)) def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: return reverse_column(transpose(__lowerCamelCase ) ) # OR.. transpose(reverse_row(matrix)) def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: _SCREAMING_SNAKE_CASE = [list(__lowerCamelCase ) for x in zip(*__lowerCamelCase )] return matrix def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: _SCREAMING_SNAKE_CASE = matrix[::-1] return matrix def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->list[list[int]]: _SCREAMING_SNAKE_CASE = [x[::-1] for x in matrix] return matrix def lowerCamelCase ( __lowerCamelCase : list[list[int]] ) ->None: for i in matrix: print(*__lowerCamelCase ) if __name__ == "__main__": lowercase_ = make_matrix() print("""\norigin:\n""") print_matrix(matrix) print("""\nrotate 90 counterclockwise:\n""") print_matrix(rotate_aa(matrix)) lowercase_ = make_matrix() print("""\norigin:\n""") print_matrix(matrix) print("""\nrotate 180:\n""") print_matrix(rotate_aaa(matrix)) lowercase_ = make_matrix() print("""\norigin:\n""") print_matrix(matrix) print("""\nrotate 270 counterclockwise:\n""") print_matrix(rotate_aaa(matrix))
58
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
1
'''simple docstring''' import argparse import copy def lowerCamelCase ( __lowerCamelCase : int ) ->str: _SCREAMING_SNAKE_CASE = {} with open(__lowerCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: _SCREAMING_SNAKE_CASE = [] _list.append([line.split()[1], line.split()[2]] ) _SCREAMING_SNAKE_CASE = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: _SCREAMING_SNAKE_CASE = [] _list.append([line.split()[0], line.split()[2]] ) _SCREAMING_SNAKE_CASE = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : str ) ->Union[str, Any]: with open(__lowerCamelCase ) as f: _SCREAMING_SNAKE_CASE = f.read(1 ) _SCREAMING_SNAKE_CASE = start_node _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = start_node _SCREAMING_SNAKE_CASE = 0 while visiting not in first_solution: _SCREAMING_SNAKE_CASE = 1_0000 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__lowerCamelCase ) and k[0] not in first_solution: _SCREAMING_SNAKE_CASE = k[1] _SCREAMING_SNAKE_CASE = k[0] first_solution.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = distance_of_first_solution + int(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = best_node first_solution.append(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 _SCREAMING_SNAKE_CASE = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0000 ) return first_solution, distance_of_first_solution def lowerCamelCase ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[str] ) ->str: _SCREAMING_SNAKE_CASE = [] for n in solution[1:-1]: _SCREAMING_SNAKE_CASE = solution.index(__lowerCamelCase ) for kn in solution[1:-1]: _SCREAMING_SNAKE_CASE = solution.index(__lowerCamelCase ) if n == kn: continue _SCREAMING_SNAKE_CASE = copy.deepcopy(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = kn _SCREAMING_SNAKE_CASE = n _SCREAMING_SNAKE_CASE = 0 for k in _tmp[:-1]: _SCREAMING_SNAKE_CASE = _tmp[_tmp.index(__lowerCamelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: _SCREAMING_SNAKE_CASE = distance + int(i[1] ) _tmp.append(__lowerCamelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) _SCREAMING_SNAKE_CASE = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __lowerCamelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : List[Any] , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] ) ->str: _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = first_solution _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = distance_of_first_solution _SCREAMING_SNAKE_CASE = solution while count <= iters: _SCREAMING_SNAKE_CASE = find_neighborhood(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution] _SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) - 1 _SCREAMING_SNAKE_CASE = False while not found: _SCREAMING_SNAKE_CASE = 0 while i < len(__lowerCamelCase ): if best_solution[i] != solution[i]: _SCREAMING_SNAKE_CASE = best_solution[i] _SCREAMING_SNAKE_CASE = solution[i] break _SCREAMING_SNAKE_CASE = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = best_solution[:-1] _SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: _SCREAMING_SNAKE_CASE = cost _SCREAMING_SNAKE_CASE = solution else: _SCREAMING_SNAKE_CASE = index_of_best_solution + 1 _SCREAMING_SNAKE_CASE = neighborhood[index_of_best_solution] if len(__lowerCamelCase ) >= size: tabu_list.pop(0 ) _SCREAMING_SNAKE_CASE = count + 1 return best_solution_ever, best_cost def lowerCamelCase ( __lowerCamelCase : List[str]=None ) ->Optional[Any]: _SCREAMING_SNAKE_CASE = generate_neighbours(args.File ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = generate_first_solution( args.File , __lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = tabu_search( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , args.Iterations , args.Size , ) print(F'Best solution: {best_sol}, with total distance: {best_cost}.' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser(description="""Tabu Search""") parser.add_argument( """-f""", """--File""", type=str, help="""Path to the file containing the data""", required=True, ) parser.add_argument( """-i""", """--Iterations""", type=int, help="""How many iterations the algorithm should perform""", required=True, ) parser.add_argument( """-s""", """--Size""", type=int, help="""Size of the tabu list""", required=True ) # Pass the arguments to main method main(parser.parse_args())
58
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
1
'''simple docstring''' import math from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """facebook/data2vec-base-960h""": """https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json""", # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''data2vec-audio''' def __init__( self , A=32 , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=0.1 , A=0.0 , A=0.1 , A=0.1 , A=0.02 , A=1e-5 , A="gelu" , A=(512, 512, 512, 512, 512, 512, 512) , A=(5, 2, 2, 2, 2, 2, 2) , A=(10, 3, 3, 3, 3, 2, 2) , A=False , A=16 , A=19 , A=5 , A=0.05 , A=10 , A=2 , A=0.0 , A=10 , A=0 , A="sum" , A=False , A=False , A=256 , A=(512, 512, 512, 512, 1500) , A=(5, 3, 3, 1, 1) , A=(1, 2, 3, 1, 1) , A=512 , A=0 , A=1 , A=2 , A=False , A=3 , A=2 , A=3 , A=None , **A , ) -> Dict: super().__init__(**A , pad_token_id=A , bos_token_id=A , eos_token_id=A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = feat_extract_activation _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = conv_bias _SCREAMING_SNAKE_CASE = num_conv_pos_embeddings _SCREAMING_SNAKE_CASE = num_conv_pos_embedding_groups _SCREAMING_SNAKE_CASE = conv_pos_kernel_size _SCREAMING_SNAKE_CASE = len(self.conv_dim ) _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_dropout _SCREAMING_SNAKE_CASE = attention_dropout _SCREAMING_SNAKE_CASE = activation_dropout _SCREAMING_SNAKE_CASE = feat_proj_dropout _SCREAMING_SNAKE_CASE = final_dropout _SCREAMING_SNAKE_CASE = layerdrop _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,' f' `len(config.conv_kernel) = {len(self.conv_kernel )}`.' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _SCREAMING_SNAKE_CASE = mask_time_prob _SCREAMING_SNAKE_CASE = mask_time_length _SCREAMING_SNAKE_CASE = mask_time_min_masks _SCREAMING_SNAKE_CASE = mask_feature_prob _SCREAMING_SNAKE_CASE = mask_feature_length _SCREAMING_SNAKE_CASE = mask_feature_min_masks # ctc loss _SCREAMING_SNAKE_CASE = ctc_loss_reduction _SCREAMING_SNAKE_CASE = ctc_zero_infinity # adapter _SCREAMING_SNAKE_CASE = add_adapter _SCREAMING_SNAKE_CASE = adapter_kernel_size _SCREAMING_SNAKE_CASE = adapter_stride _SCREAMING_SNAKE_CASE = num_adapter_layers _SCREAMING_SNAKE_CASE = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. _SCREAMING_SNAKE_CASE = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = list(A ) _SCREAMING_SNAKE_CASE = xvector_output_dim @property def snake_case_( self ) -> str: return math.prod(self.conv_stride )
58
'''simple docstring''' import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) lowercase_ = logging.getLogger(__name__) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30_522, type=int) lowercase_ = parser.parse_args() logger.info(f"""Loading data from {args.data_file}""") with open(args.data_file, """rb""") as fp: lowercase_ = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") lowercase_ = Counter() for tk_ids in data: counter.update(tk_ids) lowercase_ = [0] * args.vocab_size for k, v in counter.items(): lowercase_ = v logger.info(f"""Dump to {args.token_counts_dump}""") with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
58
1
'''simple docstring''' 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 lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[Any]=False ) ->Tuple: _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 lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple=False ) ->Union[str, Any]: 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 lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->Dict: _SCREAMING_SNAKE_CASE = ["""head.weight""", """head.bias"""] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : List[str] ) ->str: # 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(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : List[str] , __lowerCamelCase : Dict , __lowerCamelCase : Any ) ->int: _SCREAMING_SNAKE_CASE = dct.pop(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = val def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] ) ->Any: _SCREAMING_SNAKE_CASE = ViTMSNConfig() _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = """datasets/huggingface/label-files""" _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = 1536 _SCREAMING_SNAKE_CASE = 6 elif "l16" in checkpoint_url: _SCREAMING_SNAKE_CASE = 1024 _SCREAMING_SNAKE_CASE = 4096 _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 = 1024 _SCREAMING_SNAKE_CASE = 4096 _SCREAMING_SNAKE_CASE = 24 _SCREAMING_SNAKE_CASE = 16 _SCREAMING_SNAKE_CASE = 0.1 _SCREAMING_SNAKE_CASE = ViTMSNModel(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(__lowerCamelCase , map_location="""cpu""" )["""target_encoder"""] _SCREAMING_SNAKE_CASE = ViTImageProcessor(size=config.image_size ) remove_projection_head(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = create_rename_keys(__lowerCamelCase , base_model=__lowerCamelCase ) for src, dest in rename_keys: rename_key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) read_in_q_k_v(__lowerCamelCase , __lowerCamelCase , base_model=__lowerCamelCase ) model.load_state_dict(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" _SCREAMING_SNAKE_CASE = Image.open(requests.get(__lowerCamelCase , stream=__lowerCamelCase ).raw ) _SCREAMING_SNAKE_CASE = ViTImageProcessor( size=config.image_size , image_mean=__lowerCamelCase , image_std=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = image_processor(images=__lowerCamelCase , return_tensors="""pt""" ) # forward pass torch.manual_seed(2 ) _SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) _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.0915, -1.4876, -1.1809]] ) elif "b16" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor([[14.2889, -18.9045, 11.7281]] ) elif "l16" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor([[41.5028, -22.8681, 45.6475]] ) elif "b4" in checkpoint_url: _SCREAMING_SNAKE_CASE = torch.tensor([[-4.3868, 5.2932, -0.4137]] ) else: _SCREAMING_SNAKE_CASE = torch.tensor([[-0.1792, -0.6465, 2.4263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , __lowerCamelCase , atol=1e-4 ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(__lowerCamelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = 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.""" ) lowercase_ = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
58
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( ImageTextPipelineOutput, UniDiffuserPipeline, ) else: from .modeling_text_decoder import UniDiffuserTextDecoder from .modeling_uvit import UniDiffuserModel, UTransformeraDModel from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
58
1
'''simple docstring''' import re def lowerCamelCase ( __lowerCamelCase : str ) ->bool: _SCREAMING_SNAKE_CASE = re.compile(R"""^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$""" ) if match := re.search(__lowerCamelCase , __lowerCamelCase ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("""+918827897895"""))
58
'''simple docstring''' import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger() @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def snake_case_( self , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(A , nn.Convad ) or isinstance(A , nn.BatchNormad ) if has_not_submodules: self.traced.append(A ) def __call__( self , A ) -> str: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(A ) [x.remove() for x in self.handles] return self @property def snake_case_( self ) -> str: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda A : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 0 UpperCamelCase = field(default_factory=snake_case_ ) UpperCamelCase = field(default_factory=snake_case_ ) def __call__( self , A ) -> List[str]: _SCREAMING_SNAKE_CASE = Tracker(self.dest )(A ).parametrized _SCREAMING_SNAKE_CASE = Tracker(self.src )(A ).parametrized _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.src_skip , A ) ) _SCREAMING_SNAKE_CASE = list(filter(lambda A : type(A ) not in self.dest_skip , A ) ) if len(A ) != len(A ): raise Exception( f'Numbers of operations are different. Source module has {len(A )} operations while' f' destination module has {len(A )}.' ) for dest_m, src_m in zip(A , A ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : ResNetConfig , __lowerCamelCase : Path , __lowerCamelCase : bool = True ) ->int: print(F'Converting {name}...' ) with torch.no_grad(): _SCREAMING_SNAKE_CASE = timm.create_model(__lowerCamelCase , pretrained=__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ResNetForImageClassification(__lowerCamelCase ).eval() _SCREAMING_SNAKE_CASE = ModuleTransfer(src=__lowerCamelCase , dest=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(__lowerCamelCase ) assert torch.allclose(from_model(__lowerCamelCase ) , our_model(__lowerCamelCase ).logits ), "The model logits don't match the original one." _SCREAMING_SNAKE_CASE = F'resnet{"-".join(name.split("resnet" ) )}' print(__lowerCamelCase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add model""" , use_temp_dir=__lowerCamelCase , ) # we can use the convnext one _SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k""" ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name , commit_message="""Add image processor""" , use_temp_dir=__lowerCamelCase , ) print(F'Pushed {checkpoint_name}' ) def lowerCamelCase ( __lowerCamelCase : Path , __lowerCamelCase : str = None , __lowerCamelCase : bool = True ) ->Any: _SCREAMING_SNAKE_CASE = """imagenet-1k-id2label.json""" _SCREAMING_SNAKE_CASE = 1000 _SCREAMING_SNAKE_CASE = (1, num_labels) _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = num_labels _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCamelCase , __lowerCamelCase , repo_type="""dataset""" ) , """r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCamelCase ): 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 = partial(__lowerCamelCase , num_labels=__lowerCamelCase , idalabel=__lowerCamelCase , labelaid=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = { """resnet18""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet26""": ImageNetPreTrainedConfig( depths=[2, 2, 2, 2] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet34""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[64, 128, 256, 512] , layer_type="""basic""" ), """resnet50""": ImageNetPreTrainedConfig( depths=[3, 4, 6, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet101""": ImageNetPreTrainedConfig( depths=[3, 4, 23, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), """resnet152""": ImageNetPreTrainedConfig( depths=[3, 8, 36, 3] , hidden_sizes=[256, 512, 1024, 2048] , layer_type="""bottleneck""" ), } if model_name: convert_weight_and_push(__lowerCamelCase , names_to_config[model_name] , __lowerCamelCase , __lowerCamelCase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return config, expected_shape if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported resnet* architecture,""" """ currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) lowercase_ = parser.parse_args() lowercase_ = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
58
1
'''simple docstring''' from __future__ import annotations from math import gcd def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int = 2 , __lowerCamelCase : int = 1 , __lowerCamelCase : int = 3 , ) ->int | None: # A value less than 2 can cause an infinite loop in the algorithm. if num < 2: raise ValueError("""The input value cannot be less than 2""" ) # Because of the relationship between ``f(f(x))`` and ``f(x)``, this # algorithm struggles to find factors that are divisible by two. # As a workaround, we specifically check for two and even inputs. # See: https://math.stackexchange.com/a/2856214/165820 if num > 2 and num % 2 == 0: return 2 # Pollard's Rho algorithm requires a function that returns pseudorandom # values between 0 <= X < ``num``. It doesn't need to be random in the # sense that the output value is cryptographically secure or difficult # to calculate, it only needs to be random in the sense that all output # values should be equally likely to appear. # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num`` # However, the success of Pollard's algorithm isn't guaranteed and is # determined in part by the initial seed and the chosen random function. # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num`` # where ``C`` is a value that we can modify between each attempt. def rand_fn(__lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ) -> int: return (pow(__lowerCamelCase , 2 ) + step) % modulus for _ in range(__lowerCamelCase ): # These track the position within the cycle detection logic. _SCREAMING_SNAKE_CASE = seed _SCREAMING_SNAKE_CASE = seed while True: # At each iteration, the tortoise moves one step and the hare moves two. _SCREAMING_SNAKE_CASE = rand_fn(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = rand_fn(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = rand_fn(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # At some point both the tortoise and the hare will enter a cycle whose # length ``p`` is a divisor of ``num``. Once in that cycle, at some point # the tortoise and hare will end up on the same value modulo ``p``. # We can detect when this happens because the position difference between # the tortoise and the hare will share a common divisor with ``num``. _SCREAMING_SNAKE_CASE = gcd(hare - tortoise , __lowerCamelCase ) if divisor == 1: # No common divisor yet, just keep searching. continue else: # We found a common divisor! if divisor == num: # Unfortunately, the divisor is ``num`` itself and is useless. break else: # The divisor is a nontrivial factor of ``num``! return divisor # If we made it here, then this attempt failed. # We need to pick a new starting seed for the tortoise and hare # in addition to a new step value for the random function. # To keep this example implementation deterministic, the # new values will be generated based on currently available # values instead of using something like ``random.randint``. # We can use the hare's position as the new seed. # This is actually what Richard Brent's the "optimized" variant does. _SCREAMING_SNAKE_CASE = hare # The new step value for the random function can just be incremented. # At first the results will be similar to what the old function would # have produced, but the value will quickly diverge after a bit. step += 1 # We haven't found a divisor within the requested number of attempts. # We were unlucky or ``num`` itself is actually prime. return None if __name__ == "__main__": import argparse lowercase_ = argparse.ArgumentParser() parser.add_argument( """num""", type=int, help="""The value to find a divisor of""", ) parser.add_argument( """--attempts""", type=int, default=3, help="""The number of attempts before giving up""", ) lowercase_ = parser.parse_args() lowercase_ = pollard_rho(args.num, attempts=args.attempts) if divisor is None: print(f"""{args.num} is probably prime""") else: lowercase_ = args.num // divisor print(f"""{args.num} = {divisor} * {quotient}""")
58
'''simple docstring''' from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase ( __lowerCamelCase : str ) ->Optional[int]: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += [key] setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator def lowerCamelCase ( *__lowerCamelCase : List[str] ) ->Dict: def decorator(__lowerCamelCase : int ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , """handle_key""" , [] ) handle += keys setattr(__lowerCamelCase , """handle_key""" , __lowerCamelCase ) return func return decorator class a_ ( snake_case_ ): '''simple docstring''' def __new__( cls , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = super().__new__(cls , A , A , A ) if not hasattr(A , """key_handler""" ): setattr(A , """key_handler""" , {} ) setattr(A , """handle_input""" , KeyHandler.handle_input ) for value in attrs.values(): _SCREAMING_SNAKE_CASE = getattr(A , """handle_key""" , [] ) for key in handled_keys: _SCREAMING_SNAKE_CASE = value return new_cls @staticmethod def snake_case_( cls ) -> str: _SCREAMING_SNAKE_CASE = get_character() if char != KEYMAP["undefined"]: _SCREAMING_SNAKE_CASE = ord(A ) _SCREAMING_SNAKE_CASE = cls.key_handler.get(A ) if handler: _SCREAMING_SNAKE_CASE = char return handler(cls ) else: return None def lowerCamelCase ( cls : Any ) ->Dict: return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy() )
58
1
'''simple docstring''' from dataclasses import asdict, dataclass from typing import Optional from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) # TODO Update this lowercase_ = { """facebook/esm-1b""": """https://huggingface.co/facebook/esm-1b/resolve/main/config.json""", # See all ESM models at https://huggingface.co/models?filter=esm } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''esm''' def __init__( self , A=None , A=None , A=None , A=768 , A=12 , A=12 , A=3072 , A=0.1 , A=0.1 , A=1026 , A=0.02 , A=1e-12 , A="absolute" , A=True , A=None , A=False , A=False , A=None , A=None , **A , ) -> List[str]: super().__init__(pad_token_id=A , mask_token_id=A , **A ) _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 = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = emb_layer_norm_before _SCREAMING_SNAKE_CASE = token_dropout _SCREAMING_SNAKE_CASE = is_folding_model if is_folding_model: if esmfold_config is None: logger.info("""No esmfold_config supplied for folding model, using default values.""" ) _SCREAMING_SNAKE_CASE = EsmFoldConfig() elif isinstance(A , A ): _SCREAMING_SNAKE_CASE = EsmFoldConfig(**A ) _SCREAMING_SNAKE_CASE = esmfold_config if vocab_list is None: logger.warning("""No vocab_list supplied for folding model, assuming the ESM-2 vocabulary!""" ) _SCREAMING_SNAKE_CASE = get_default_vocab_list() else: _SCREAMING_SNAKE_CASE = vocab_list else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None if self.esmfold_config is not None and getattr(self.esmfold_config , """use_esm_attn_map""" , A ): raise ValueError("""The HuggingFace port of ESMFold does not support use_esm_attn_map at this time!""" ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = super().to_dict() if isinstance(self.esmfold_config , A ): _SCREAMING_SNAKE_CASE = self.esmfold_config.to_dict() return output @dataclass class a_ : '''simple docstring''' UpperCamelCase = None UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = 0 UpperCamelCase = True UpperCamelCase = False UpperCamelCase = 1_28 UpperCamelCase = None def snake_case_( self ) -> Any: if self.trunk is None: _SCREAMING_SNAKE_CASE = TrunkConfig() elif isinstance(self.trunk , A ): _SCREAMING_SNAKE_CASE = TrunkConfig(**self.trunk ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = asdict(self ) _SCREAMING_SNAKE_CASE = self.trunk.to_dict() return output @dataclass class a_ : '''simple docstring''' UpperCamelCase = 48 UpperCamelCase = 10_24 UpperCamelCase = 1_28 UpperCamelCase = 32 UpperCamelCase = 32 UpperCamelCase = 32 UpperCamelCase = 0 UpperCamelCase = 0 UpperCamelCase = False UpperCamelCase = 4 UpperCamelCase = 1_28 UpperCamelCase = None def snake_case_( self ) -> int: if self.structure_module is None: _SCREAMING_SNAKE_CASE = StructureModuleConfig() elif isinstance(self.structure_module , A ): _SCREAMING_SNAKE_CASE = StructureModuleConfig(**self.structure_module ) if self.max_recycles <= 0: raise ValueError(f'`max_recycles` should be positive, got {self.max_recycles}.' ) if self.sequence_state_dim % self.sequence_state_dim != 0: raise ValueError( """`sequence_state_dim` should be a round multiple of `sequence_state_dim`, got""" f' {self.sequence_state_dim} and {self.sequence_state_dim}.' ) if self.pairwise_state_dim % self.pairwise_state_dim != 0: raise ValueError( """`pairwise_state_dim` should be a round multiple of `pairwise_state_dim`, got""" f' {self.pairwise_state_dim} and {self.pairwise_state_dim}.' ) _SCREAMING_SNAKE_CASE = self.sequence_state_dim // self.sequence_head_width _SCREAMING_SNAKE_CASE = self.pairwise_state_dim // self.pairwise_head_width if self.sequence_state_dim != sequence_num_heads * self.sequence_head_width: raise ValueError( """`sequence_state_dim` should be equal to `sequence_num_heads * sequence_head_width, got""" f' {self.sequence_state_dim} != {sequence_num_heads} * {self.sequence_head_width}.' ) if self.pairwise_state_dim != pairwise_num_heads * self.pairwise_head_width: raise ValueError( """`pairwise_state_dim` should be equal to `pairwise_num_heads * pairwise_head_width, got""" f' {self.pairwise_state_dim} != {pairwise_num_heads} * {self.pairwise_head_width}.' ) if self.pairwise_state_dim % 2 != 0: raise ValueError(f'`pairwise_state_dim` should be even, got {self.pairwise_state_dim}.' ) if self.dropout >= 0.4: raise ValueError(f'`dropout` should not be greater than 0.4, got {self.dropout}.' ) def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = asdict(self ) _SCREAMING_SNAKE_CASE = self.structure_module.to_dict() return output @dataclass class a_ : '''simple docstring''' UpperCamelCase = 3_84 UpperCamelCase = 1_28 UpperCamelCase = 16 UpperCamelCase = 1_28 UpperCamelCase = 12 UpperCamelCase = 4 UpperCamelCase = 8 UpperCamelCase = 0.1 UpperCamelCase = 8 UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = 7 UpperCamelCase = 10 UpperCamelCase = 1E-8 UpperCamelCase = 1E5 def snake_case_( self ) -> int: return asdict(self ) def lowerCamelCase ( ) ->Optional[int]: return ( "<cls>", "<pad>", "<eos>", "<unk>", "L", "A", "G", "V", "S", "E", "R", "T", "I", "D", "P", "K", "Q", "N", "F", "Y", "M", "H", "W", "C", "X", "B", "U", "Z", "O", ".", "-", "<null_1>", "<mask>", )
58
'''simple docstring''' import importlib.metadata import operator import re import sys from typing import Optional from packaging import version lowercase_ = { """<""": operator.lt, """<=""": operator.le, """==""": operator.eq, """!=""": operator.ne, """>=""": operator.ge, """>""": operator.gt, } def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] ) ->Tuple: if got_ver is None or want_ver is None: raise ValueError( F'Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider' F' reinstalling {pkg}.' ) if not ops[op](version.parse(__lowerCamelCase ) , version.parse(__lowerCamelCase ) ): raise ImportError( F'{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}' ) def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[str] = None ) ->None: _SCREAMING_SNAKE_CASE = F'\n{hint}' if hint is not None else """""" # non-versioned check if re.match(R"""^[\w_\-\d]+$""" , __lowerCamelCase ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = requirement, None, None else: _SCREAMING_SNAKE_CASE = re.findall(R"""^([^!=<>\s]+)([\s!=<>]{1,2}.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but""" F' got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_full.split(""",""" ) # there could be multiple requirements _SCREAMING_SNAKE_CASE = {} for w in want_range: _SCREAMING_SNAKE_CASE = re.findall(R"""^([\s!=<>]{1,2})(.+)""" , __lowerCamelCase ) if not match: raise ValueError( """requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,""" F' but got {requirement}' ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = match[0] _SCREAMING_SNAKE_CASE = want_ver if op not in ops: raise ValueError(F'{requirement}: need one of {list(ops.keys() )}, but got {op}' ) # special case if pkg == "python": _SCREAMING_SNAKE_CASE = """.""".join([str(__lowerCamelCase ) for x in sys.version_info[:3]] ) for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) return # check if any version is installed try: _SCREAMING_SNAKE_CASE = importlib.metadata.version(__lowerCamelCase ) except importlib.metadata.PackageNotFoundError: raise importlib.metadata.PackageNotFoundError( F'The \'{requirement}\' distribution was not found and is required by this application. {hint}' ) # check that the right version is installed if version number or a range was provided if want_ver is not None: for op, want_ver in wanted.items(): _compare_versions(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : Union[str, Any] ) ->str: _SCREAMING_SNAKE_CASE = """Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main""" return require_version(__lowerCamelCase , __lowerCamelCase )
58
1
'''simple docstring''' import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def lowerCamelCase ( __lowerCamelCase : List[str] ) ->List[str]: _SCREAMING_SNAKE_CASE = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """decoder.output_projection.weight""", """_float_tensor""", """encoder.embed_positions._float_tensor""", """decoder.embed_positions._float_tensor""", ] for k in ignore_keys: state_dict.pop(__lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : int ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: _SCREAMING_SNAKE_CASE = s_dict.pop(__lowerCamelCase ) elif "subsample" in key: _SCREAMING_SNAKE_CASE = s_dict.pop(__lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : List[str] ) ->List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = emb.weight.shape _SCREAMING_SNAKE_CASE = nn.Linear(__lowerCamelCase , __lowerCamelCase , bias=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[str] ) ->int: _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , map_location="""cpu""" ) _SCREAMING_SNAKE_CASE = mam_aaa["""args"""] _SCREAMING_SNAKE_CASE = mam_aaa["""model"""] _SCREAMING_SNAKE_CASE = state_dict["""decoder.output_projection.weight"""] remove_ignore_keys_(__lowerCamelCase ) rename_keys(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = state_dict["""decoder.embed_tokens.weight"""].shape[0] _SCREAMING_SNAKE_CASE = args.share_decoder_input_output_embed _SCREAMING_SNAKE_CASE = [int(__lowerCamelCase ) for i in args.conv_kernel_sizes.split(""",""" )] _SCREAMING_SNAKE_CASE = SpeechaTextConfig( vocab_size=__lowerCamelCase , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="""relu""" , num_conv_layers=len(__lowerCamelCase ) , conv_channels=args.conv_channels , conv_kernel_sizes=__lowerCamelCase , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=__lowerCamelCase , num_beams=5 , max_length=200 , use_cache=__lowerCamelCase , decoder_start_token_id=2 , early_stopping=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = SpeechaTextForConditionalGeneration(__lowerCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = model.model.load_state_dict(__lowerCamelCase , strict=__lowerCamelCase ) if len(__lowerCamelCase ) > 0 and not set(__lowerCamelCase ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( """Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,""" F' but all the following weights are missing {missing}' ) if tie_embeds: _SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.decoder.embed_tokens ) else: _SCREAMING_SNAKE_CASE = lm_head_weights model.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument("""--fairseq_path""", type=str, help="""Path to the fairseq model (.pt) file.""") parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") lowercase_ = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
58
'''simple docstring''' from __future__ import annotations import unittest from transformers import AutoTokenizer, PegasusConfig, is_tf_available from transformers.testing_utils import require_sentencepiece, 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, TFPegasusForConditionalGeneration, TFPegasusModel @require_tf class a_ : '''simple docstring''' UpperCamelCase = PegasusConfig UpperCamelCase = {} UpperCamelCase = '''gelu''' def __init__( self , A , A=13 , A=7 , A=True , A=False , A=99 , A=32 , A=2 , A=4 , A=37 , A=0.1 , A=0.1 , A=40 , A=2 , A=1 , A=0 , ) -> Optional[int]: _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]: _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_pegasus_inputs_dict(A , A , A ) return config, inputs_dict def snake_case_( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFPegasusModel(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 lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : str , __lowerCamelCase : Optional[int] , __lowerCamelCase : int=None , __lowerCamelCase : Dict=None , __lowerCamelCase : Union[str, Any]=None , __lowerCamelCase : str=None , __lowerCamelCase : List[Any]=None , ) ->int: if attention_mask is None: _SCREAMING_SNAKE_CASE = tf.cast(tf.math.not_equal(__lowerCamelCase , 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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else () UpperCamelCase = (TFPegasusForConditionalGeneration,) if is_tf_available() else () UpperCamelCase = ( { '''conversational''': TFPegasusForConditionalGeneration, '''feature-extraction''': TFPegasusModel, '''summarization''': TFPegasusForConditionalGeneration, '''text2text-generation''': TFPegasusForConditionalGeneration, '''translation''': TFPegasusForConditionalGeneration, } if is_tf_available() else {} ) UpperCamelCase = True UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = TFPegasusModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A ) def snake_case_( self ) -> List[str]: self.config_tester.run_common_tests() def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*A ) @require_sentencepiece @require_tokenizers @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = [ ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''', ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''', ] UpperCamelCase = [ '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to''' ''' reduce the risk of wildfires.''', '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''', ] # differs slightly from pytorch, likely due to numerical differences in linear layers UpperCamelCase = '''google/pegasus-xsum''' @cached_property def snake_case_( self ) -> List[str]: return AutoTokenizer.from_pretrained(self.model_name ) @cached_property def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model def snake_case_( self , **A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.translate_src_text(**A ) assert self.expected_text == generated_words def snake_case_( self , **A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.tokenizer(self.src_text , **A , padding=A , 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 ) return generated_words @slow def snake_case_( self ) -> Any: self._assert_generated_batch_equal_expected()
58
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """microsoft/trocr-base-handwritten""": ( """https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json""" ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''trocr''' UpperCamelCase = ['''past_key_values'''] UpperCamelCase = { '''num_attention_heads''': '''decoder_attention_heads''', '''hidden_size''': '''d_model''', '''num_hidden_layers''': '''decoder_layers''', } def __init__( self , A=5_0265 , A=1024 , A=12 , A=16 , A=4096 , A="gelu" , A=512 , A=0.1 , A=0.0 , A=0.0 , A=2 , A=0.02 , A=0.0 , A=True , A=False , A=True , A=True , A=1 , A=0 , A=2 , **A , ) -> str: _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = d_model _SCREAMING_SNAKE_CASE = decoder_layers _SCREAMING_SNAKE_CASE = decoder_attention_heads _SCREAMING_SNAKE_CASE = decoder_ffn_dim _SCREAMING_SNAKE_CASE = activation_function _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = dropout _SCREAMING_SNAKE_CASE = attention_dropout _SCREAMING_SNAKE_CASE = activation_dropout _SCREAMING_SNAKE_CASE = init_std _SCREAMING_SNAKE_CASE = decoder_layerdrop _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = scale_embedding _SCREAMING_SNAKE_CASE = use_learned_position_embeddings _SCREAMING_SNAKE_CASE = layernorm_embedding super().__init__( pad_token_id=A , bos_token_id=A , eos_token_id=A , decoder_start_token_id=A , **A , )
58
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: 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(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
1
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : '''simple docstring''' def __init__( self , A , A=13 , A=32 , A=2 , A=3 , A=16 , A=[1, 2, 1] , A=[2, 2, 4] , A=2 , A=2.0 , A=True , A=0.0 , A=0.0 , A=0.1 , A="gelu" , A=False , A=True , A=0.02 , A=1e-5 , A=True , A=None , A=True , A=10 , A=8 , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = batch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = embed_dim _SCREAMING_SNAKE_CASE = depths _SCREAMING_SNAKE_CASE = num_heads _SCREAMING_SNAKE_CASE = window_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 = use_absolute_embeddings _SCREAMING_SNAKE_CASE = patch_norm _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = is_training _SCREAMING_SNAKE_CASE = scope _SCREAMING_SNAKE_CASE = use_labels _SCREAMING_SNAKE_CASE = type_sequence_label_size _SCREAMING_SNAKE_CASE = encoder_stride def snake_case_( self ) -> Union[str, Any]: _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.type_sequence_label_size ) _SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def snake_case_( self ) -> str: return SwinvaConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def snake_case_( self , A , A , A ) -> Dict: _SCREAMING_SNAKE_CASE = SwinvaModel(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A ) _SCREAMING_SNAKE_CASE = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _SCREAMING_SNAKE_CASE = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def snake_case_( self , A , A , A ) -> Tuple: _SCREAMING_SNAKE_CASE = SwinvaForMaskedImageModeling(config=A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _SCREAMING_SNAKE_CASE = 1 _SCREAMING_SNAKE_CASE = SwinvaForMaskedImageModeling(A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def snake_case_( self , A , A , A ) -> Dict: _SCREAMING_SNAKE_CASE = self.type_sequence_label_size _SCREAMING_SNAKE_CASE = SwinvaForImageClassification(A ) model.to(A ) model.eval() _SCREAMING_SNAKE_CASE = model(A , labels=A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def snake_case_( self ) -> List[str]: _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 a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) UpperCamelCase = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE = SwinvaModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A , embed_dim=37 ) def snake_case_( self ) -> Optional[int]: self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def snake_case_( self ) -> Optional[Any]: pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def snake_case_( self ) -> int: pass def snake_case_( self ) -> List[Any]: _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 ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(A , nn.Linear ) ) def snake_case_( self ) -> List[str]: _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: _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 = len(self.model_tester.depths ) self.assertEqual(len(A ) , A ) # check that output_attentions also work using config del inputs_dict["output_attentions"] _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = config.window_size**2 _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 ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) _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 ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): _SCREAMING_SNAKE_CASE = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states _SCREAMING_SNAKE_CASE = 2 self.assertEqual(out_len + added_hidden_states , len(A ) ) _SCREAMING_SNAKE_CASE = outputs.attentions self.assertEqual(len(A ) , A ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def snake_case_( self , A , A , A , A ) -> Dict: _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 = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(A ) , A ) # Swinv2 has a different seq_length _SCREAMING_SNAKE_CASE = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _SCREAMING_SNAKE_CASE = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) _SCREAMING_SNAKE_CASE = outputs.reshaped_hidden_states self.assertEqual(len(A ) , A ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = reshaped_hidden_states[0].shape _SCREAMING_SNAKE_CASE = ( reshaped_hidden_states[0].view(A , A , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(A , A , A , A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(A , A , A , A ) def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE = 3 _SCREAMING_SNAKE_CASE = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _SCREAMING_SNAKE_CASE = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _SCREAMING_SNAKE_CASE = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _SCREAMING_SNAKE_CASE = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(A , A , A , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE = True self.check_hidden_states_output(A , A , A , (padded_height, padded_width) ) def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*A ) def snake_case_( self ) -> Any: _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 ) -> List[str]: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _SCREAMING_SNAKE_CASE = SwinvaModel.from_pretrained(A ) self.assertIsNotNone(A ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() _SCREAMING_SNAKE_CASE = _config_zero_init(A ) for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE = model_class(config=A ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) @require_vision @require_torch class a_ ( unittest.TestCase ): '''simple docstring''' @cached_property def snake_case_( self ) -> Optional[Any]: return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( A ) _SCREAMING_SNAKE_CASE = self.default_image_processor _SCREAMING_SNAKE_CASE = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) _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, 1000) ) self.assertEqual(outputs.logits.shape , A ) _SCREAMING_SNAKE_CASE = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , A , atol=1e-4 ) )
58
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase_ = None lowercase_ = """<""" if sys.byteorder == """little""" else """>""" # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase_ = [ np.dtype("""|b1"""), np.dtype("""|u1"""), np.dtype("""<u2"""), np.dtype(""">u2"""), np.dtype("""<i2"""), np.dtype(""">i2"""), np.dtype("""<u4"""), np.dtype(""">u4"""), np.dtype("""<i4"""), np.dtype(""">i4"""), np.dtype("""<f4"""), np.dtype(""">f4"""), np.dtype("""<f8"""), np.dtype(""">f8"""), ] @dataclass class a_ : '''simple docstring''' UpperCamelCase = True UpperCamelCase = None # Automatically constructed UpperCamelCase = "PIL.Image.Image" UpperCamelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) UpperCamelCase = field(default='''Image''' , init=snake_case_ , repr=snake_case_ ) def __call__( self ) -> Tuple: return self.pa_type def snake_case_( self , A ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if isinstance(A , A ): _SCREAMING_SNAKE_CASE = np.array(A ) if isinstance(A , A ): return {"path": value, "bytes": None} elif isinstance(A , A ): return {"path": None, "bytes": value} elif isinstance(A , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(A ) elif isinstance(A , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(A ) elif value.get("""path""" ) is not None and os.path.isfile(value["""path"""] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("""path""" )} elif value.get("""bytes""" ) is not None or value.get("""path""" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("""bytes""" ), "path": value.get("""path""" )} else: raise ValueError( f'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.' ) def snake_case_( self , A , A=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead.""" ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support decoding images, please install 'Pillow'.""" ) if token_per_repo_id is None: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = value["""path"""], value["""bytes"""] if bytes_ is None: if path is None: raise ValueError(f'An image should have one of \'path\' or \'bytes\' but both are None in {value}.' ) else: if is_local_path(A ): _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) else: _SCREAMING_SNAKE_CASE = path.split("""::""" )[-1] try: _SCREAMING_SNAKE_CASE = string_to_dict(A , config.HUB_DATASETS_URL )["""repo_id"""] _SCREAMING_SNAKE_CASE = token_per_repo_id.get(A ) except ValueError: _SCREAMING_SNAKE_CASE = None with xopen(A , """rb""" , use_auth_token=A ) as f: _SCREAMING_SNAKE_CASE = BytesIO(f.read() ) _SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: _SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def snake_case_( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("""binary""" ), "path": Value("""string""" ), } ) def snake_case_( self , A ) -> pa.StructArray: if pa.types.is_string(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("""bytes""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""bytes""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.binary() ) if storage.type.get_field_index("""path""" ) >= 0: _SCREAMING_SNAKE_CASE = storage.field("""path""" ) else: _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(A ) )["""bytes"""] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array([None] * len(A ) , type=pa.string() ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def snake_case_( self , A ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(A ): with xopen(A , """rb""" ) as f: _SCREAMING_SNAKE_CASE = f.read() return bytes_ _SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x["""path"""] ) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(A ) if path is not None else None for path in storage.field("""path""" ).to_pylist()] , type=pa.string() , ) _SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["""bytes""", """path"""] , mask=bytes_array.is_null() ) return array_cast(A , self.pa_type ) def lowerCamelCase ( ) ->List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() _SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->bytes: _SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): _SCREAMING_SNAKE_CASE = image.format else: _SCREAMING_SNAKE_CASE = """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF""" image.save(__lowerCamelCase , format=__lowerCamelCase ) return buffer.getvalue() def lowerCamelCase ( __lowerCamelCase : "PIL.Image.Image" ) ->dict: if hasattr(__lowerCamelCase , """filename""" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : np.ndarray ) ->dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) _SCREAMING_SNAKE_CASE = array.dtype _SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER _SCREAMING_SNAKE_CASE = dtype.kind _SCREAMING_SNAKE_CASE = dtype.itemsize _SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _SCREAMING_SNAKE_CASE = np.dtype("""|u1""" ) if dtype_kind not in ["u", "i"]: raise TypeError( F'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: _SCREAMING_SNAKE_CASE = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: _SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.dtype(__lowerCamelCase ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(F'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( F'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) _SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(__lowerCamelCase ) ) return {"path": None, "bytes": image_to_bytes(__lowerCamelCase )} def lowerCamelCase ( __lowerCamelCase : Union[List[str], List[dict], List[np.ndarray], List["PIL.Image.Image"]] ) ->List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("""To support encoding images, please install 'Pillow'.""" ) if objs: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = first_non_null_value(__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__lowerCamelCase , np.ndarray ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] elif isinstance(__lowerCamelCase , PIL.Image.Image ): _SCREAMING_SNAKE_CASE = no_op_if_value_is_null(__lowerCamelCase ) return [obj_to_image_dict_func(__lowerCamelCase ) for obj in objs] else: return objs else: return objs
58
1
'''simple docstring''' import math def lowerCamelCase ( __lowerCamelCase : int ) ->str: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 while num > 0: _SCREAMING_SNAKE_CASE = num % 8 _SCREAMING_SNAKE_CASE = octal + (remainder * math.floor(math.pow(10 , __lowerCamelCase ) )) counter += 1 _SCREAMING_SNAKE_CASE = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return F'0o{int(__lowerCamelCase )}' def lowerCamelCase ( ) ->None: print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
58
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """facebook/data2vec-text-base""": """https://huggingface.co/data2vec/resolve/main/config.json""", } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''data2vec-text''' def __init__( self , A=3_0522 , A=768 , A=12 , A=12 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=2 , A=0.02 , A=1e-12 , A=1 , A=0 , A=2 , A="absolute" , A=True , A=None , **A , ) -> int: super().__init__(pad_token_id=A , bos_token_id=A , eos_token_id=A , **A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = classifier_dropout class a_ ( snake_case_ ): '''simple docstring''' @property def snake_case_( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] )
58
1
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES lowercase_ = logging.get_logger(__name__) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = OrderedDict( [ # Model for Image-classsification ("""beit""", """FlaxBeitForImageClassification"""), ("""regnet""", """FlaxRegNetForImageClassification"""), ("""resnet""", """FlaxResNetForImageClassification"""), ("""vit""", """FlaxViTForImageClassification"""), ] ) lowercase_ = OrderedDict( [ ("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = 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"""), ] ) lowercase_ = OrderedDict( [ ("""bert""", """FlaxBertForNextSentencePrediction"""), ] ) lowercase_ = OrderedDict( [ ("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""), ("""whisper""", """FlaxWhisperForConditionalGeneration"""), ] ) lowercase_ = OrderedDict( [ ("""whisper""", """FlaxWhisperForAudioClassification"""), ] ) lowercase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) lowercase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) lowercase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) lowercase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) lowercase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_MAPPING lowercase_ = auto_class_update(FlaxAutoModel) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_PRETRAINING_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_MASKED_LM_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base""" ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="""sequence classification""" ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="""token classification""" ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction""" ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="""image classification""" ) class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING lowercase_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""") class a_ ( _BaseAutoModelClass ): '''simple docstring''' UpperCamelCase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING lowercase_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling""" )
58
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ) ->Union[str, Any]: for attribute in key.split(""".""" ): _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ) if weight_type is not None: _SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , __lowerCamelCase ).shape else: _SCREAMING_SNAKE_CASE = hf_pointer.shape assert hf_shape == value.shape, ( F'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' F' {value.shape} for {full_name}' ) if weight_type == "weight": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_g": _SCREAMING_SNAKE_CASE = value elif weight_type == "weight_v": _SCREAMING_SNAKE_CASE = value elif weight_type == "bias": _SCREAMING_SNAKE_CASE = value else: _SCREAMING_SNAKE_CASE = value logger.info(F'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def lowerCamelCase ( __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any] ) ->Any: _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = fairseq_model.state_dict() _SCREAMING_SNAKE_CASE = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): _SCREAMING_SNAKE_CASE = False if "conv_layers" in name: load_conv_layer( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , hf_model.config.feat_extract_norm == """group""" , ) _SCREAMING_SNAKE_CASE = True else: for key, mapped_key in MAPPING.items(): _SCREAMING_SNAKE_CASE = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned): _SCREAMING_SNAKE_CASE = True if "*" in mapped_key: _SCREAMING_SNAKE_CASE = name.split(__lowerCamelCase )[0].split(""".""" )[-2] _SCREAMING_SNAKE_CASE = mapped_key.replace("""*""" , __lowerCamelCase ) if "weight_g" in name: _SCREAMING_SNAKE_CASE = """weight_g""" elif "weight_v" in name: _SCREAMING_SNAKE_CASE = """weight_v""" elif "weight" in name: _SCREAMING_SNAKE_CASE = """weight""" elif "bias" in name: _SCREAMING_SNAKE_CASE = """bias""" else: _SCREAMING_SNAKE_CASE = None set_recursively(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) continue if not is_used: unused_weights.append(__lowerCamelCase ) logger.warning(F'Unused weights: {unused_weights}' ) def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Any , __lowerCamelCase : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] ) ->Union[str, Any]: _SCREAMING_SNAKE_CASE = full_name.split("""conv_layers.""" )[-1] _SCREAMING_SNAKE_CASE = name.split(""".""" ) _SCREAMING_SNAKE_CASE = int(items[0] ) _SCREAMING_SNAKE_CASE = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'{full_name} has size {value.shape}, but' F' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) _SCREAMING_SNAKE_CASE = value logger.info(F'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(__lowerCamelCase ) @torch.no_grad() def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : str , __lowerCamelCase : List[Any]=None , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Union[str, Any]=True ) ->Optional[int]: if config_path is not None: _SCREAMING_SNAKE_CASE = HubertConfig.from_pretrained(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertConfig() if is_finetuned: if dict_path: _SCREAMING_SNAKE_CASE = Dictionary.load(__lowerCamelCase ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq _SCREAMING_SNAKE_CASE = target_dict.pad_index _SCREAMING_SNAKE_CASE = target_dict.bos_index _SCREAMING_SNAKE_CASE = target_dict.eos_index _SCREAMING_SNAKE_CASE = len(target_dict.symbols ) _SCREAMING_SNAKE_CASE = os.path.join(__lowerCamelCase , """vocab.json""" ) if not os.path.isdir(__lowerCamelCase ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(__lowerCamelCase ) ) return os.makedirs(__lowerCamelCase , exist_ok=__lowerCamelCase ) with open(__lowerCamelCase , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(target_dict.indices , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( __lowerCamelCase , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = True if config.feat_extract_norm == """layer""" else False _SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0 , do_normalize=__lowerCamelCase , return_attention_mask=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=__lowerCamelCase , tokenizer=__lowerCamelCase ) processor.save_pretrained(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = HubertForCTC(__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = HubertModel(__lowerCamelCase ) if is_finetuned: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) _SCREAMING_SNAKE_CASE = model[0].eval() recursively_load_weights(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) hf_wavavec.save_pretrained(__lowerCamelCase ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) lowercase_ = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : int ) ->int: while second != 0: _SCREAMING_SNAKE_CASE = first & second first ^= second _SCREAMING_SNAKE_CASE = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowercase_ = int(input("""Enter the first number: """).strip()) lowercase_ = int(input("""Enter the second number: """).strip()) print(f"""{add(first, second) = }""")
58
'''simple docstring''' from string import ascii_lowercase, ascii_uppercase def lowerCamelCase ( __lowerCamelCase : str ) ->str: if not sentence: return "" _SCREAMING_SNAKE_CASE = dict(zip(__lowerCamelCase , __lowerCamelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->str: if number > 0: raise ValueError("""input must be a negative integer""" ) _SCREAMING_SNAKE_CASE = len(bin(__lowerCamelCase )[3:] ) _SCREAMING_SNAKE_CASE = bin(abs(__lowerCamelCase ) - (1 << binary_number_length) )[3:] _SCREAMING_SNAKE_CASE = ( ( """1""" + """0""" * (binary_number_length - len(__lowerCamelCase )) + twos_complement_number ) if number < 0 else """0""" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_vision_model''' def __init__( self , A=768 , A=12 , A=3 , A=16 , A=288 , A=1 , A=1e-05 , A=False , A=True , A=False , **A , ) -> Dict: super().__init__(**A ) _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = patch_size _SCREAMING_SNAKE_CASE = image_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = stop_gradient _SCREAMING_SNAKE_CASE = share_layernorm _SCREAMING_SNAKE_CASE = remove_last_layer @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower_text_model''' def __init__( self , A=5_0265 , A=768 , A=12 , A=12 , A=1 , A=3072 , A="gelu" , A=0.1 , A=0.1 , A=514 , A=1 , A=1e-05 , A=1 , A=0 , A=2 , A="absolute" , A=True , **A , ) -> Union[str, Any]: super().__init__(**A ) _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = intermediate_size _SCREAMING_SNAKE_CASE = hidden_dropout_prob _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = max_position_embeddings _SCREAMING_SNAKE_CASE = type_vocab_size _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = position_embedding_type _SCREAMING_SNAKE_CASE = use_cache _SCREAMING_SNAKE_CASE = pad_token_id _SCREAMING_SNAKE_CASE = bos_token_id _SCREAMING_SNAKE_CASE = eos_token_id @classmethod def snake_case_( cls , A , **A ) -> "PretrainedConfig": _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cls.get_config_dict(A , **A ) if config_dict.get("""model_type""" ) == "bridgetower": _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 a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''bridgetower''' def __init__( self , A=True , A="gelu" , A=768 , A=1 , A=1e-05 , A=False , A="add" , A=12 , A=6 , A=False , A=False , A=None , A=None , **A , ) -> Tuple: # TODO: remove this once the Hub files are updated. _SCREAMING_SNAKE_CASE = kwargs.pop("""text_config_dict""" , A ) _SCREAMING_SNAKE_CASE = kwargs.pop("""vision_config_dict""" , A ) super().__init__(**A ) _SCREAMING_SNAKE_CASE = share_cross_modal_transformer_layers _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = hidden_size _SCREAMING_SNAKE_CASE = initializer_factor _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = share_link_tower_layers _SCREAMING_SNAKE_CASE = link_tower_type _SCREAMING_SNAKE_CASE = num_attention_heads _SCREAMING_SNAKE_CASE = num_hidden_layers _SCREAMING_SNAKE_CASE = tie_word_embeddings _SCREAMING_SNAKE_CASE = init_layernorm_from_vision_encoder if text_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.""" ) if vision_config is None: _SCREAMING_SNAKE_CASE = {} logger.info("""`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.""" ) _SCREAMING_SNAKE_CASE = BridgeTowerTextConfig(**A ) _SCREAMING_SNAKE_CASE = BridgeTowerVisionConfig(**A ) @classmethod def snake_case_( cls , A , A , **A ) -> int: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **A ) def snake_case_( self ) -> List[Any]: _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
58
1
'''simple docstring''' class a_ : '''simple docstring''' def __init__( self , A , A ) -> int: _SCREAMING_SNAKE_CASE = name _SCREAMING_SNAKE_CASE = val def __str__( self ) -> Dict: return f'{self.__class__.__name__}({self.name}, {self.val})' def __lt__( self , A ) -> Any: return self.val < other.val class a_ : '''simple docstring''' def __init__( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = {} _SCREAMING_SNAKE_CASE = self.build_heap(A ) def __getitem__( self , A ) -> Any: return self.get_value(A ) def snake_case_( self , A ) -> Optional[int]: return (idx - 1) // 2 def snake_case_( self , A ) -> List[Any]: return idx * 2 + 1 def snake_case_( self , A ) -> Dict: return idx * 2 + 2 def snake_case_( self , A ) -> Tuple: return self.heap_dict[key] def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = len(A ) - 1 _SCREAMING_SNAKE_CASE = self.get_parent_idx(A ) for idx, i in enumerate(A ): _SCREAMING_SNAKE_CASE = idx _SCREAMING_SNAKE_CASE = i.val for i in range(A , -1 , -1 ): self.sift_down(A , A ) return array def snake_case_( self , A , A ) -> List[str]: while True: _SCREAMING_SNAKE_CASE = self.get_left_child_idx(A ) # noqa: E741 _SCREAMING_SNAKE_CASE = self.get_right_child_idx(A ) _SCREAMING_SNAKE_CASE = idx if l < len(A ) and array[l] < array[idx]: _SCREAMING_SNAKE_CASE = l if r < len(A ) and array[r] < array[smallest]: _SCREAMING_SNAKE_CASE = r if smallest != idx: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = array[smallest], array[idx] ( ( _SCREAMING_SNAKE_CASE ) , ( _SCREAMING_SNAKE_CASE ) , ) = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) _SCREAMING_SNAKE_CASE = smallest else: break def snake_case_( self , A ) -> int: _SCREAMING_SNAKE_CASE = self.get_parent_idx(A ) while p >= 0 and self.heap[p] > self.heap[idx]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.heap[idx], self.heap[p] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) _SCREAMING_SNAKE_CASE = p _SCREAMING_SNAKE_CASE = self.get_parent_idx(A ) def snake_case_( self ) -> Optional[Any]: return self.heap[0] def snake_case_( self ) -> Dict: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = self.heap[-1], self.heap[0] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) _SCREAMING_SNAKE_CASE = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 , self.heap ) return x def snake_case_( self , A ) -> Optional[int]: self.heap.append(A ) _SCREAMING_SNAKE_CASE = len(self.heap ) - 1 _SCREAMING_SNAKE_CASE = node.val self.sift_up(len(self.heap ) - 1 ) def snake_case_( self ) -> Optional[int]: return len(self.heap ) == 0 def snake_case_( self , A , A ) -> Any: assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" _SCREAMING_SNAKE_CASE = new_value _SCREAMING_SNAKE_CASE = new_value self.sift_up(self.idx_of_element[node] ) lowercase_ = Node("""R""", -1) lowercase_ = Node("""B""", 6) lowercase_ = Node("""A""", 3) lowercase_ = Node("""X""", 1) lowercase_ = Node("""E""", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array lowercase_ = MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("""Min Heap - before decrease key""") for i in my_min_heap.heap: print(i) print("""Min Heap - After decrease key of node [B -> -17]""") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
58
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowercase_ = logging.get_logger(__name__) # pylint: disable=invalid-name lowercase_ = """ Examples: ```py >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline >>> import torch >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-prior\") >>> pipe_prior.to(\"cuda\") >>> prompt = \"red cat, 4k photo\" >>> out = pipe_prior(prompt) >>> image_emb = out.image_embeds >>> zero_image_emb = out.negative_image_embeds >>> pipe = KandinskyV22Pipeline.from_pretrained(\"kandinsky-community/kandinsky-2-2-decoder\") >>> pipe.to(\"cuda\") >>> image = pipe( ... image_embeds=image_emb, ... negative_image_embeds=zero_image_emb, ... height=768, ... width=768, ... num_inference_steps=50, ... ).images >>> image[0].save(\"cat.png\") ``` """ def lowerCamelCase ( __lowerCamelCase : str , __lowerCamelCase : Optional[Any] , __lowerCamelCase : List[Any]=8 ) ->Tuple: _SCREAMING_SNAKE_CASE = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 _SCREAMING_SNAKE_CASE = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A , A , ) -> Union[str, Any]: super().__init__() self.register_modules( unet=A , scheduler=A , movq=A , ) _SCREAMING_SNAKE_CASE = 2 ** (len(self.movq.config.block_out_channels ) - 1) def snake_case_( self , A , A , A , A , A , A ) -> Union[str, Any]: if latents is None: _SCREAMING_SNAKE_CASE = randn_tensor(A , generator=A , device=A , dtype=A ) else: if latents.shape != shape: raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}' ) _SCREAMING_SNAKE_CASE = latents.to(A ) _SCREAMING_SNAKE_CASE = latents * scheduler.init_noise_sigma return latents def snake_case_( self , A=0 ) -> Dict: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) _SCREAMING_SNAKE_CASE = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A , A ) def snake_case_( self , A=0 ) -> str: if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ): from accelerate import cpu_offload_with_hook else: raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" ) _SCREAMING_SNAKE_CASE = torch.device(f'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to("""cpu""" , silence_dtype_warnings=A ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) _SCREAMING_SNAKE_CASE = None for cpu_offloaded_model in [self.unet, self.movq]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = cpu_offload_with_hook(A , A , prev_module_hook=A ) # We'll offload the last model manually. _SCREAMING_SNAKE_CASE = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def snake_case_( self ) -> Tuple: if not hasattr(self.unet , """_hf_hook""" ): return self.device for module in self.unet.modules(): if ( hasattr(A , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(A ) def __call__( self , A , A , A = 512 , A = 512 , A = 100 , A = 4.0 , A = 1 , A = None , A = None , A = "pil" , A = True , ) -> List[str]: _SCREAMING_SNAKE_CASE = self._execution_device _SCREAMING_SNAKE_CASE = guidance_scale > 1.0 if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) _SCREAMING_SNAKE_CASE = image_embeds.shape[0] * num_images_per_prompt if isinstance(A , A ): _SCREAMING_SNAKE_CASE = torch.cat(A , dim=0 ) if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE = image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = negative_image_embeds.repeat_interleave(A , dim=0 ) _SCREAMING_SNAKE_CASE = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A ) self.scheduler.set_timesteps(A , device=A ) _SCREAMING_SNAKE_CASE = self.scheduler.timesteps _SCREAMING_SNAKE_CASE = self.unet.config.in_channels _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = downscale_height_and_width(A , A , self.movq_scale_factor ) # create initial latent _SCREAMING_SNAKE_CASE = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A , A , A , self.scheduler , ) for i, t in enumerate(self.progress_bar(A ) ): # expand the latents if we are doing classifier free guidance _SCREAMING_SNAKE_CASE = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _SCREAMING_SNAKE_CASE = {"""image_embeds""": image_embeds} _SCREAMING_SNAKE_CASE = self.unet( sample=A , timestep=A , encoder_hidden_states=A , added_cond_kwargs=A , return_dict=A , )[0] if do_classifier_free_guidance: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.chunk(2 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = variance_pred.chunk(2 ) _SCREAMING_SNAKE_CASE = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) _SCREAMING_SNAKE_CASE = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , """variance_type""" ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 _SCREAMING_SNAKE_CASE = self.scheduler.step( A , A , A , generator=A , )[0] # post-processing _SCREAMING_SNAKE_CASE = self.movq.decode(A , force_not_quantize=A )["""sample"""] if output_type not in ["pt", "np", "pil"]: raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: _SCREAMING_SNAKE_CASE = image * 0.5 + 0.5 _SCREAMING_SNAKE_CASE = image.clamp(0 , 1 ) _SCREAMING_SNAKE_CASE = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": _SCREAMING_SNAKE_CASE = self.numpy_to_pil(A ) if not return_dict: return (image,) return ImagePipelineOutput(images=A )
58
1
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
'''simple docstring''' import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowercase_ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowercase_ , lowercase_ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowercase_ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowercase_ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowercase_ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {" ".join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int ) ->int: return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def lowerCamelCase ( __lowerCamelCase : int ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = number while duplicate > 0: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = divmod(__lowerCamelCase , 10 ) fact_sum += factorial(__lowerCamelCase ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") lowercase_ = int(input("""Enter number: """).strip()) print( f"""{number} is {"" if krishnamurthy(number) else "not "}a Krishnamurthy Number.""" )
58
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_poolformer import PoolFormerConfig lowercase_ = logging.get_logger(__name__) # General docstring lowercase_ = """PoolFormerConfig""" # Base docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = [1, 512, 7, 7] # Image classification docstring lowercase_ = """sail/poolformer_s12""" lowercase_ = """tabby, tabby cat""" lowercase_ = [ """sail/poolformer_s12""", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowerCamelCase ( __lowerCamelCase : List[Any] , __lowerCamelCase : float = 0.0 , __lowerCamelCase : bool = False ) ->int: if drop_prob == 0.0 or not training: return input _SCREAMING_SNAKE_CASE = 1 - drop_prob _SCREAMING_SNAKE_CASE = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets _SCREAMING_SNAKE_CASE = keep_prob + torch.rand(__lowerCamelCase , dtype=input.dtype , device=input.device ) random_tensor.floor_() # binarize _SCREAMING_SNAKE_CASE = input.div(__lowerCamelCase ) * random_tensor return output class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A = None ) -> None: super().__init__() _SCREAMING_SNAKE_CASE = drop_prob def snake_case_( self , A ) -> torch.Tensor: return drop_path(A , self.drop_prob , self.training ) def snake_case_( self ) -> str: return "p={}".format(self.drop_prob ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A=None ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = patch_size if isinstance(A , collections.abc.Iterable ) else (patch_size, patch_size) _SCREAMING_SNAKE_CASE = stride if isinstance(A , collections.abc.Iterable ) else (stride, stride) _SCREAMING_SNAKE_CASE = padding if isinstance(A , collections.abc.Iterable ) else (padding, padding) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , kernel_size=A , stride=A , padding=A ) _SCREAMING_SNAKE_CASE = norm_layer(A ) if norm_layer else nn.Identity() def snake_case_( self , A ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.projection(A ) _SCREAMING_SNAKE_CASE = self.norm(A ) return embeddings class a_ ( nn.GroupNorm ): '''simple docstring''' def __init__( self , A , **A ) -> Union[str, Any]: super().__init__(1 , A , **A ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.AvgPoolad(A , stride=1 , padding=pool_size // 2 , count_include_pad=A ) def snake_case_( self , A ) -> Union[str, Any]: return self.pool(A ) - hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A ) -> List[Any]: super().__init__() _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = nn.Convad(A , A , 1 ) _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if isinstance(config.hidden_act , A ): _SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] else: _SCREAMING_SNAKE_CASE = config.hidden_act def snake_case_( self , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.act_fn(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) _SCREAMING_SNAKE_CASE = self.conva(A ) _SCREAMING_SNAKE_CASE = self.drop(A ) return hidden_states class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A , A , A , A , A , A ) -> Union[str, Any]: super().__init__() _SCREAMING_SNAKE_CASE = PoolFormerPooling(A ) _SCREAMING_SNAKE_CASE = PoolFormerOutput(A , A , A , A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(A ) # Useful for training neural nets _SCREAMING_SNAKE_CASE = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() _SCREAMING_SNAKE_CASE = config.use_layer_scale if config.use_layer_scale: _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) _SCREAMING_SNAKE_CASE = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ) , requires_grad=A ) def snake_case_( self , A ) -> Optional[Any]: if self.use_layer_scale: _SCREAMING_SNAKE_CASE = self.pooling(self.before_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = () _SCREAMING_SNAKE_CASE = self.output(self.after_norm(A ) ) _SCREAMING_SNAKE_CASE = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection _SCREAMING_SNAKE_CASE = hidden_states + self.drop_path(A ) _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs else: _SCREAMING_SNAKE_CASE = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection _SCREAMING_SNAKE_CASE = pooling_output + hidden_states _SCREAMING_SNAKE_CASE = () # Second residual connection inside the PoolFormerOutput block _SCREAMING_SNAKE_CASE = self.drop_path(self.output(self.after_norm(A ) ) ) _SCREAMING_SNAKE_CASE = hidden_states + layer_output _SCREAMING_SNAKE_CASE = (output,) + outputs return outputs class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Any: super().__init__() _SCREAMING_SNAKE_CASE = config # stochastic depth decay rule _SCREAMING_SNAKE_CASE = [x.item() for x in torch.linspace(0 , config.drop_path_rate , sum(config.depths ) )] # patch embeddings _SCREAMING_SNAKE_CASE = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i] , stride=config.strides[i] , padding=config.padding[i] , num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1] , hidden_size=config.hidden_sizes[i] , ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) # Transformer blocks _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers _SCREAMING_SNAKE_CASE = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A , num_channels=config.hidden_sizes[i] , pool_size=config.pool_size , hidden_size=config.hidden_sizes[i] , intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ) , drop_path=dpr[cur + j] , ) ) blocks.append(nn.ModuleList(A ) ) _SCREAMING_SNAKE_CASE = nn.ModuleList(A ) def snake_case_( self , A , A=False , A=True ) -> List[Any]: _SCREAMING_SNAKE_CASE = () if output_hidden_states else None _SCREAMING_SNAKE_CASE = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings , self.block ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = layers # Get patch embeddings from hidden_states _SCREAMING_SNAKE_CASE = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): _SCREAMING_SNAKE_CASE = blk(A ) _SCREAMING_SNAKE_CASE = layer_outputs[0] if output_hidden_states: _SCREAMING_SNAKE_CASE = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A , hidden_states=A ) class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = PoolFormerConfig UpperCamelCase = '''poolformer''' UpperCamelCase = '''pixel_values''' UpperCamelCase = True def snake_case_( self , A ) -> int: if isinstance(A , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(A , nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def snake_case_( self , A , A=False ) -> Dict: if isinstance(A , A ): _SCREAMING_SNAKE_CASE = value lowercase_ = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ lowercase_ = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`PoolFormerImageProcessor.__call__`] for details. """ @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> int: super().__init__(A ) _SCREAMING_SNAKE_CASE = config _SCREAMING_SNAKE_CASE = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def snake_case_( self ) -> Any: return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=A , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def snake_case_( self , A = None , A = None , A = None , ) -> Union[Tuple, BaseModelOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError("""You have to specify pixel_values""" ) _SCREAMING_SNAKE_CASE = self.encoder( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A , hidden_states=encoder_outputs.hidden_states , ) class a_ ( nn.Module ): '''simple docstring''' def __init__( self , A ) -> Dict: super().__init__() _SCREAMING_SNAKE_CASE = nn.Linear(config.hidden_size , config.hidden_size ) def snake_case_( self , A ) -> str: _SCREAMING_SNAKE_CASE = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , snake_case_ , ) class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A ) -> Optional[Any]: super().__init__(A ) _SCREAMING_SNAKE_CASE = config.num_labels _SCREAMING_SNAKE_CASE = PoolFormerModel(A ) # Final norm _SCREAMING_SNAKE_CASE = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head _SCREAMING_SNAKE_CASE = ( nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=A , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def snake_case_( self , A = None , A = None , A = None , A = None , ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]: _SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict _SCREAMING_SNAKE_CASE = self.poolformer( A , output_hidden_states=A , return_dict=A , ) _SCREAMING_SNAKE_CASE = outputs[0] _SCREAMING_SNAKE_CASE = self.classifier(self.norm(A ).mean([-2, -1] ) ) _SCREAMING_SNAKE_CASE = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _SCREAMING_SNAKE_CASE = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _SCREAMING_SNAKE_CASE = """single_label_classification""" else: _SCREAMING_SNAKE_CASE = """multi_label_classification""" if self.config.problem_type == "regression": _SCREAMING_SNAKE_CASE = MSELoss() if self.num_labels == 1: _SCREAMING_SNAKE_CASE = loss_fct(logits.squeeze() , labels.squeeze() ) else: _SCREAMING_SNAKE_CASE = loss_fct(A , A ) elif self.config.problem_type == "single_label_classification": _SCREAMING_SNAKE_CASE = CrossEntropyLoss() _SCREAMING_SNAKE_CASE = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _SCREAMING_SNAKE_CASE = BCEWithLogitsLoss() _SCREAMING_SNAKE_CASE = loss_fct(A , A ) if not return_dict: _SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A , logits=A , hidden_states=outputs.hidden_states )
58
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class a_ : '''simple docstring''' def __init__( self , A , A=13 , A=7 , A=True , A=True , A=True , A=True , A=99 , A=32 , A=2 , A=4 , A=37 , A="gelu" , A=0.1 , A=0.1 , A=512 , A=16 , A=2 , A=0.02 , A=3 , A=4 , A=None , ) -> Optional[int]: _SCREAMING_SNAKE_CASE = parent _SCREAMING_SNAKE_CASE = 13 _SCREAMING_SNAKE_CASE = 7 _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = True _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.02 _SCREAMING_SNAKE_CASE = 3 _SCREAMING_SNAKE_CASE = 4 _SCREAMING_SNAKE_CASE = None def snake_case_( self ) -> Any: _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 = RoFormerConfig( 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 , initializer_range=self.initializer_range , return_dict=A , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case_( self , A , A , A , A , A , A , A ) -> Tuple: _SCREAMING_SNAKE_CASE = TFRoFormerModel(config=A ) _SCREAMING_SNAKE_CASE = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids} _SCREAMING_SNAKE_CASE = [input_ids, input_mask] _SCREAMING_SNAKE_CASE = model(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 , A , A , A , A , A , A , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = True _SCREAMING_SNAKE_CASE = TFRoFormerForCausalLM(config=A ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _SCREAMING_SNAKE_CASE = model(A )["""logits"""] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_size] ) def snake_case_( self , A , A , A , A , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM(config=A ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case_( self , A , A , A , A , A , A , A ) -> int: _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = TFRoFormerForSequenceClassification(config=A ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def snake_case_( self , A , A , A , A , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.num_choices _SCREAMING_SNAKE_CASE = TFRoFormerForMultipleChoice(config=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 = 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, """token_type_ids""": multiple_choice_token_type_ids, } _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def snake_case_( self , A , A , A , A , A , A , A ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.num_labels _SCREAMING_SNAKE_CASE = TFRoFormerForTokenClassification(config=A ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _SCREAMING_SNAKE_CASE = model(A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def snake_case_( self , A , A , A , A , A , A , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = TFRoFormerForQuestionAnswering(config=A ) _SCREAMING_SNAKE_CASE = { """input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids, } _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 ) -> List[str]: _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, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_tf class a_ ( snake_case_ , snake_case_ , unittest.TestCase ): '''simple docstring''' UpperCamelCase = ( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) UpperCamelCase = ( { '''feature-extraction''': TFRoFormerModel, '''fill-mask''': TFRoFormerForMaskedLM, '''question-answering''': TFRoFormerForQuestionAnswering, '''text-classification''': TFRoFormerForSequenceClassification, '''text-generation''': TFRoFormerForCausalLM, '''token-classification''': TFRoFormerForTokenClassification, '''zero-shot''': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase = False UpperCamelCase = False def snake_case_( self , A , A , A , A , A ) -> List[Any]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = TFRoFormerModelTester(self ) _SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=A , hidden_size=37 ) def snake_case_( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*A ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*A ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) def snake_case_( self ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) @slow def snake_case_( self ) -> int: _SCREAMING_SNAKE_CASE = TFRoFormerModel.from_pretrained("""junnyu/roformer_chinese_base""" ) self.assertIsNotNone(A ) @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' @slow def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = TFRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base""" ) _SCREAMING_SNAKE_CASE = tf.constant([[0, 1, 2, 3, 4, 5]] ) _SCREAMING_SNAKE_CASE = model(A )[0] # TODO Replace vocab size _SCREAMING_SNAKE_CASE = 5_0000 _SCREAMING_SNAKE_CASE = [1, 6, vocab_size] self.assertEqual(output.shape , A ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. _SCREAMING_SNAKE_CASE = tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , A , atol=1e-4 ) @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = 1E-4 def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = tf.constant([[4, 10]] ) _SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) _SCREAMING_SNAKE_CASE = emba(input_ids.shape ) _SCREAMING_SNAKE_CASE = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(A , A , atol=self.tolerance ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) _SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) _SCREAMING_SNAKE_CASE = emba.weight[:3, :5] tf.debugging.assert_near(A , A , atol=self.tolerance ) @require_tf class a_ ( unittest.TestCase ): '''simple docstring''' UpperCamelCase = 1E-4 def snake_case_( self ) -> Union[str, Any]: # 2,12,16,64 _SCREAMING_SNAKE_CASE = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 _SCREAMING_SNAKE_CASE = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 _SCREAMING_SNAKE_CASE = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) _SCREAMING_SNAKE_CASE = embed_positions([2, 16, 768] )[None, None, :, :] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = TFRoFormerSelfAttention.apply_rotary_position_embeddings( A , A , A ) _SCREAMING_SNAKE_CASE = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) _SCREAMING_SNAKE_CASE = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , A , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , A , atol=self.tolerance )
58
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) lowercase_ = logging.getLogger(__name__) lowercase_ = """Hello world! cécé herlolip""" lowercase_ = namedtuple( """BertAbsConfig""", [ """temp_dir""", """large""", """use_bert_emb""", """finetune_bert""", """encoder""", """share_emb""", """max_pos""", """enc_layers""", """enc_hidden_size""", """enc_heads""", """enc_ff_size""", """enc_dropout""", """dec_layers""", """dec_hidden_size""", """dec_heads""", """dec_ff_size""", """dec_dropout""", ], ) def lowerCamelCase ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] ) ->List[Any]: _SCREAMING_SNAKE_CASE = BertAbsConfig( temp_dir=""".""" , finetune_bert=__lowerCamelCase , large=__lowerCamelCase , share_emb=__lowerCamelCase , use_bert_emb=__lowerCamelCase , encoder="""bert""" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) _SCREAMING_SNAKE_CASE = torch.load(__lowerCamelCase , lambda __lowerCamelCase , __lowerCamelCase : storage ) _SCREAMING_SNAKE_CASE = AbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) , __lowerCamelCase ) original.eval() _SCREAMING_SNAKE_CASE = BertAbsSummarizer(__lowerCamelCase , torch.device("""cpu""" ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("""convert the model""" ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("""Make sure that the models' outputs are identical""" ) _SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("""bert-base-uncased""" ) # prepare the model inputs _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample éàalj'-.""" ) encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) _SCREAMING_SNAKE_CASE = tokenizer.encode("""This is sample 3 éàalj'-.""" ) decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(__lowerCamelCase )) ) _SCREAMING_SNAKE_CASE = torch.tensor(__lowerCamelCase ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass _SCREAMING_SNAKE_CASE = encoder_input_ids _SCREAMING_SNAKE_CASE = decoder_input_ids _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical _SCREAMING_SNAKE_CASE = original(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = original.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = new_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )[0] _SCREAMING_SNAKE_CASE = new_model.generator(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print("""Maximum absolute difference beween weights: {:.2f}""".format(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = torch.allclose(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) if are_identical: logging.info("""all weights are equal up to 1e-3""" ) else: raise ValueError("""the weights are different. The new model is likely different from the original one.""" ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("""saving the model's state dictionary""" ) torch.save( new_model.state_dict() , """./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin""" ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument( """--bertabs_checkpoint_path""", default=None, type=str, required=True, help="""Path the official PyTorch dump.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""", ) lowercase_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
58
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { """vinvino02/glpn-kitti""": """https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json""", # See all GLPN models at https://huggingface.co/models?filter=glpn } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = '''glpn''' def __init__( self , A=3 , A=4 , A=[2, 2, 2, 2] , A=[8, 4, 2, 1] , A=[32, 64, 160, 256] , A=[7, 3, 3, 3] , A=[4, 2, 2, 2] , A=[1, 2, 5, 8] , A=[4, 4, 4, 4] , A="gelu" , A=0.0 , A=0.0 , A=0.02 , A=0.1 , A=1e-6 , A=64 , A=10 , A=-1 , **A , ) -> Any: super().__init__(**A ) _SCREAMING_SNAKE_CASE = num_channels _SCREAMING_SNAKE_CASE = num_encoder_blocks _SCREAMING_SNAKE_CASE = depths _SCREAMING_SNAKE_CASE = sr_ratios _SCREAMING_SNAKE_CASE = hidden_sizes _SCREAMING_SNAKE_CASE = patch_sizes _SCREAMING_SNAKE_CASE = strides _SCREAMING_SNAKE_CASE = mlp_ratios _SCREAMING_SNAKE_CASE = num_attention_heads _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 = drop_path_rate _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = decoder_hidden_size _SCREAMING_SNAKE_CASE = max_depth _SCREAMING_SNAKE_CASE = head_in_index
58
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a_ ( snake_case_ ): '''simple docstring''' def snake_case_( self ) -> Tuple: return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def snake_case_( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = {"""col_1""": [3, 2, 1, 0], """col_2""": ["""a""", """b""", """c""", """d"""]} return Dataset.from_dict(A ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertListEqual(dset.column_names , ["""col_1""", """col_2"""] ) for i, r in enumerate(A ): self.assertDictEqual(A , example_records[i] ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self._create_example_records() _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) _SCREAMING_SNAKE_CASE = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def snake_case_( self ) -> Union[str, Any]: # checks what happens with missing columns _SCREAMING_SNAKE_CASE = [{"""col_1""": 1}, {"""col_2""": """x"""}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertDictEqual(dset[0] , {"""col_1""": 1} ) self.assertDictEqual(dset[1] , {"""col_1""": None} ) # NB: first record is used for columns def snake_case_( self ) -> Optional[Any]: # checks if the type can be inferred from the second record _SCREAMING_SNAKE_CASE = [{"""col_1""": []}, {"""col_1""": [1, 2]}] _SCREAMING_SNAKE_CASE = Dataset.from_list(A ) self.assertEqual(dset.info.features["""col_1"""] , Sequence(Value("""int64""" ) ) ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = Dataset.from_list([] ) self.assertEqual(len(A ) , 0 ) self.assertListEqual(dset.column_names , [] )
58
1
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: 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(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
'''simple docstring''' import argparse import os import re import numpy as np import PIL import torch from timm import create_model from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import DataLoader, Dataset from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor from accelerate import Accelerator def lowerCamelCase ( __lowerCamelCase : Tuple ) ->Tuple: _SCREAMING_SNAKE_CASE = fname.split(os.path.sep )[-1] return re.search(R"""^(.*)_\d+\.jpg$""" , __lowerCamelCase ).groups()[0] class a_ ( snake_case_ ): '''simple docstring''' def __init__( self , A , A=None , A=None ) -> int: _SCREAMING_SNAKE_CASE = file_names _SCREAMING_SNAKE_CASE = image_transform _SCREAMING_SNAKE_CASE = label_to_id def __len__( self ) -> Optional[Any]: return len(self.file_names ) def __getitem__( self , A ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.file_names[idx] _SCREAMING_SNAKE_CASE = PIL.Image.open(A ) _SCREAMING_SNAKE_CASE = raw_image.convert("""RGB""" ) if self.image_transform is not None: _SCREAMING_SNAKE_CASE = self.image_transform(A ) _SCREAMING_SNAKE_CASE = extract_label(A ) if self.label_to_id is not None: _SCREAMING_SNAKE_CASE = self.label_to_id[label] return {"image": image, "label": label} def lowerCamelCase ( __lowerCamelCase : Any , __lowerCamelCase : Tuple ) ->str: # Initialize accelerator if args.with_tracking: _SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir ) else: _SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs _SCREAMING_SNAKE_CASE = config["""lr"""] _SCREAMING_SNAKE_CASE = int(config["""num_epochs"""] ) _SCREAMING_SNAKE_CASE = int(config["""seed"""] ) _SCREAMING_SNAKE_CASE = int(config["""batch_size"""] ) _SCREAMING_SNAKE_CASE = config["""image_size"""] if not isinstance(__lowerCamelCase , (list, tuple) ): _SCREAMING_SNAKE_CASE = (image_size, image_size) # Parse out whether we are saving every epoch or after a certain number of batches if hasattr(args.checkpointing_steps , """isdigit""" ): if args.checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = args.checkpointing_steps elif args.checkpointing_steps.isdigit(): _SCREAMING_SNAKE_CASE = int(args.checkpointing_steps ) else: raise ValueError( F'Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.' ) else: _SCREAMING_SNAKE_CASE = None # We need to initialize the trackers we use, and also store our configuration if args.with_tracking: _SCREAMING_SNAKE_CASE = os.path.split(__lowerCamelCase )[-1].split(""".""" )[0] accelerator.init_trackers(__lowerCamelCase , __lowerCamelCase ) # Grab all the image filenames _SCREAMING_SNAKE_CASE = [os.path.join(args.data_dir , __lowerCamelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )] # Build the label correspondences _SCREAMING_SNAKE_CASE = [extract_label(__lowerCamelCase ) for fname in file_names] _SCREAMING_SNAKE_CASE = list(set(__lowerCamelCase ) ) id_to_label.sort() _SCREAMING_SNAKE_CASE = {lbl: i for i, lbl in enumerate(__lowerCamelCase )} # Set the seed before splitting the data. np.random.seed(__lowerCamelCase ) torch.manual_seed(__lowerCamelCase ) torch.cuda.manual_seed_all(__lowerCamelCase ) # Split our filenames between train and validation _SCREAMING_SNAKE_CASE = np.random.permutation(len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = int(0.8 * len(__lowerCamelCase ) ) _SCREAMING_SNAKE_CASE = random_perm[:cut] _SCREAMING_SNAKE_CASE = random_perm[cut:] # For training we use a simple RandomResizedCrop _SCREAMING_SNAKE_CASE = Compose([RandomResizedCrop(__lowerCamelCase , scale=(0.5, 1.0) ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset( [file_names[i] for i in train_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # For evaluation, we use a deterministic Resize _SCREAMING_SNAKE_CASE = Compose([Resize(__lowerCamelCase ), ToTensor()] ) _SCREAMING_SNAKE_CASE = PetsDataset([file_names[i] for i in eval_split] , image_transform=__lowerCamelCase , label_to_id=__lowerCamelCase ) # Instantiate dataloaders. _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) _SCREAMING_SNAKE_CASE = DataLoader(__lowerCamelCase , shuffle=__lowerCamelCase , batch_size=__lowerCamelCase , num_workers=4 ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) _SCREAMING_SNAKE_CASE = create_model("""resnet50d""" , pretrained=__lowerCamelCase , num_classes=len(__lowerCamelCase ) ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). _SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Freezing the base model for param in model.parameters(): _SCREAMING_SNAKE_CASE = False for param in model.get_classifier().parameters(): _SCREAMING_SNAKE_CASE = True # We normalize the batches of images to be a bit faster. _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device ) _SCREAMING_SNAKE_CASE = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device ) # Instantiate optimizer _SCREAMING_SNAKE_CASE = torch.optim.Adam(params=model.parameters() , lr=lr / 25 ) # Instantiate learning rate scheduler _SCREAMING_SNAKE_CASE = OneCycleLR(optimizer=__lowerCamelCase , max_lr=__lowerCamelCase , epochs=__lowerCamelCase , steps_per_epoch=len(__lowerCamelCase ) ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.prepare( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # We need to keep track of how many total steps we have iterated over _SCREAMING_SNAKE_CASE = 0 # We also need to keep track of the starting epoch so files are named properly _SCREAMING_SNAKE_CASE = 0 # Potentially load in the weights and states from a previous save if args.resume_from_checkpoint: if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": accelerator.print(F'Resumed from checkpoint: {args.resume_from_checkpoint}' ) accelerator.load_state(args.resume_from_checkpoint ) _SCREAMING_SNAKE_CASE = os.path.basename(args.resume_from_checkpoint ) else: # Get the most recent checkpoint _SCREAMING_SNAKE_CASE = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()] dirs.sort(key=os.path.getctime ) _SCREAMING_SNAKE_CASE = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last # Extract `epoch_{i}` or `step_{i}` _SCREAMING_SNAKE_CASE = os.path.splitext(__lowerCamelCase )[0] if "epoch" in training_difference: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""epoch_""" , """""" ) ) + 1 _SCREAMING_SNAKE_CASE = None else: _SCREAMING_SNAKE_CASE = int(training_difference.replace("""step_""" , """""" ) ) _SCREAMING_SNAKE_CASE = resume_step // len(__lowerCamelCase ) resume_step -= starting_epoch * len(__lowerCamelCase ) # Now we train the model for epoch in range(__lowerCamelCase , __lowerCamelCase ): model.train() if args.with_tracking: _SCREAMING_SNAKE_CASE = 0 if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: # We need to skip steps until we reach the resumed step _SCREAMING_SNAKE_CASE = accelerator.skip_first_batches(__lowerCamelCase , __lowerCamelCase ) overall_step += resume_step else: # After the first iteration though, we need to go back to the original dataloader _SCREAMING_SNAKE_CASE = train_dataloader for batch in active_dataloader: # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.nn.functional.cross_entropy(__lowerCamelCase , batch["""label"""] ) # We keep track of the loss at each epoch if args.with_tracking: total_loss += loss.detach().float() accelerator.backward(__lowerCamelCase ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 if isinstance(__lowerCamelCase , __lowerCamelCase ): _SCREAMING_SNAKE_CASE = F'step_{overall_step}' if overall_step % checkpointing_steps == 0: if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) model.eval() _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 for step, batch in enumerate(__lowerCamelCase ): # We could avoid this line since we set the accelerator with `device_placement=True`. _SCREAMING_SNAKE_CASE = {k: v.to(accelerator.device ) for k, v in batch.items()} _SCREAMING_SNAKE_CASE = (batch["""image"""] - mean) / std with torch.no_grad(): _SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.argmax(dim=-1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["""label"""]) ) _SCREAMING_SNAKE_CASE = predictions == references num_elems += accurate_preds.shape[0] accurate += accurate_preds.long().sum() _SCREAMING_SNAKE_CASE = accurate.item() / num_elems # Use accelerator.print to print only on the main process. accelerator.print(F'epoch {epoch}: {100 * eval_metric:.2f}' ) if args.with_tracking: accelerator.log( { """accuracy""": 100 * eval_metric, """train_loss""": total_loss.item() / len(__lowerCamelCase ), """epoch""": epoch, } , step=__lowerCamelCase , ) if checkpointing_steps == "epoch": _SCREAMING_SNAKE_CASE = F'epoch_{epoch}' if args.output_dir is not None: _SCREAMING_SNAKE_CASE = os.path.join(args.output_dir , __lowerCamelCase ) accelerator.save_state(__lowerCamelCase ) if args.with_tracking: accelerator.end_training() def lowerCamelCase ( ) ->int: _SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="""Simple example of training script.""" ) parser.add_argument("""--data_dir""" , required=__lowerCamelCase , help="""The data folder on disk.""" ) parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" ) parser.add_argument( """--mixed_precision""" , type=__lowerCamelCase , default=__lowerCamelCase , choices=["""no""", """fp16""", """bf16""", """fp8"""] , help="""Whether to use mixed precision. Choose""" """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.""" """and an Nvidia Ampere GPU.""" , ) parser.add_argument("""--cpu""" , action="""store_true""" , help="""If passed, will train on the CPU.""" ) parser.add_argument( """--checkpointing_steps""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , ) parser.add_argument( """--output_dir""" , type=__lowerCamelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , ) parser.add_argument( """--resume_from_checkpoint""" , type=__lowerCamelCase , default=__lowerCamelCase , help="""If the training should continue from a checkpoint folder.""" , ) parser.add_argument( """--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , ) parser.add_argument( """--project_dir""" , type=__lowerCamelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , ) _SCREAMING_SNAKE_CASE = parser.parse_args() _SCREAMING_SNAKE_CASE = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224} training_function(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": main()
58
1
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class a_ ( unittest.TestCase ): '''simple docstring''' def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = """laion/clap-htsat-unfused""" _SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def snake_case_( self , **A ) -> int: return RobertaTokenizer.from_pretrained(self.checkpoint , **A ) def snake_case_( self , **A ) -> Optional[int]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **A ) def snake_case_( self ) -> Dict: shutil.rmtree(self.tmpdirname ) def snake_case_( self ) -> Union[str, Any]: _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = self.get_feature_extractor() _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=A , feature_extractor=A ) processor.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , A ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , A ) def snake_case_( self ) -> List[str]: _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) _SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=A , padding_value=1.0 ) _SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=A , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , A ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , A ) def snake_case_( self ) -> List[Any]: _SCREAMING_SNAKE_CASE = self.get_feature_extractor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=A , feature_extractor=A ) _SCREAMING_SNAKE_CASE = floats_list((3, 1000) ) _SCREAMING_SNAKE_CASE = feature_extractor(A , return_tensors="""np""" ) _SCREAMING_SNAKE_CASE = processor(audios=A , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def snake_case_( self ) -> str: _SCREAMING_SNAKE_CASE = self.get_feature_extractor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=A , feature_extractor=A ) _SCREAMING_SNAKE_CASE = """This is a test string""" _SCREAMING_SNAKE_CASE = processor(text=A ) _SCREAMING_SNAKE_CASE = tokenizer(A ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def snake_case_( self ) -> Any: _SCREAMING_SNAKE_CASE = self.get_feature_extractor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=A , feature_extractor=A ) _SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _SCREAMING_SNAKE_CASE = processor.batch_decode(A ) _SCREAMING_SNAKE_CASE = tokenizer.batch_decode(A ) self.assertListEqual(A , A ) def snake_case_( self ) -> Tuple: _SCREAMING_SNAKE_CASE = self.get_feature_extractor() _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=A , feature_extractor=A ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="""`processor` and `feature_extractor` model input names do not match""" , )
58
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = """Usage of script: script_name <size_of_canvas:int>""" lowercase_ = [0] * 100 + [1] * 10 random.shuffle(choice) def lowerCamelCase ( __lowerCamelCase : int ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = [[False for i in range(__lowerCamelCase )] for j in range(__lowerCamelCase )] return canvas def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->None: for i, row in enumerate(__lowerCamelCase ): for j, _ in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = bool(random.getrandbits(1 ) ) def lowerCamelCase ( __lowerCamelCase : list[list[bool]] ) ->list[list[bool]]: _SCREAMING_SNAKE_CASE = np.array(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__lowerCamelCase ): for c, pt in enumerate(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = __judge_point( __lowerCamelCase , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) _SCREAMING_SNAKE_CASE = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. _SCREAMING_SNAKE_CASE = current_canvas.tolist() return return_canvas def lowerCamelCase ( __lowerCamelCase : bool , __lowerCamelCase : list[list[bool]] ) ->bool: _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. _SCREAMING_SNAKE_CASE = pt if pt: if alive < 2: _SCREAMING_SNAKE_CASE = False elif alive == 2 or alive == 3: _SCREAMING_SNAKE_CASE = True elif alive > 3: _SCREAMING_SNAKE_CASE = False else: if alive == 3: _SCREAMING_SNAKE_CASE = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ , lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(["""w""", """k"""]) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
58
1
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : list ) ->Union[str, Any]: _enforce_args(__lowerCamelCase , __lowerCamelCase ) if n == 0: return 0 _SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE = max( __lowerCamelCase , prices[i - 1] + naive_cut_rod_recursive(n - i , __lowerCamelCase ) ) return max_revue def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : list ) ->Optional[Any]: _enforce_args(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : list , __lowerCamelCase : list ) ->Tuple: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: _SCREAMING_SNAKE_CASE = float("""-inf""" ) for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE = max( __lowerCamelCase , prices[i - 1] + _top_down_cut_rod_recursive(n - i , __lowerCamelCase , __lowerCamelCase ) , ) _SCREAMING_SNAKE_CASE = max_revenue return max_rev[n] def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : list ) ->Union[str, Any]: _enforce_args(__lowerCamelCase , __lowerCamelCase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. _SCREAMING_SNAKE_CASE = [float("""-inf""" ) for _ in range(n + 1 )] _SCREAMING_SNAKE_CASE = 0 for i in range(1 , n + 1 ): _SCREAMING_SNAKE_CASE = max_rev[i] for j in range(1 , i + 1 ): _SCREAMING_SNAKE_CASE = max(__lowerCamelCase , prices[j - 1] + max_rev[i - j] ) _SCREAMING_SNAKE_CASE = max_revenue_i return max_rev[n] def lowerCamelCase ( __lowerCamelCase : int , __lowerCamelCase : list ) ->int: if n < 0: _SCREAMING_SNAKE_CASE = F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(__lowerCamelCase ) if n > len(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = ( """Each integral piece of rod must have a corresponding price. """ F'Got n = {n} but length of prices = {len(__lowerCamelCase )}' ) raise ValueError(__lowerCamelCase ) def lowerCamelCase ( ) ->Tuple: _SCREAMING_SNAKE_CASE = [6, 10, 12, 15, 20, 23] _SCREAMING_SNAKE_CASE = len(__lowerCamelCase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. _SCREAMING_SNAKE_CASE = 36 _SCREAMING_SNAKE_CASE = top_down_cut_rod(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = bottom_up_cut_rod(__lowerCamelCase , __lowerCamelCase ) _SCREAMING_SNAKE_CASE = naive_cut_rod_recursive(__lowerCamelCase , __lowerCamelCase ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
58
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home lowercase_ = HUGGINGFACE_HUB_CACHE lowercase_ = """config.json""" lowercase_ = """diffusion_pytorch_model.bin""" lowercase_ = """diffusion_flax_model.msgpack""" lowercase_ = """model.onnx""" lowercase_ = """diffusion_pytorch_model.safetensors""" lowercase_ = """weights.pb""" lowercase_ = """https://huggingface.co""" lowercase_ = default_cache_path lowercase_ = """diffusers_modules""" lowercase_ = os.getenv("""HF_MODULES_CACHE""", os.path.join(hf_cache_home, """modules""")) lowercase_ = ["""fp16""", """non-ema"""] lowercase_ = """.self_attn"""
58
1
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { """configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""], """processing_mgp_str""": ["""MgpstrProcessor"""], """tokenization_mgp_str""": ["""MgpstrTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""", """MgpstrModel""", """MgpstrPreTrainedModel""", """MgpstrForSceneTextRecognition""", ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
'''simple docstring''' from __future__ import annotations import math def lowerCamelCase ( __lowerCamelCase : int ) ->list[int]: if num <= 0: _SCREAMING_SNAKE_CASE = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = [True] * (num + 1) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = 2 _SCREAMING_SNAKE_CASE = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: _SCREAMING_SNAKE_CASE = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("""Enter a positive integer: """).strip())))
58
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = """▁""" lowercase_ = {"""vocab_file""": """sentencepiece.bpe.model"""} lowercase_ = { """vocab_file""": { """xlm-roberta-base""": """https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large""": """https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model""", """xlm-roberta-large-finetuned-conll02-dutch""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll02-spanish""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-english""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model""" ), """xlm-roberta-large-finetuned-conll03-german""": ( """https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model""" ), } } lowercase_ = { """xlm-roberta-base""": 512, """xlm-roberta-large""": 512, """xlm-roberta-large-finetuned-conll02-dutch""": 512, """xlm-roberta-large-finetuned-conll02-spanish""": 512, """xlm-roberta-large-finetuned-conll03-english""": 512, """xlm-roberta-large-finetuned-conll03-german""": 512, } class a_ ( snake_case_ ): '''simple docstring''' UpperCamelCase = VOCAB_FILES_NAMES UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase = ['''input_ids''', '''attention_mask'''] def __init__( self , A , A="<s>" , A="</s>" , A="</s>" , A="<s>" , A="<unk>" , A="<pad>" , A="<mask>" , A = None , **A , ) -> None: # Mask token behave like a normal word, i.e. include the space before it _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 , 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 ) + self.fairseq_offset _SCREAMING_SNAKE_CASE = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Optional[int]: _SCREAMING_SNAKE_CASE = self.__dict__.copy() _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() return state def __setstate__( self , A ) -> Optional[Any]: _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 ) def snake_case_( self , A , A = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _SCREAMING_SNAKE_CASE = [self.cls_token_id] _SCREAMING_SNAKE_CASE = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def snake_case_( self , A , A = None , A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=A , token_ids_a=A , already_has_special_tokens=A ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def snake_case_( self , A , A = None ) -> List[int]: _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] @property def snake_case_( self ) -> Tuple: return len(self.sp_model ) + self.fairseq_offset + 1 # Add the <mask> token def snake_case_( self ) -> Tuple: _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 , A ) -> List[str]: return self.sp_model.encode(A , out_type=A ) def snake_case_( self , A ) -> Optional[int]: 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 , A ) -> Dict: 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 , A ) -> List[Any]: _SCREAMING_SNAKE_CASE = """""".join(A ).replace(A , """ """ ).strip() return out_string def snake_case_( self , A , A = None ) -> Tuple[str]: 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,)
58
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {"""configuration_mbart""": ["""MBART_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MBartConfig""", """MBartOnnxConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ["""MBartTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """MBART_PRETRAINED_MODEL_ARCHIVE_LIST""", """MBartForCausalLM""", """MBartForConditionalGeneration""", """MBartForQuestionAnswering""", """MBartForSequenceClassification""", """MBartModel""", """MBartPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """TFMBartForConditionalGeneration""", """TFMBartModel""", """TFMBartPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ """FlaxMBartForConditionalGeneration""", """FlaxMBartForQuestionAnswering""", """FlaxMBartForSequenceClassification""", """FlaxMBartModel""", """FlaxMBartPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
58
1