



"""simple docstring"""






import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()

class 			__SCREAMING_SNAKE_CASE      ( unittest.TestCase  ):


					'''simple docstring'''





					_a       =				'hf-internal-testing/tiny-stable-diffusion-pipe'
					_a       =				1
					_a       =				7_7
					_a       =				3_2
					_a       =				4
					_a       =				_a       =				6_4
					_a       =				torch.manual_seed(0  )



					def 						snake_case			(			self				:    Optional[Any],    lowerCamelCase				:    List[str]=0.9_999	)->   Union[str, Any]:
								lowerCamelCase__						:						str						      =UNetaDConditionModel.from_pretrained(self.model_id,    subfolder='''unet'''	)
								lowerCamelCase__						:						Optional[int]						      =unet.to(lowerCamelCase	)
								lowerCamelCase__						:						Optional[Any]						      =EMAModel(unet.parameters(),    decay=lowerCamelCase,    model_cls=lowerCamelCase,    model_config=unet.config	)
								return unet, ema_unet



					def 						snake_case			(			self				:    Any	)->   Dict:
								lowerCamelCase__						:						List[Any]						      =torch.randn(
								    self.batch_size,    self.num_in_channels,    self.latent_height,    self.latent_width,    generator=self.generator	).to(lowerCamelCase	)
								lowerCamelCase__						:						str						      =torch.randint(0,    1000,    size=(self.batch_size,),    generator=self.generator	).to(lowerCamelCase	)
								lowerCamelCase__						:						Any						      =torch.randn(
								    self.batch_size,    self.prompt_length,    self.text_encoder_hidden_dim,    generator=self.generator	).to(lowerCamelCase	)
								return noisy_latents, timesteps, encoder_hidden_states



					def 						snake_case			(			self				:    Optional[int],    lowerCamelCase				:    Optional[int]	)->   int:
								lowerCamelCase__						:						Optional[int]						      ={}
								for k, param in unet.state_dict().items():
											lowerCamelCase__						:						List[Any]						      =torch.randn_like(lowerCamelCase	) + (param * torch.randn_like(lowerCamelCase	))
											updated_state_dict.update({k: updated_param}	)
								unet.load_state_dict(lowerCamelCase	)
								return unet



					def 						snake_case			(			self				:    int	)->   int:
								lowerCamelCase__      ,  lowerCamelCase__						:						List[str]						      =self.get_models()
								# Take the first (hypothetical) EMA step.
								ema_unet.step(unet.parameters()	)
								assert ema_unet.optimization_step == 1

								# Take two more.
								for _ in range(2	):
											ema_unet.step(unet.parameters()	)
								assert ema_unet.optimization_step == 3



					def 						snake_case			(			self				:    str	)->   Union[str, Any]:
								lowerCamelCase__      ,  lowerCamelCase__						:						str						      =self.get_models()
								# Since the `unet` is not being updated (i.e., backprop'd)
								# there won't be any difference between the `params` of `unet`
								# and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
								ema_unet.step(unet.parameters()	)
								lowerCamelCase__						:						str						      =list(unet.parameters()	)
								for s_param, param in zip(ema_unet.shadow_params,    lowerCamelCase	):
											assert torch.allclose(lowerCamelCase,    lowerCamelCase	)

								# The above holds true even if we call `ema.step()` multiple times since
								# `unet` params are still not being updated.
								for _ in range(4	):
											ema_unet.step(unet.parameters()	)
								for s_param, param in zip(ema_unet.shadow_params,    lowerCamelCase	):
											assert torch.allclose(lowerCamelCase,    lowerCamelCase	)



					def 						snake_case			(			self				:    List[str]	)->   str:
								lowerCamelCase__      ,  lowerCamelCase__						:						Tuple						      =self.get_models()
								# Here we simulate the parameter updates for `unet`. Since there might
								# be some parameters which are initialized to zero we take extra care to
								# initialize their values to something non-zero before the multiplication.
								lowerCamelCase__						:						Dict						      =self.simulate_backprop(lowerCamelCase	)

								# Take the EMA step.
								ema_unet.step(unet_pseudo_updated_step_one.parameters()	)

								# Now the EMA'd parameters won't be equal to the original model parameters.
								lowerCamelCase__						:						Union[str, Any]						      =list(unet_pseudo_updated_step_one.parameters()	)
								for s_param, param in zip(ema_unet.shadow_params,    lowerCamelCase	):
											assert ~torch.allclose(lowerCamelCase,    lowerCamelCase	)

								# Ensure this is the case when we take multiple EMA steps.
								for _ in range(4	):
											ema_unet.step(unet.parameters()	)
								for s_param, param in zip(ema_unet.shadow_params,    lowerCamelCase	):
											assert ~torch.allclose(lowerCamelCase,    lowerCamelCase	)



					def 						snake_case			(			self				:    List[str]	)->   Tuple:
								# If we call EMA step after a backpropagation consecutively for two times,
								# the shadow params from those two steps should be different.
								lowerCamelCase__      ,  lowerCamelCase__						:						Optional[Any]						      =self.get_models()

								# First backprop + EMA
								lowerCamelCase__						:						Optional[int]						      =self.simulate_backprop(lowerCamelCase	)
								ema_unet.step(unet_step_one.parameters()	)
								lowerCamelCase__						:						Any						      =ema_unet.shadow_params

								# Second backprop + EMA
								lowerCamelCase__						:						int						      =self.simulate_backprop(lowerCamelCase	)
								ema_unet.step(unet_step_two.parameters()	)
								lowerCamelCase__						:						Dict						      =ema_unet.shadow_params

								for step_one, step_two in zip(lowerCamelCase,    lowerCamelCase	):
											assert ~torch.allclose(lowerCamelCase,    lowerCamelCase	)



					def 						snake_case			(			self				:    Any	)->   int:
								# If there's no decay even if there are backprops, EMA steps
								# won't take any effect i.e., the shadow params would remain the
								# same.
								lowerCamelCase__      ,  lowerCamelCase__						:						Optional[int]						      =self.get_models(decay=0.0	)
								lowerCamelCase__						:						Union[str, Any]						      =self.simulate_backprop(lowerCamelCase	)
								ema_unet.step(unet_step_one.parameters()	)
								lowerCamelCase__						:						Union[str, Any]						      =ema_unet.shadow_params

								lowerCamelCase__						:						List[Any]						      =self.simulate_backprop(lowerCamelCase	)
								ema_unet.step(unet_step_two.parameters()	)
								lowerCamelCase__						:						List[str]						      =ema_unet.shadow_params

								for step_one, step_two in zip(lowerCamelCase,    lowerCamelCase	):
											assert torch.allclose(lowerCamelCase,    lowerCamelCase	)




					@skip_mps
					def 						snake_case			(			self				:    Tuple	)->   int:
								lowerCamelCase__      ,  lowerCamelCase__						:						Union[str, Any]						      =self.get_models()
								lowerCamelCase__      ,  lowerCamelCase__      ,  lowerCamelCase__						:						Any						      =self.get_dummy_inputs()

								with tempfile.TemporaryDirectory() as tmpdir:
											ema_unet.save_pretrained(lowerCamelCase	)
											lowerCamelCase__						:						Tuple						      =UNetaDConditionModel.from_pretrained(lowerCamelCase,    model_cls=lowerCamelCase	)
											lowerCamelCase__						:						Dict						      =loaded_unet.to(unet.device	)

								# Since no EMA step has been performed the outputs should match.
								lowerCamelCase__						:						Tuple						      =unet(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	).sample
								lowerCamelCase__						:						int						      =loaded_unet(lowerCamelCase,    lowerCamelCase,    lowerCamelCase	).sample

								assert torch.allclose(lowerCamelCase,    lowerCamelCase,    atol=1E-4	)












'''simple docstring'''







import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile
from typing import List

from datasets import config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.info_utils import VerificationMode


def     _UpperCamelCase				(  snake_case__				,      **snake_case__				):
      return RunBeamCommand(
          args.dataset				,      args.name				,      args.cache_dir				,      args.beam_pipeline_options				,      args.data_dir				,      args.all_configs				,      args.save_info or args.save_infos				,      args.ignore_verifications				,      args.force_redownload				,      **snake_case__				,      )






class        a__     (      lowerCamelCase    ):
     '''simple docstring'''







     @staticmethod
     def      _UpperCamelCase (lowercase__     :						ArgumentParser       )	->							List[Any]:
           __A		 =   parser.add_parser("run_beam"					,					help="Run a Beam dataset processing pipeline"       )
           run_beam_parser.add_argument("dataset"					,					type=lowercase__					,					help="Name of the dataset to download"       )
           run_beam_parser.add_argument("--name"					,					type=lowercase__					,					default=lowercase__					,					help="Dataset config name"       )
           run_beam_parser.add_argument(
               "--cache_dir"					,					type=lowercase__					,					default=lowercase__					,					help="Cache directory where the datasets are stored"					,					)
           run_beam_parser.add_argument(
               "--beam_pipeline_options"					,					type=lowercase__					,					default=""					,					help="Beam pipeline options, separated by commas. Example:: `--beam_pipeline_options=job_name=my-job,project=my-project`"					,					)
           run_beam_parser.add_argument(
               "--data_dir"					,					type=lowercase__					,					default=lowercase__					,					help="Can be used to specify a manual directory to get the files from"					,					)
           run_beam_parser.add_argument("--all_configs"					,					action="store_true"					,					help="Test all dataset configurations"       )
           run_beam_parser.add_argument("--save_info"					,					action="store_true"					,					help="Save the dataset infos file"       )
           run_beam_parser.add_argument(
               "--ignore_verifications"					,					action="store_true"					,					help="Run the test without checksums and splits checks"       )
           run_beam_parser.add_argument("--force_redownload"					,					action="store_true"					,					help="Force dataset redownload"       )
           # aliases
           run_beam_parser.add_argument("--save_infos"					,					action="store_true"					,					help="alias for save_info"       )
           run_beam_parser.set_defaults(func=lowercase__       )






     def __init__(self     :						Any					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						str					,					lowercase__     :						bool					,					lowercase__     :						bool					,					lowercase__     :						bool					,					lowercase__     :						bool					,					**lowercase__     :						Tuple					,					)	->							List[Any]:
           __A		 =   dataset
           __A		 =   name
           __A		 =   cache_dir
           __A		 =   beam_pipeline_options
           __A		 =   data_dir
           __A		 =   all_configs
           __A		 =   save_infos
           __A		 =   ignore_verifications
           __A		 =   force_redownload
           __A		 =   config_kwargs






     def      _UpperCamelCase (self     :						int       )	->							Dict:
           import apache_beam as beam

           if self._name is not None and self._all_configs:
                 print("Both parameters `name` and `all_configs` can't be used at once."       )
                 exit(1       )
           __A ,					__A		 =   self._dataset, self._name
           __A		 =   dataset_module_factory(lowercase__       )
           __A		 =   import_main_class(dataset_module.module_path       )
           __A		 =   []
           if self._beam_pipeline_options:
                 __A		 =   beam.options.pipeline_options.PipelineOptions(
                     flags=[f"--{opt.strip()}" for opt in self._beam_pipeline_options.split(","       ) if opt]       )
           else:
                 __A		 =   None
           if self._all_configs and len(builder_cls.BUILDER_CONFIGS       ) > 0:
                 for builder_config in builder_cls.BUILDER_CONFIGS:
                       builders.append(
                           builder_cls(
                               config_name=builder_config.name					,					data_dir=self._data_dir					,					hash=dataset_module.hash					,					beam_options=lowercase__					,					cache_dir=self._cache_dir					,					base_path=dataset_module.builder_kwargs.get("base_path"       )					,					)       )
           else:
                 builders.append(
                     builder_cls(
                         config_name=lowercase__					,					data_dir=self._data_dir					,					beam_options=lowercase__					,					cache_dir=self._cache_dir					,					base_path=dataset_module.builder_kwargs.get("base_path"       )					,					**self._config_kwargs					,					)       )

           for builder in builders:
                 builder.download_and_prepare(
                     download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
                     if not self._force_redownload
                     else DownloadMode.FORCE_REDOWNLOAD					,					download_config=DownloadConfig(cache_dir=config.DOWNLOADED_DATASETS_PATH       )					,					verification_mode=VerificationMode.NO_CHECKS
                     if self._ignore_verifications
                     else VerificationMode.ALL_CHECKS					,					try_from_hf_gcs=lowercase__					,					)
                 if self._save_infos:
                       builder._save_infos()

           print("Apache beam run successful."       )

           # If save_infos=True, the dataset infos file is created next to the loaded module file.
           # Let's move it to the original directory of the dataset script, to allow the user to
           # upload them on S3 at the same time afterwards.
           if self._save_infos:
                 __A		 =   os.path.join(builder_cls.get_imported_module_dir()					,					config.DATASETDICT_INFOS_FILENAME       )

                 __A		 =   Path(lowercase__       ).name + ".py"

                 __A		 =   os.path.join(lowercase__					,					lowercase__       )
                 if os.path.isfile(lowercase__       ):
                       __A		 =   os.path.dirname(lowercase__       )
                 elif os.path.isfile(lowercase__       ):
                       __A		 =   path
                 else:  # in case of a remote dataset
                       print(f"Dataset Infos file saved at {dataset_infos_path}"       )
                       exit(1       )

                 # Move datasetinfo back to the user
                 __A		 =   os.path.join(lowercase__					,					config.DATASETDICT_INFOS_FILENAME       )
                 copyfile(lowercase__					,					lowercase__       )
                 print(f"Dataset Infos file saved at {user_dataset_infos_path}"       )


