'''simple docstring'''

# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


_A			:      Any					      =				float('''nan''')







class 				_lowercase     :


 '''simple docstring'''






 def __init__(      self   :	Optional[Any]      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]							)  ->    List[str]:
  __lowerCAmelCase											=						sys.stdout
  __lowerCAmelCase											=						open(SCREAMING_SNAKE_CASE__      ,       """a"""							)
 def __getattr__(      self   :	List[str]      ,       SCREAMING_SNAKE_CASE__   :	Optional[int]							)  ->    List[str]:
  return getattr(self.stdout      ,       SCREAMING_SNAKE_CASE__							)





 def a					(      self   :	str      ,       SCREAMING_SNAKE_CASE__   :	Any							)  ->    Optional[int]:
  self.stdout.write(SCREAMING_SNAKE_CASE__							)
  # strip tqdm codes
  self.file.write(re.sub(R"""^.*\r"""      ,       """"""      ,       SCREAMING_SNAKE_CASE__      ,       0      ,       re.M							)							)







def      UpperCamelCase_						(					snake_case_       :       str=80						,		snake_case_       :       Optional[Any]=False      )					->     Union[str, Any]:






 '''simple docstring'''

 __lowerCAmelCase											=						[]

 # deal with critical env vars
 __lowerCAmelCase											=						["""CUDA_VISIBLE_DEVICES"""]
 for key in env_keys:
  __lowerCAmelCase											=						os.environ.get(snake_case_						,		snake_case_      )
  if val is not None:
   cmd.append(f"""{key}={val}"""      )

    # python executable (not always needed if the script is executable)
 __lowerCAmelCase											=						sys.executable if full_python_path else sys.executable.split("""/"""      )[-1]
 cmd.append(snake_case_      )

 # now the normal args
 cmd += list(map(shlex.quote						,		sys.argv      )      )

 # split up into up to MAX_WIDTH lines with shell multi-line escapes
 __lowerCAmelCase											=						[]
 __lowerCAmelCase											=						""""""
 while len(snake_case_      ) > 0:
  current_line += f"""{cmd.pop(0      )} """
  if len(snake_case_      ) == 0 or len(snake_case_      ) + len(cmd[0]      ) + 1 > max_width - 1:
   lines.append(snake_case_      )
   __lowerCAmelCase											=						""""""
 return "\\\n".join(snake_case_      )







def      UpperCamelCase_						(					snake_case_       :       Any						,		snake_case_       :       Optional[int]      )					->     Tuple:






 '''simple docstring'''

 __lowerCAmelCase											=						re.sub(r"""[\\\n]+"""						,		""" """						,		args.base_cmd      )

 # remove --output_dir if any and set our own
 __lowerCAmelCase											=						re.sub("""--output_dir\s+[^\s]+"""						,		""""""						,		args.base_cmd      )
 args.base_cmd += f""" --output_dir {output_dir}"""

 # ensure we have --overwrite_output_dir
 __lowerCAmelCase											=						re.sub("""--overwrite_output_dir\s+"""						,		""""""						,		args.base_cmd      )
 args.base_cmd += " --overwrite_output_dir"

 return [sys.executable] + shlex.split(args.base_cmd      )







def      UpperCamelCase_						(					snake_case_       :       Optional[Any]						,		snake_case_       :       Tuple						,		snake_case_       :       Tuple						,		snake_case_       :       List[Any]						,		snake_case_       :       Optional[int]						,		snake_case_       :       List[Any]						,		snake_case_       :       Dict      )					->     int:






 '''simple docstring'''

 if 0:
  import random
  from time import sleep

  sleep(0      )
  return dict(
      {k: random.uniform(0						,		1_00      ) for k in metric_keys}						,		**{target_metric_key: random.choice([nan, 1_0.3_1, 1_0_0.2, 5_5.6_6_6_6, 2_2_2.2_2_2_2_2_2_2_2]      )}						,		)

 __lowerCAmelCase											=						subprocess.run(snake_case_						,		capture_output=snake_case_						,		text=snake_case_      )

 if verbose:
  print("""STDOUT"""						,		result.stdout      )
  print("""STDERR"""						,		result.stderr      )

 # save the streams
 __lowerCAmelCase											=						variation.replace(""" """						,		"""-"""      )
 with open(Path(snake_case_      ) / f"""log.{prefix}.stdout.txt"""						,		"""w"""      ) as f:
  f.write(result.stdout      )
 with open(Path(snake_case_      ) / f"""log.{prefix}.stderr.txt"""						,		"""w"""      ) as f:
  f.write(result.stderr      )

 if result.returncode != 0:
  if verbose:
   print("""failed"""      )
  return {target_metric_key: nan}

 with io.open(f"""{output_dir}/all_results.json"""						,		"""r"""						,		encoding="""utf-8"""      ) as f:
  __lowerCAmelCase											=						json.load(snake_case_      )

 # filter out just the keys we want
 return {k: v for k, v in metrics.items() if k in metric_keys}







def      UpperCamelCase_						(					snake_case_       :       Tuple						,		snake_case_       :       str						,		snake_case_       :       Tuple						,		snake_case_       :       str						,		snake_case_       :       List[Any]						,		snake_case_       :       Optional[int]						,		snake_case_       :       Any						,		snake_case_       :       Any						,		snake_case_       :       List[str]						,		snake_case_       :       List[Any]						,		)					->     List[str]:






 '''simple docstring'''

 __lowerCAmelCase											=						[]
 __lowerCAmelCase											=						[]
 __lowerCAmelCase											=						f"""{id}: {variation:<{longest_variation_len}}"""
 __lowerCAmelCase											=						f"""{preamble}: """
 __lowerCAmelCase											=						set(report_metric_keys + [target_metric_key]      )
 for i in tqdm(range(snake_case_      )						,		desc=snake_case_						,		leave=snake_case_      ):
  __lowerCAmelCase											=						process_run_single(
      snake_case_						,		snake_case_						,		snake_case_						,		snake_case_						,		snake_case_						,		snake_case_						,		snake_case_      )
  __lowerCAmelCase											=						single_run_metrics[target_metric_key]
  if not math.isnan(snake_case_      ):
   metrics.append(snake_case_      )
   results.append(snake_case_      )
   outcome += "✓"
  else:
   outcome += "✘"
 __lowerCAmelCase											=						f"""\33[2K\r{outcome}"""
 if len(snake_case_      ) > 0:
  __lowerCAmelCase											=						{k: fmean([x[k] for x in metrics]      ) for k in metrics[0].keys()}
  __lowerCAmelCase											=						round(mean_metrics[target_metric_key]						,		2      )
  __lowerCAmelCase											=						f"""{outcome} {mean_target}"""
  if len(snake_case_      ) > 1:
   results_str += f""" {tuple(round(snake_case_						,		2      ) for x in results      )}"""
  print(snake_case_      )
  __lowerCAmelCase											=						variation
  return mean_metrics
 else:
  print(snake_case_      )
  return {variation_key: variation, target_metric_key: nan}







def      UpperCamelCase_						(					)					->     Union[str, Any]:






 '''simple docstring'''

 __lowerCAmelCase											=						torch.cuda.get_device_properties(torch.device("""cuda"""      )      )
 return f"""
Datetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"      )}

Software:
transformers: {transformers.__version__}
torch       : {torch.__version__}
cuda        : {torch.version.cuda}
python      : {platform.python_version()}

Hardware:
{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB
"""







def      UpperCamelCase_						(					snake_case_       :       Optional[int]						,		snake_case_       :       List[Any]						,		snake_case_       :       Optional[Any]						,		snake_case_       :       List[str]						,		snake_case_       :       Dict      )					->     Dict:






 '''simple docstring'''

 __lowerCAmelCase											=						pd.DataFrame(snake_case_      )
 __lowerCAmelCase											=						"""variation"""
 __lowerCAmelCase											=						"""diff_%"""

 __lowerCAmelCase											=						nan
 if base_variation is not None and len(df[df[variation_key] == base_variation]      ):
  # this may still return nan
  __lowerCAmelCase											=						df.loc[df[variation_key] == base_variation][target_metric_key].item()
 if math.isnan(snake_case_      ):
  # as a fallback, use the minimal value as the sentinel
  __lowerCAmelCase											=						df.loc[df[target_metric_key] != nan][target_metric_key].min()

 # create diff column if possible
 if not math.isnan(snake_case_      ):
  __lowerCAmelCase											=						df.apply(
      lambda snake_case_      : round(1_00 * (r[target_metric_key] - sentinel_value) / sentinel_value      )
      if not math.isnan(r[target_metric_key]      )
      else 0						,		axis="""columns"""						,		)

 # re-order columns
 __lowerCAmelCase											=						[variation_key, target_metric_key, diff_key, *report_metric_keys]
 __lowerCAmelCase											=						df.reindex(snake_case_						,		axis="""columns"""      )  # reorder cols

 # capitalize
 __lowerCAmelCase											=						df.rename(str.capitalize						,		axis="""columns"""      )

 # make the cols as narrow as possible
 __lowerCAmelCase											=						df.rename(lambda snake_case_      : c.replace("""_"""						,		"""<br>"""      )						,		axis="""columns"""      )
 __lowerCAmelCase											=						df.rename(lambda snake_case_      : c.replace("""_"""						,		"""\n"""      )						,		axis="""columns"""      )

 __lowerCAmelCase											=						["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""]
 report += ["----------8<-----------------8<--------"]
 report += ["*** Results:", df_github.to_markdown(index=snake_case_						,		floatfmt=""".2f"""      )]
 report += ["```"]
 report += ["*** Setup:", get_versions()]
 report += ["*** The benchmark command line was:", get_original_command()]
 report += ["```"]
 report += ["----------8<-----------------8<--------"]
 report += ["*** Results (console):", df_console.to_markdown(index=snake_case_						,		floatfmt=""".2f"""      )]

 print("""\n\n""".join(snake_case_      )      )







def      UpperCamelCase_						(					)					->     Optional[int]:






 '''simple docstring'''

 __lowerCAmelCase											=						argparse.ArgumentParser()
 parser.add_argument(
     """--base-cmd"""						,		default=snake_case_						,		type=snake_case_						,		required=snake_case_						,		help="""Base cmd"""						,		)
 parser.add_argument(
     """--variations"""						,		default=snake_case_						,		type=snake_case_						,		nargs="""+"""						,		required=snake_case_						,		help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'"""						,		)
 parser.add_argument(
     """--base-variation"""						,		default=snake_case_						,		type=snake_case_						,		help="""Baseline variation to compare to. if None the minimal target value will be used to compare against"""						,		)
 parser.add_argument(
     """--target-metric-key"""						,		default=snake_case_						,		type=snake_case_						,		required=snake_case_						,		help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second"""						,		)
 parser.add_argument(
     """--report-metric-keys"""						,		default=""""""						,		type=snake_case_						,		help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples"""						,		)
 parser.add_argument(
     """--repeat-times"""						,		default=1						,		type=snake_case_						,		help="""How many times to re-run each variation - an average will be reported"""						,		)
 parser.add_argument(
     """--output_dir"""						,		default="""output_benchmark"""						,		type=snake_case_						,		help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked"""						,		)
 parser.add_argument(
     """--verbose"""						,		default=snake_case_						,		action="""store_true"""						,		help="""Whether to show the outputs of each run or just the benchmark progress"""						,		)
 __lowerCAmelCase											=						parser.parse_args()

 __lowerCAmelCase											=						args.output_dir
 Path(snake_case_      ).mkdir(exist_ok=snake_case_      )
 __lowerCAmelCase											=						get_base_command(snake_case_						,		snake_case_      )

 # split each dimension into its --foo variations
 __lowerCAmelCase											=						[list(map(str.strip						,		re.split(r"""\|"""						,		snake_case_      )      )      ) for x in args.variations]
 # build a cartesian product of dimensions and convert those back into cmd-line arg strings,
 # while stripping white space for inputs that were empty
 __lowerCAmelCase											=						list(map(str.strip						,		map(""" """.join						,		itertools.product(*snake_case_      )      )      )      )
 __lowerCAmelCase											=						max(len(snake_case_      ) for x in variations      )

 # split wanted keys
 __lowerCAmelCase											=						args.report_metric_keys.split()

 # capture prints into a log file for convenience
 __lowerCAmelCase											=						f"""benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"      )}.txt"""
 print(f"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt"""      )
 print(f"""and this script's output is also piped into {report_fn}"""      )

 __lowerCAmelCase											=						Tee(snake_case_      )

 print(f"""\n*** Running {len(snake_case_      )} benchmarks:"""      )
 print(f"""Base command: {" ".join(snake_case_      )}"""      )

 __lowerCAmelCase											=						"""variation"""
 __lowerCAmelCase											=						[]
 for id, variation in enumerate(tqdm(snake_case_						,		desc="""Total completion: """						,		leave=snake_case_      )      ):
  __lowerCAmelCase											=						base_cmd + variation.split()
  results.append(
      process_run(
          id + 1						,		snake_case_						,		snake_case_						,		snake_case_						,		snake_case_						,		args.target_metric_key						,		snake_case_						,		args.repeat_times						,		snake_case_						,		args.verbose						,		)      )

 process_results(snake_case_						,		args.target_metric_key						,		snake_case_						,		args.base_variation						,		snake_case_      )


if __name__ == "__main__":
 main()







'''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


_A			:      List[Any]					      =				(
    '''https://raw.githubusercontent.com/huggingface/diffusers/{revision}/examples/community/{pipeline}.py'''
)


_A			:      List[Any]					      =				logging.get_logger(__name__)  # pylint: disable=invalid-name







def      UpperCamelCase_						(					)					->     Dict:






 '''simple docstring'''

 __lowerCAmelCase											=						"""https://pypi.org/pypi/diffusers/json"""
 __lowerCAmelCase											=						json.loads(request.urlopen(snake_case_      ).read()      )["""releases"""].keys()
 return sorted(snake_case_						,		key=lambda snake_case_      : version.Version(snake_case_      )      )







def      UpperCamelCase_						(					)					->     int:






 '''simple docstring'''

 if HF_MODULES_CACHE in sys.path:
  return

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







def      UpperCamelCase_						(					snake_case_       :       Union[str, os.PathLike]      )					->     Dict:






 '''simple docstring'''

 init_hf_modules()
 __lowerCAmelCase											=						Path(snake_case_      ) / 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(snake_case_						,		exist_ok=snake_case_      )
 __lowerCAmelCase											=						dynamic_module_path / """__init__.py"""
 if not init_path.exists():
  init_path.touch()







def      UpperCamelCase_						(					snake_case_       :       int      )					->     str:






 '''simple docstring'''

 with open(snake_case_						,		"""r"""						,		encoding="""utf-8"""      ) as f:
  __lowerCAmelCase											=						f.read()

 # Imports of the form `import .xxx`
 __lowerCAmelCase											=						re.findall("""^\s*import\s+\.(\S+)\s*$"""						,		snake_case_						,		flags=re.MULTILINE      )
 # Imports of the form `from .xxx import yyy`
 relative_imports += re.findall("""^\s*from\s+\.(\S+)\s+import"""						,		snake_case_						,		flags=re.MULTILINE      )
 # Unique-ify
 return list(set(snake_case_      )      )







def      UpperCamelCase_						(					snake_case_       :       int      )					->     Dict:






 '''simple docstring'''

 __lowerCAmelCase											=						False
 __lowerCAmelCase											=						[module_file]
 __lowerCAmelCase											=						[]

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

  __lowerCAmelCase											=						Path(snake_case_      ).parent
  __lowerCAmelCase											=						[str(module_path / m      ) for m in new_imports]
  __lowerCAmelCase											=						[f for f in new_import_files if f not in all_relative_imports]
  __lowerCAmelCase											=						[f"""{f}.py""" for f in new_import_files]

  __lowerCAmelCase											=						len(snake_case_      ) == 0
  all_relative_imports.extend(snake_case_      )

 return all_relative_imports







def      UpperCamelCase_						(					snake_case_       :       List[Any]      )					->     Optional[Any]:






 '''simple docstring'''

 with open(snake_case_						,		"""r"""						,		encoding="""utf-8"""      ) as f:
  __lowerCAmelCase											=						f.read()

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

 # Unique-ify and test we got them all
 __lowerCAmelCase											=						list(set(snake_case_      )      )
 __lowerCAmelCase											=						[]
 for imp in imports:
  try:
   importlib.import_module(snake_case_      )
  except ImportError:
   missing_packages.append(snake_case_      )

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

 return get_relative_imports(snake_case_      )







def      UpperCamelCase_						(					snake_case_       :       Dict						,		snake_case_       :       Optional[int]      )					->     List[str]:






 '''simple docstring'''

 __lowerCAmelCase											=						module_path.replace(os.path.sep						,		"""."""      )
 __lowerCAmelCase											=						importlib.import_module(snake_case_      )

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







def      UpperCamelCase_						(					snake_case_       :       str      )					->     Optional[Any]:






 '''simple docstring'''

 from ..pipelines import DiffusionPipeline

 __lowerCAmelCase											=						dict(inspect.getmembers(snake_case_						,		inspect.isclass      )      )

 __lowerCAmelCase											=						None
 for cls_name, cls in cls_members.items():
  if (
      cls_name != DiffusionPipeline.__name__
      and issubclass(cls						,		snake_case_      )
      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}."""      )
   __lowerCAmelCase											=						cls

 return pipeline_class







def      UpperCamelCase_						(					snake_case_       :       Union[str, os.PathLike]						,		snake_case_       :       str						,		snake_case_       :       Optional[Union[str, os.PathLike]] = None						,		snake_case_       :       bool = False						,		snake_case_       :       bool = False						,		snake_case_       :       Optional[Dict[str, str]] = None						,		snake_case_       :       Optional[Union[bool, str]] = None						,		snake_case_       :       Optional[str] = None						,		snake_case_       :       bool = False						,		)					->     Any:






 '''simple docstring'''

 __lowerCAmelCase											=						str(snake_case_      )

 __lowerCAmelCase											=						os.path.join(snake_case_						,		snake_case_      )

 if os.path.isfile(snake_case_      ):
  __lowerCAmelCase											=						module_file_or_url
  __lowerCAmelCase											=						"""local"""
 elif pretrained_model_name_or_path.count("""/"""      ) == 0:
  __lowerCAmelCase											=						get_diffusers_versions()
  # cut ".dev0"
  __lowerCAmelCase											=						"""v""" + """.""".join(__version__.split("""."""      )[:3]      )

  # retrieve github version that matches
  if revision is None:
   __lowerCAmelCase											=						latest_version if latest_version[1:] in available_versions else """main"""
   logger.info(f"""Defaulting to latest_version: {revision}."""      )
  elif revision in available_versions:
   __lowerCAmelCase											=						f"""v{revision}"""
  elif revision == "main":
   __lowerCAmelCase											=						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
  __lowerCAmelCase											=						COMMUNITY_PIPELINES_URL.format(revision=snake_case_						,		pipeline=snake_case_      )
  try:
   __lowerCAmelCase											=						cached_download(
       snake_case_						,		cache_dir=snake_case_						,		force_download=snake_case_						,		proxies=snake_case_						,		resume_download=snake_case_						,		local_files_only=snake_case_						,		use_auth_token=snake_case_						,		)
   __lowerCAmelCase											=						"""git"""
   __lowerCAmelCase											=						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
   __lowerCAmelCase											=						hf_hub_download(
       snake_case_						,		snake_case_						,		cache_dir=snake_case_						,		force_download=snake_case_						,		proxies=snake_case_						,		resume_download=snake_case_						,		local_files_only=snake_case_						,		use_auth_token=snake_case_						,		)
   __lowerCAmelCase											=						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
 __lowerCAmelCase											=						check_imports(snake_case_      )

 # Now we move the module inside our cached dynamic modules.
 __lowerCAmelCase											=						DIFFUSERS_DYNAMIC_MODULE_NAME + os.path.sep + submodule
 create_dynamic_module(snake_case_      )
 __lowerCAmelCase											=						Path(snake_case_      ) / 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(snake_case_						,		submodule_path / module_file      )
  for module_needed in modules_needed:
   __lowerCAmelCase											=						f"""{module_needed}.py"""
   shutil.copy(os.path.join(snake_case_						,		snake_case_      )						,		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(snake_case_						,		snake_case_      ):
   __lowerCAmelCase											=						use_auth_token
  elif use_auth_token is True:
   __lowerCAmelCase											=						HfFolder.get_token()
  else:
   __lowerCAmelCase											=						None

  __lowerCAmelCase											=						model_info(snake_case_						,		revision=snake_case_						,		token=snake_case_      ).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.
  __lowerCAmelCase											=						submodule_path / commit_hash
  __lowerCAmelCase											=						full_submodule + os.path.sep + commit_hash
  create_dynamic_module(snake_case_      )

  if not (submodule_path / module_file).exists():
   shutil.copy(snake_case_						,		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(
        snake_case_						,		f"""{module_needed}.py"""						,		cache_dir=snake_case_						,		force_download=snake_case_						,		resume_download=snake_case_						,		proxies=snake_case_						,		use_auth_token=snake_case_						,		revision=snake_case_						,		local_files_only=snake_case_						,		)
 return os.path.join(snake_case_						,		snake_case_      )







def      UpperCamelCase_						(					snake_case_       :       Union[str, os.PathLike]						,		snake_case_       :       str						,		snake_case_       :       Optional[str] = None						,		snake_case_       :       Optional[Union[str, os.PathLike]] = None						,		snake_case_       :       bool = False						,		snake_case_       :       bool = False						,		snake_case_       :       Optional[Dict[str, str]] = None						,		snake_case_       :       Optional[Union[bool, str]] = None						,		snake_case_       :       Optional[str] = None						,		snake_case_       :       bool = False						,		**snake_case_       :       Dict						,		)					->     Tuple:






 '''simple docstring'''

 __lowerCAmelCase											=						get_cached_module_file(
     snake_case_						,		snake_case_						,		cache_dir=snake_case_						,		force_download=snake_case_						,		resume_download=snake_case_						,		proxies=snake_case_						,		use_auth_token=snake_case_						,		revision=snake_case_						,		local_files_only=snake_case_						,		)
 return get_class_in_module(snake_case_						,		final_module.replace(""".py"""						,		""""""      )      )






