


"""simple docstring"""







import importlib
import inspect
import json
import os
import re
import shutil
import sys
from pathlib import Path
from typing import Dict, Optional, Union
from urllib import request

from huggingface_hub import HfFolder, cached_download, hf_hub_download, model_info
from packaging import version

from .. import __version__
from . import DIFFUSERS_DYNAMIC_MODULE_NAME, HF_MODULES_CACHE, logging


__lowercase    =				(
    'https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'
)


__lowercase    =				logging.get_logger(__name__)  # pylint: disable=invalid-name


def 					lowercase      (    )->				Tuple:
  '''simple docstring'''







  a						:		List[str]											=      "https://pypi.org/pypi/diffusers/json"
  a						:		Union[str, Any]											=      json.loads(request.urlopen(a__	).read()	)["releases"].keys()
  return sorted(a__  ,       key=lambda A_	: version.Version(a__	)	)


def 					lowercase      (    )->				List[Any]:
  '''simple docstring'''







  if HF_MODULES_CACHE in sys.path:
    return

  sys.path.append(a__	)
  os.makedirs(a__  ,       exist_ok=a__	)
  a						:		Any											=      Path(a__	) / "__init__.py"
  if not init_path.exists():
    init_path.touch()


def 					lowercase      (    A_	)->				Dict:
  '''simple docstring'''







  init_hf_modules()
  a						:		Union[str, Any]											=      Path(a__	) / name
  # If the parent module does not exist yet, recursively create it.
  if not dynamic_module_path.parent.exists():
    create_dynamic_module(dynamic_module_path.parent	)
  os.makedirs(a__  ,       exist_ok=a__	)
  a						:		Union[str, Any]											=      dynamic_module_path / "__init__.py"
  if not init_path.exists():
    init_path.touch()


def 					lowercase      (    A_	)->				Dict:
  '''simple docstring'''







  with open(a__  ,       "r"  ,       encoding="utf-8"	) as f:
    a						:		List[Any]											=      f.read()

  # Imports of the form `import .xxx`
  a						:		List[Any]											=      re.findall("^\s*import\s+\.(\S+)\s*$"  ,       a__  ,       flags=re.MULTILINE	)
  # Imports of the form `from .xxx import yyy`
  relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import"  ,       a__  ,       flags=re.MULTILINE	)
  # Unique-ify
  return list(set(a__	)	)


def 					lowercase      (    A_	)->				Any:
  '''simple docstring'''







  a						:		List[str]											=      False
  a						:		int											=      [module_file]
  a						:		Optional[Any]											=      []

  # Let's recurse through all relative imports
  while not no_change:
    a						:		str											=      []
    for f in files_to_check:
      new_imports.extend(get_relative_imports(a__	)	)

    a						:		Union[str, Any]											=      Path(a__	).parent
    a						:		int											=      [str(module_path / m	) for m in new_imports]
    a						:		Optional[Any]											=      [f for f in new_import_files if f not in all_relative_imports]
    a						:		Optional[int]											=      [F'''{f}.py''' for f in new_import_files]

    a						:		Union[str, Any]											=      len(a__	) == 0
    all_relative_imports.extend(a__	)

  return all_relative_imports


def 					lowercase      (    A_	)->				str:
  '''simple docstring'''







  with open(a__  ,       "r"  ,       encoding="utf-8"	) as f:
    a						:		Optional[int]											=      f.read()

  # Imports of the form `import xxx`
  a						:		str											=      re.findall("^\s*import\s+(\S+)\s*$"  ,       a__  ,       flags=re.MULTILINE	)
  # Imports of the form `from xxx import yyy`
  imports += re.findall("^\s*from\s+(\S+)\s+import"  ,       a__  ,       flags=re.MULTILINE	)
  # Only keep the top-level module
  a						:		str											=      [imp.split("."	)[0] for imp in imports if not imp.startswith("."	)]

  # Unique-ify and test we got them all
  a						:		Optional[Any]											=      list(set(a__	)	)
  a						:		List[str]											=      []
  for imp in imports:
    try:
      importlib.import_module(a__	)
    except ImportError:
      missing_packages.append(a__	)

  if len(a__	) > 0:
    raise ImportError(
        "This modeling file requires the following packages that were not found in your environment: "
        F'''{", ".join(a__	)}. Run `pip install {" ".join(a__	)}`'''	)

  return get_relative_imports(a__	)


def 					lowercase      (    A_  ,       A_	)->				Dict:
  '''simple docstring'''







  a						:		Optional[Any]											=      module_path.replace(os.path.sep  ,       "."	)
  a						:		int											=      importlib.import_module(a__	)

  if class_name is None:
    return find_pipeline_class(a__	)
  return getattr(a__  ,       a__	)


def 					lowercase      (    A_	)->				Optional[Any]:
  '''simple docstring'''







  from ..pipelines import DiffusionPipeline

  a						:		Dict											=      dict(inspect.getmembers(a__  ,       inspect.isclass	)	)

  a						:		Optional[Any]											=      None
  for cls_name, cls in cls_members.items():
    if (
        cls_name != DiffusionPipeline.__name__
        and issubclass(cls  ,       a__	)
        and cls.__module__.split("."	)[0] != "diffusers"
    ):
      if pipeline_class is not None:
        raise ValueError(
            F'''Multiple classes that inherit from {DiffusionPipeline.__name__} have been found:'''
            F''' {pipeline_class.__name__}, and {cls_name}. Please make sure to define only one in'''
            F''' {loaded_module}.'''	)
      a						:		List[Any]											=      cls

  return pipeline_class


def 					lowercase      (    A_  ,       A_  ,       A_ = None  ,       A_ = False  ,       A_ = False  ,       A_ = None  ,       A_ = None  ,       A_ = None  ,       A_ = False  ,       )->				Tuple:
  '''simple docstring'''







  a						:		Tuple											=      str(a__	)

  a						:		int											=      os.path.join(a__  ,       a__	)

  if os.path.isfile(a__	):
    a						:		Union[str, Any]											=      module_file_or_url
    a						:		Union[str, Any]											=      "local"
  elif pretrained_model_name_or_path.count("/"	) == 0:
    a						:		List[Any]											=      get_diffusers_versions()
    # cut ".dev0"
    a						:		Union[str, Any]											=      "v" + ".".join(__version__.split("."	)[:3]	)

    # retrieve github version that matches
    if revision is None:
      a						:		Dict											=      latest_version if latest_version[1:] in available_versions else "main"
      logger.info(F'''Defaulting to latest_version: {revision}.'''	)
    elif revision in available_versions:
      a						:		Any											=      F'''v{revision}'''
    elif revision == "main":
      a						:		List[Any]											=      revision
    else:
      raise ValueError(
          F'''`custom_revision`: {revision} does not exist. Please make sure to choose one of'''
          F''' {", ".join(available_versions + ["main"]	)}.'''	)

    # community pipeline on GitHub
    a						:		Union[str, Any]											=      COMMUNITY_PIPELINES_URL.format(revision=a__  ,       pipeline=a__	)
    try:
      a						:		str											=      cached_download(
          a__  ,       cache_dir=a__  ,       force_download=a__  ,       proxies=a__  ,       resume_download=a__  ,       local_files_only=a__  ,       use_auth_token=a__  ,       )
      a						:		Optional[int]											=      "git"
      a						:		List[Any]											=      pretrained_model_name_or_path + ".py"
    except EnvironmentError:
      logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.'''	)
      raise
  else:
    try:
      # Load from URL or cache if already cached
      a						:		int											=      hf_hub_download(
          a__  ,       a__  ,       cache_dir=a__  ,       force_download=a__  ,       proxies=a__  ,       resume_download=a__  ,       local_files_only=a__  ,       use_auth_token=a__  ,       )
      a						:		Optional[int]											=      os.path.join("local"  ,       "--".join(pretrained_model_name_or_path.split("/"	)	)	)
    except EnvironmentError:
      logger.error(F'''Could not locate the {module_file} inside {pretrained_model_name_or_path}.'''	)
      raise

    # Check we have all the requirements in our environment
  a						:		Any											=      check_imports(a__	)

  # Now we move the module inside our cached dynamic modules.
  a						:		str											=      DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
  create_dynamic_module(a__	)
  a						:		List[str]											=      Path(a__	) / full_submodule
  if submodule == "local" or submodule == "git":
    # We always copy local files (we could hash the file to see if there was a change, and give them the name of
    # that hash, to only copy when there is a modification but it seems overkill for now).
    # The only reason we do the copy is to avoid putting too many folders in sys.path.
    shutil.copy(a__  ,       submodule_path / module_file	)
    for module_needed in modules_needed:
      a						:		Any											=      F'''{module_needed}.py'''
      shutil.copy(os.path.join(a__  ,       a__	)  ,       submodule_path / module_needed	)
  else:
    # Get the commit hash
    # TODO: we will get this info in the etag soon, so retrieve it from there and not here.
    if isinstance(a__  ,       a__	):
      a						:		List[Any]											=      use_auth_token
    elif use_auth_token is True:
      a						:		Dict											=      HfFolder.get_token()
    else:
      a						:		Any											=      None

    a						:		Optional[Any]											=      model_info(a__  ,       revision=a__  ,       token=a__	).sha

    # The module file will end up being placed in a subfolder with the git hash of the repo. This way we get the
    # benefit of versioning.
    a						:		Union[str, Any]											=      submodule_path / commit_hash
    a						:		Dict											=      full_submodule + os.path.sep + commit_hash
    create_dynamic_module(a__	)

    if not (submodule_path / module_file).exists():
      shutil.copy(a__  ,       submodule_path / module_file	)
    # Make sure we also have every file with relative
    for module_needed in modules_needed:
      if not (submodule_path / module_needed).exists():
        get_cached_module_file(
            a__  ,       F'''{module_needed}.py'''  ,       cache_dir=a__  ,       force_download=a__  ,       resume_download=a__  ,       proxies=a__  ,       use_auth_token=a__  ,       revision=a__  ,       local_files_only=a__  ,       )
  return os.path.join(a__  ,       a__	)







def 					lowercase      (    A_  ,       A_  ,       A_ = None  ,       A_ = None  ,       A_ = False  ,       A_ = False  ,       A_ = None  ,       A_ = None  ,       A_ = None  ,       A_ = False  ,       **A_  ,       )->				Tuple:
  '''simple docstring'''







  a						:		Dict											=      get_cached_module_file(
      a__  ,       a__  ,       cache_dir=a__  ,       force_download=a__  ,       resume_download=a__  ,       proxies=a__  ,       use_auth_token=a__  ,       revision=a__  ,       local_files_only=a__  ,       )
  return get_class_in_module(a__  ,       final_module.replace(".py"  ,       ""	)	)










"""simple docstring"""







from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowercase    =				logging.get_logger(__name__)

__lowercase    =				{
    """EleutherAI/gpt-neox-20b""": """https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json""",
    # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox
}






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Union[str, Any]     =	"""gpt_neox"""






    def __init__( self    :   List[str]    ,			__UpperCAmelCase    :   Tuple=50432    ,			__UpperCAmelCase    :   str=6144    ,			__UpperCAmelCase    :   Any=44    ,			__UpperCAmelCase    :   Union[str, Any]=64    ,			__UpperCAmelCase    :   Dict=24576    ,			__UpperCAmelCase    :   Any="gelu"    ,			__UpperCAmelCase    :   List[Any]=0.25    ,			__UpperCAmelCase    :   Optional[Any]=10000    ,			__UpperCAmelCase    :   Tuple=0.0    ,			__UpperCAmelCase    :   Union[str, Any]=0.0    ,			__UpperCAmelCase    :   Optional[int]=0.1    ,			__UpperCAmelCase    :   List[Any]=2048    ,			__UpperCAmelCase    :   Optional[Any]=0.02    ,			__UpperCAmelCase    :   Optional[Any]=1e-5    ,			__UpperCAmelCase    :   Dict=True    ,			__UpperCAmelCase    :   Union[str, Any]=0    ,			__UpperCAmelCase    :   Union[str, Any]=2    ,			__UpperCAmelCase    :   Any=False    ,			__UpperCAmelCase    :   List[Any]=True    ,			__UpperCAmelCase    :   int=None    ,			**__UpperCAmelCase    :   Tuple    ,			):
      super().__init__(bos_token_id=__UpperCAmelCase    ,			eos_token_id=__UpperCAmelCase    ,			**__UpperCAmelCase)
      a						:		List[Any]											=      vocab_size
      a						:		Optional[int]											=      max_position_embeddings
      a						:		List[Any]											=      hidden_size
      a						:		Union[str, Any]											=      num_hidden_layers
      a						:		int											=      num_attention_heads
      a						:		Union[str, Any]											=      intermediate_size
      a						:		Optional[Any]											=      hidden_act
      a						:		Dict											=      rotary_pct
      a						:		Any											=      rotary_emb_base
      a						:		Dict											=      attention_dropout
      a						:		List[str]											=      hidden_dropout
      a						:		List[str]											=      classifier_dropout
      a						:		Any											=      initializer_range
      a						:		Union[str, Any]											=      layer_norm_eps
      a						:		int											=      use_cache
      a						:		int											=      tie_word_embeddings
      a						:		str											=      use_parallel_residual
      a						:		Union[str, Any]											=      rope_scaling
      self._rope_scaling_validation()

      if self.hidden_size % self.num_attention_heads != 0:
        raise ValueError(
            "The hidden size is not divisble by the number of attention heads! Make sure to update them!")






    def      __snake_case							( self    :   Any):
      if self.rope_scaling is None:
        return

      if not isinstance(self.rope_scaling    ,			__UpperCAmelCase) or len(self.rope_scaling) != 2:
        raise ValueError(
            "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
            f'''got {self.rope_scaling}''')
      a						:		str											=      self.rope_scaling.get("type"    ,			__UpperCAmelCase)
      a						:		List[str]											=      self.rope_scaling.get("factor"    ,			__UpperCAmelCase)
      if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
        raise ValueError(
            f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''')
      if rope_scaling_factor is None or not isinstance(__UpperCAmelCase    ,			__UpperCAmelCase) or rope_scaling_factor <= 1.0:
        raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''')






