
"""simple docstring"""




from typing import Optional, Tuple

import flax.linen as nn
import jax
import jax.numpy as jnp
from configuration_hybrid_clip import HybridCLIPConfig
from flax.core.frozen_dict import FrozenDict

from transformers import FLAX_MODEL_MAPPING, FlaxCLIPVisionModel
from transformers.modeling_flax_utils import FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPOutput
from transformers.utils import logging


a		:					List[Any]    	=					logging.get_logger(__name__)







class 						lowercase(nn.Module					):
     __snake_case:  Optional[Any]  				=    42
     __snake_case:  Dict  				=    jnp.floataa



     def  lowercase__     (       self      )		->    Tuple:







         """simple docstring"""



         a__    = self.config.text_config
         a__    = self.config.vision_config

         a__    = self.config.projection_dim
         a__    = text_config.hidden_size
         a__    = vision_config.hidden_size

         a__    = FLAX_MODEL_MAPPING[self.config.text_config.__class__].module_class
         a__    = FLAX_MODEL_MAPPING.get(self.config.vision_config.__class__    ,							lowercase_      ).module_class

         a__    = text_module(lowercase_    ,							dtype=self.dtype      )
         a__    = vision_module(lowercase_    ,							dtype=self.dtype      )

         a__    = nn.Dense(
             self.projection_dim    ,							dtype=self.dtype    ,							kernel_init=jax.nn.initializers.normal(0.02      )    ,							use_bias=lowercase_    ,							)
         a__    = nn.Dense(
             self.projection_dim    ,							dtype=self.dtype    ,							kernel_init=jax.nn.initializers.normal(0.02      )    ,							use_bias=lowercase_    ,							)
         a__    = self.param('logit_scale'    ,							jax.nn.initializers.ones    ,							[]      )




     def __call__(       self    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE = True    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							)		->    Optional[int]:







         """simple docstring"""



         a__    = return_dict if return_dict is not None else self.config.return_dict

         a__    = self.vision_model(
             pixel_values=lowercase_    ,							deterministic=lowercase_    ,							output_attentions=lowercase_    ,							output_hidden_states=lowercase_    ,							return_dict=lowercase_    ,							)

         a__    = self.text_model(
             input_ids=lowercase_    ,							attention_mask=lowercase_    ,							token_type_ids=lowercase_    ,							position_ids=lowercase_    ,							deterministic=lowercase_    ,							output_attentions=lowercase_    ,							output_hidden_states=lowercase_    ,							return_dict=lowercase_    ,							)

         a__    = vision_outputs[1]
         a__    = self.visual_projection(lowercase_      )

         a__    = text_outputs[1]
         a__    = self.text_projection(lowercase_      )

         # normalized features
         a__    = image_embeds / jnp.linalg.norm(lowercase_    ,							axis=-1    ,							keepdims=lowercase_      )
         a__    = text_embeds / jnp.linalg.norm(lowercase_    ,							axis=-1    ,							keepdims=lowercase_      )

         # cosine similarity as logits
         a__    = jnp.exp(self.logit_scale      )
         a__    = jnp.matmul(lowercase_    ,							image_embeds.T      ) * logit_scale
         a__    = logits_per_text.T

         if not return_dict:
             return (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)

         return FlaxCLIPOutput(
             logits_per_image=lowercase_    ,							logits_per_text=lowercase_    ,							text_embeds=lowercase_    ,							image_embeds=lowercase_    ,							text_model_output=lowercase_    ,							vision_model_output=lowercase_    ,							)







class 						lowercase(__UpperCAmelCase					):
     __snake_case:  Union[str, Any]  				=    HybridCLIPConfig
     __snake_case:  Any  				=    FlaxHybridCLIPModule



     def __init__(       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = 0    ,							__SCREAMING_SNAKE_CASE = jnp.floataa    ,							**__SCREAMING_SNAKE_CASE    ,							)		->    str:







         """simple docstring"""



         if input_shape is None:
             a__    = ((1, 1), (1, config.vision_config.image_size, config.vision_config.image_size, 3))

         a__    = self.module_class(config=lowercase_    ,							dtype=lowercase_    ,							**lowercase_      )
         super().__init__(lowercase_    ,							lowercase_    ,							input_shape=lowercase_    ,							seed=lowercase_    ,							dtype=lowercase_      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE = None      )		->    FrozenDict:







         """simple docstring"""



         a__    = jnp.zeros(input_shape[0]    ,							dtype='i4'      )
         a__    = jnp.broadcast_to(jnp.arange(jnp.atleast_ad(lowercase_      ).shape[-1]      )    ,							input_shape[0]      )
         a__    = jnp.ones_like(lowercase_      )
         a__    = jnp.ones_like(lowercase_      )

         a__    = jax.random.normal(lowercase_    ,							input_shape[1]      )

         a__    = jax.random.split(lowercase_      )
         a__    = {'''params''': params_rng, '''dropout''': dropout_rng}

         return self.module.init(lowercase_    ,							lowercase_    ,							lowercase_    ,							lowercase_    ,							lowercase_    ,							lowercase_      )["params"]



     def __call__(       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = False    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							)		->    Union[str, Any]:







         """simple docstring"""



         a__    = output_attentions if output_attentions is not None else self.config.output_attentions
         a__    = (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         a__    = return_dict if return_dict is not None else self.config.return_dict

         if position_ids is None:
             a__    = jnp.broadcast_to(jnp.arange(jnp.atleast_ad(lowercase_      ).shape[-1]      )    ,							input_ids.shape      )

         if token_type_ids is None:
             a__    = jnp.zeros_like(lowercase_      )

         if attention_mask is None:
             a__    = jnp.ones_like(lowercase_      )

         # Handle any PRNG if needed
         a__    = {}
         if dropout_rng is not None:
             a__    = dropout_rng

         return self.module.apply(
             {'params': params or self.params}    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype=jnp.floataa      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							not train    ,							lowercase_    ,							lowercase_    ,							lowercase_    ,							rngs=lowercase_    ,							)



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE=None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE=False    ,							)		->    Union[str, Any]:







         """simple docstring"""



         if position_ids is None:
             a__    = jnp.broadcast_to(jnp.arange(jnp.atleast_ad(lowercase_      ).shape[-1]      )    ,							input_ids.shape      )

         if token_type_ids is None:
             a__    = jnp.zeros_like(lowercase_      )

         if attention_mask is None:
             a__    = jnp.ones_like(lowercase_      )

         # Handle any PRNG if needed
         a__    = {}
         if dropout_rng is not None:
             a__    = dropout_rng

         def _get_features(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      ):
             a__    = module.text_model(
                 input_ids=lowercase_    ,							attention_mask=lowercase_    ,							position_ids=lowercase_    ,							token_type_ids=lowercase_    ,							deterministic=lowercase_    ,							)
             a__    = text_outputs[1]
             a__    = module.text_projection(lowercase_      )
             return text_features

         return self.module.apply(
             {'params': params or self.params}    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							jnp.array(lowercase_    ,							dtype='i4'      )    ,							not train    ,							method=_get_features    ,							rngs=lowercase_    ,							)



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE=False      )		->    List[Any]:







         """simple docstring"""



         a__    = {}
         if dropout_rng is not None:
             a__    = dropout_rng

         def _get_features(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      ):
             a__    = module.vision_model(pixel_values=lowercase_    ,							deterministic=lowercase_      )
             a__    = vision_outputs[1]  # pooled_output
             a__    = module.visual_projection(lowercase_      )
             return image_features

         return self.module.apply(
             {'params': params or self.params}    ,							jnp.array(lowercase_    ,							dtype=jnp.floataa      )    ,							not train    ,							method=_get_features    ,							rngs=lowercase_    ,							)




     @classmethod
     def  lowercase__     (       cls    ,							__SCREAMING_SNAKE_CASE = None    ,							__SCREAMING_SNAKE_CASE = None    ,							*__SCREAMING_SNAKE_CASE    ,							**__SCREAMING_SNAKE_CASE    ,							)		->    FlaxPreTrainedModel:







         """simple docstring"""



         a__    = {
             argument[len('text_'      ) :]: value for argument, value in kwargs.items() if argument.startswith('text_'      )
         }

         a__    = {
             argument[len('vision_'      ) :]: value for argument, value in kwargs.items() if argument.startswith('vision_'      )
         }

         # remove text, vision kwargs from kwargs
         for key in kwargs_text.keys():
             del kwargs["text_" + key]
         for key in kwargs_vision.keys():
             del kwargs["vision_" + key]

         # Load and initialize the text and vision model
         a__    = kwargs_text.pop('model'    ,							lowercase_      )
         if text_model is None:
             assert (
                 text_model_name_or_path is not None
             ), "If `model` is not defined as an argument, a `text_model_name_or_path` has to be defined"
             from transformers import FlaxAutoModel

             if "config" not in kwargs_text:
                 from transformers import AutoConfig

                 a__    = AutoConfig.from_pretrained(lowercase_      )
                 a__    = text_config

             a__    = FlaxAutoModel.from_pretrained(lowercase_    ,							*lowercase_    ,							**lowercase_      )

         a__    = kwargs_vision.pop('model'    ,							lowercase_      )
         if vision_model is None:
             assert (
                 vision_model_name_or_path is not None
             ), "If `model` is not defined as an argument, a `vision_model_name_or_path` has to be defined"
             from transformers import FlaxAutoModel

             if "config" not in kwargs_vision:
                 from transformers import AutoConfig

                 a__    = AutoConfig.from_pretrained(lowercase_      )
                 a__    = vision_config

             a__    = FlaxAutoModel.from_pretrained(lowercase_    ,							*lowercase_    ,							**lowercase_      )

         # instantiate config with corresponding kwargs
         a__    = kwargs.pop('dtype'    ,							jnp.floataa      )
         a__    = HybridCLIPConfig.from_text_vision_configs(text_model.config    ,							vision_model.config    ,							**lowercase_      )

         # init model
         a__    = cls(lowercase_    ,							*lowercase_    ,							dtype=lowercase_    ,							**lowercase_      )

         if vision_config.model_type == "clip":
             a__    = vision_model.params['''vision_model''']
             a__    = vision_model.params['''visual_projection''']['''kernel''']
         else:
             a__    = vision_model.params

         a__    = text_model.params

         return model




"""simple docstring"""




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


a		:					Tuple    	=					os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
a		:					Union[str, Any]    	=					os.path.join(hf_cache_home, 'accelerate')
a		:					Dict    	=					os.path.join(cache_dir, 'default_config.yaml')
a		:					List[str]    	=					os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
    a		:					Tuple    	=					default_yaml_config_file
else:
    a		:					Dict    	=					default_json_config_file



def 						__magic_name__		(				UpperCamelCase    :		Tuple    )    ->	Union[str, Any]:
    if config_file is not None:
        if not os.path.isfile(UpperCamelCase    ):
            raise FileNotFoundError(
                f'The passed configuration file `{config_file}` does not exist. '
                'Please pass an existing file to `accelerate launch`, or use the the default one '
                'created through `accelerate config` and run `accelerate launch` '
                'without the `--config_file` argument.'    )
    else:
        a__    = default_config_file
    with open(UpperCamelCase       ,		'r'       ,		encoding='utf-8'    ) as f:
        if config_file.endswith('.json'    ):
            if (
                json.load(UpperCamelCase    ).get('compute_environment'       ,		ComputeEnvironment.LOCAL_MACHINE    )
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                a__    = ClusterConfig
            else:
                a__    = SageMakerConfig
            return config_class.from_json_file(json_file=UpperCamelCase    )
        else:
            if (
                yaml.safe_load(UpperCamelCase    ).get('compute_environment'       ,		ComputeEnvironment.LOCAL_MACHINE    )
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                a__    = ClusterConfig
            else:
                a__    = SageMakerConfig
            return config_class.from_yaml_file(yaml_file=UpperCamelCase    )







@dataclass
class 						lowercase:
     __snake_case:  ComputeEnvironment
     __snake_case:  Union[DistributedType, SageMakerDistributedType]
     __snake_case:  str
     __snake_case:  bool



     def  lowercase__     (       self      )		->    int:







         """simple docstring"""



         a__    = self.__dict__
         # For serialization, it's best to convert Enums to strings (or their underlying value type).
         for key, value in result.items():
             if isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      ):
                 a__    = value.value
             if isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE      ) and not bool(__SCREAMING_SNAKE_CASE      ):
                 a__    = None
         a__    = {k: v for k, v in result.items() if v is not None}
         return result



     @classmethod
     def  lowercase__     (       cls    ,							__SCREAMING_SNAKE_CASE=None      )		->    Dict:







         """simple docstring"""



         a__    = default_json_config_file if json_file is None else json_file
         with open(__SCREAMING_SNAKE_CASE    ,							'r'    ,							encoding='utf-8'      ) as f:
             a__    = json.load(__SCREAMING_SNAKE_CASE      )
         if "compute_environment" not in config_dict:
             a__    = ComputeEnvironment.LOCAL_MACHINE
         if "mixed_precision" not in config_dict:
             a__    = 'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
         if "fp16" in config_dict:  # Convert the config to the new format.
             del config_dict["fp16"]
         if "dynamo_backend" in config_dict:  # Convert the config to the new format.
             a__    = config_dict.pop('dynamo_backend'      )
             a__    = {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
         if "use_cpu" not in config_dict:
             a__    = False
         return cls(**__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    int:







         """simple docstring"""



         with open(__SCREAMING_SNAKE_CASE    ,							'w'    ,							encoding='utf-8'      ) as f:
             a__    = json.dumps(self.to_dict()    ,							indent=2    ,							sort_keys=__SCREAMING_SNAKE_CASE      ) + '\n'
             f.write(__SCREAMING_SNAKE_CASE      )



     @classmethod
     def  lowercase__     (       cls    ,							__SCREAMING_SNAKE_CASE=None      )		->    Optional[Any]:







         """simple docstring"""



         a__    = default_yaml_config_file if yaml_file is None else yaml_file
         with open(__SCREAMING_SNAKE_CASE    ,							'r'    ,							encoding='utf-8'      ) as f:
             a__    = yaml.safe_load(__SCREAMING_SNAKE_CASE      )
         if "compute_environment" not in config_dict:
             a__    = ComputeEnvironment.LOCAL_MACHINE

         if "mixed_precision" not in config_dict:
             a__    = 'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
         if isinstance(config_dict['mixed_precision']    ,							__SCREAMING_SNAKE_CASE      ) and not config_dict["mixed_precision"]:
             a__    = 'no'
         if "fp16" in config_dict:  # Convert the config to the new format.
             del config_dict["fp16"]
         if "dynamo_backend" in config_dict:  # Convert the config to the new format.
             a__    = config_dict.pop('dynamo_backend'      )
             a__    = {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
         if "use_cpu" not in config_dict:
             a__    = False
         return cls(**__SCREAMING_SNAKE_CASE      )



     def  lowercase__     (       self    ,							__SCREAMING_SNAKE_CASE      )		->    List[Any]:







         """simple docstring"""



         with open(__SCREAMING_SNAKE_CASE    ,							'w'    ,							encoding='utf-8'      ) as f:
             yaml.safe_dump(self.to_dict()    ,							__SCREAMING_SNAKE_CASE      )




     def  lowercase__     (       self      )		->    Optional[int]:







         """simple docstring"""



         if isinstance(self.compute_environment    ,							__SCREAMING_SNAKE_CASE      ):
             a__    = ComputeEnvironment(self.compute_environment      )
         if isinstance(self.distributed_type    ,							__SCREAMING_SNAKE_CASE      ):
             if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                 a__    = SageMakerDistributedType(self.distributed_type      )
             else:
                 a__    = DistributedType(self.distributed_type      )
         if self.dynamo_config is None:
             a__    = {}







@dataclass
class 						lowercase(_lowercase					):
     __snake_case:  int
     __snake_case:  int  				=    0
     __snake_case:  int  				=    1
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[int]  				=    None
     __snake_case:  Optional[str]  				=    "static"
     __snake_case:  Optional[bool]  				=    False
     __snake_case:  str  				=    "main"

     # args for deepspeed_plugin
     __snake_case:  dict  				=    None
     # args for fsdp
     __snake_case:  dict  				=    None
     # args for megatron_lm
     __snake_case:  dict  				=    None
     # args for ipex
     __snake_case:  dict  				=    None
     # args for TPU
     __snake_case:  bool  				=    False

     # args for TPU pods
     __snake_case:  str  				=    None
     __snake_case:  str  				=    None
     __snake_case:  bool  				=    False
     __snake_case:  bool  				=    False
     __snake_case:  str  				=    None
     __snake_case:  List[str]  				=    None
     __snake_case:  List[str]  				=    None
     __snake_case:  List[str]  				=    None

     # args for dynamo
     __snake_case:  dict  				=    None



     def  lowercase__     (       self      )		->    List[str]:







         """simple docstring"""



         if self.deepspeed_config is None:
             a__    = {}
         if self.fsdp_config is None:
             a__    = {}
         if self.megatron_lm_config is None:
             a__    = {}
         if self.ipex_config is None:
             a__    = {}
         return super().__post_init__()







@dataclass
class 						lowercase(_lowercase					):
     __snake_case:  str
     __snake_case:  str
     __snake_case:  Optional[str]  				=    None
     __snake_case:  Optional[str]  				=    None
     __snake_case:  str  				=    "us-east-1"
     __snake_case:  int  				=    1
     __snake_case:  str  				=    "all"
     __snake_case:  str  				=    f"accelerate-sagemaker-{num_machines}"
     __snake_case:  str  				=    SAGEMAKER_PYTORCH_VERSION
     __snake_case:  str  				=    SAGEMAKER_TRANSFORMERS_VERSION
     __snake_case:  str  				=    SAGEMAKER_PYTHON_VERSION
     __snake_case:  str  				=    None
     __snake_case:  str  				=    None
     __snake_case:  dict  				=    None
     __snake_case:  dict  				=    None


