


# 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 warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType







class 		_snake_case  (				_snake_case							):




 def __init__(		self ,  _lowerCamelCase   ):
       a						:Optional[int]										=	data




 def __iter__(		self   ):
       for element in self.data:
             yield element







def     __lowerCamelCase						(			UpperCAmelCase_						:		Union[str, Any]=True						):




      """simple docstring"""





      a						:List[str]										=	Accelerator(even_batches=UpperCAmelCase_						)
      assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
      return accelerator
def     __lowerCamelCase						(			UpperCAmelCase_						:		Accelerator			,  UpperCAmelCase_						:		int			,  UpperCAmelCase_						:		int			,  UpperCAmelCase_						:		bool = False						):




      """simple docstring"""





      if iterable:
            a						:Tuple										=	DummyIterableDataset(torch.as_tensor(range(UpperCAmelCase_						)						)						)
      else:
            a						:int										=	TensorDataset(torch.as_tensor(range(UpperCAmelCase_						)						)						)

      a						:Optional[Any]										=	DataLoader(UpperCAmelCase_			,  batch_size=UpperCAmelCase_						)
      a						:str										=	accelerator.prepare(UpperCAmelCase_						)

      return dl
def     __lowerCamelCase						(			UpperCAmelCase_						:		Accelerator			,  UpperCAmelCase_						:		int			,  UpperCAmelCase_						:		int			,  UpperCAmelCase_						:		List[int]			,  UpperCAmelCase_						:		List[int]			,  ):




      """simple docstring"""





      a						:Any										=	create_dataloader(accelerator=UpperCAmelCase_			,  dataset_size=UpperCAmelCase_			,  batch_size=UpperCAmelCase_						)

      a						:Optional[int]										=	[len(batch[0]						) for batch in dl]

      if accelerator.process_index == 0:
            assert batch_sizes == process_0_expected_batch_sizes
      elif accelerator.process_index == 1:
            assert batch_sizes == process_1_expected_batch_sizes
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:Dict										=	create_accelerator()

      # without padding, we would expect a different number of batches
      verify_dataloader_batch_sizes(
          UpperCAmelCase_			,  dataset_size=3			,  batch_size=1			,  process_0_expected_batch_sizes=[1, 1]			,  process_1_expected_batch_sizes=[1, 1]			,  )

      # without padding, we would expect the same number of batches, but different sizes
      verify_dataloader_batch_sizes(
          UpperCAmelCase_			,  dataset_size=7			,  batch_size=2			,  process_0_expected_batch_sizes=[2, 2]			,  process_1_expected_batch_sizes=[2, 2]			,  )
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:Optional[int]										=	create_accelerator(even_batches=UpperCAmelCase_						)

      verify_dataloader_batch_sizes(
          UpperCAmelCase_			,  dataset_size=3			,  batch_size=1			,  process_0_expected_batch_sizes=[1, 1]			,  process_1_expected_batch_sizes=[1]			,  )

      verify_dataloader_batch_sizes(
          UpperCAmelCase_			,  dataset_size=7			,  batch_size=2			,  process_0_expected_batch_sizes=[2, 2]			,  process_1_expected_batch_sizes=[2, 1]			,  )
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:Optional[int]										=	create_accelerator(even_batches=UpperCAmelCase_						)

      a						:Any										=	torch.nn.Linear(1			,  1						)
      a						:int										=	accelerator.prepare(UpperCAmelCase_						)

      a						:int										=	create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1						)

      a						:Optional[Any]										=	[]
      with accelerator.join_uneven_inputs([ddp_model]						):
            for batch_idx, batch in enumerate(UpperCAmelCase_						):
                  a						:Optional[int]										=	ddp_model(batch[0].float()						)
                  a						:List[Any]										=	output.sum()
                  loss.backward()
                  batch_idxs.append(UpperCAmelCase_						)

      accelerator.wait_for_everyone()

      if accelerator.process_index == 0:
            assert batch_idxs == [0, 1]
      elif accelerator.process_index == 1:
            assert batch_idxs == [0]
def     __lowerCamelCase						(			UpperCAmelCase_						:		Dict						):




      """simple docstring"""





      with warnings.catch_warnings(record=UpperCAmelCase_						) as w:
            with accelerator.join_uneven_inputs([Mock()]						):
                  pass

            assert issubclass(w[-1].category			,  UpperCAmelCase_						)
            assert "only supported for multi-GPU" in str(w[-1].message						)
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:List[str]										=	True
      a						:int										=	False
      a						:Union[str, Any]										=	create_accelerator(even_batches=UpperCAmelCase_						)
      a						:int										=	torch.nn.Linear(1			,  1						)
      a						:Union[str, Any]										=	accelerator.prepare(UpperCAmelCase_						)
      a						:int										=	create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1						)
      a						:Optional[int]										=	create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1						)

      with accelerator.join_uneven_inputs([ddp_model]			,  even_batches=UpperCAmelCase_						):
            a						:List[str]										=	train_dl.batch_sampler.even_batches
            a						:Optional[int]										=	valid_dl.batch_sampler.even_batches

      assert train_dl_overridden_value == overridden_even_batches
      assert valid_dl_overridden_value == overridden_even_batches
      assert train_dl.batch_sampler.even_batches == default_even_batches
      assert valid_dl.batch_sampler.even_batches == default_even_batches
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:List[Any]										=	True
      a						:Dict										=	False
      a						:Optional[int]										=	create_accelerator(even_batches=UpperCAmelCase_						)
      a						:Any										=	torch.nn.Linear(1			,  1						)
      a						:str										=	accelerator.prepare(UpperCAmelCase_						)
      create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1			,  iterable=UpperCAmelCase_						)
      a						:Optional[int]										=	create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1						)

      with warnings.catch_warnings():
            warnings.filterwarnings('''ignore'''						)
            try:
                  with accelerator.join_uneven_inputs([ddp_model]			,  even_batches=UpperCAmelCase_						):
                        a						:List[Any]										=	batch_dl.batch_sampler.even_batches
            except AttributeError:
                  # ensure attribute error is not raised when processing iterable dl
                  raise AssertionError

      assert batch_dl_overridden_value == overridden_even_batches
      assert batch_dl.batch_sampler.even_batches == default_even_batches
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:List[str]										=	create_accelerator()
      a						:List[str]										=	torch.nn.Linear(1			,  1						)
      a						:Optional[Any]										=	accelerator.prepare(UpperCAmelCase_						)
      create_dataloader(UpperCAmelCase_			,  dataset_size=3			,  batch_size=1			,  iterable=UpperCAmelCase_						)

      with warnings.catch_warnings(record=UpperCAmelCase_						) as w:
            with accelerator.join_uneven_inputs([ddp_model]			,  even_batches=UpperCAmelCase_						):
                  pass

            assert issubclass(w[-1].category			,  UpperCAmelCase_						)
            assert "only supported for map-style datasets" in str(w[-1].message						)
def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:List[str]										=	create_accelerator()

      accelerator.print('''Test that even_batches variable ensures uniform batches across processes'''						)
      test_default_ensures_even_batch_sizes()

      accelerator.print('''Run tests with even_batches disabled'''						)
      test_can_disable_even_batches()

      accelerator.print('''Test joining uneven inputs'''						)
      test_can_join_uneven_inputs()

      accelerator.print('''Test overriding even_batches when joining uneven inputs'''						)
      test_join_can_override_even_batches()

      accelerator.print('''Test overriding even_batches for mixed dataloader types'''						)
      test_join_can_override_for_mixed_type_dataloaders()

      accelerator.print('''Test overriding even_batches raises a warning for iterable dataloaders'''						)
      test_join_raises_warning_for_iterable_when_overriding_even_batches()

      accelerator.print('''Test join with non DDP distributed raises warning'''						)
      a						:str										=	accelerator.state.distributed_type
      a						:Tuple										=	DistributedType.FSDP
      test_join_raises_warning_for_non_ddp_distributed(UpperCAmelCase_						)
      a						:Optional[int]										=	original_state


if __name__ == "__main__":
       main()









import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin







@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP
class 		_snake_case  (				_snake_case							):
 SCREAMING_SNAKE_CASE__				=	42
 SCREAMING_SNAKE_CASE__				=	None







def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[Any]			,  UpperCAmelCase_						:		List[str]=0.999			,  UpperCAmelCase_						:		str="cosine"			,  ):




      """simple docstring"""





      if alpha_transform_type == "cosine":

            def alpha_bar_fn(UpperCAmelCase_						:		List[str]						):
                  return math.cos((t + 0.008) / 1.008 * math.pi / 2						) ** 2

      elif alpha_transform_type == "exp":

            def alpha_bar_fn(UpperCAmelCase_						:		List[Any]						):
                  return math.exp(t * -12.0						)

      else:
            raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}'''						)

      a						:Union[str, Any]										=	[]
      for i in range(UpperCAmelCase_						):
            a						:Optional[Any]										=	i / num_diffusion_timesteps
            a						:int										=	(i + 1) / num_diffusion_timesteps
            betas.append(min(1 - alpha_bar_fn(UpperCAmelCase_						) / alpha_bar_fn(UpperCAmelCase_						)			,  UpperCAmelCase_						)						)
      return torch.tensor(UpperCAmelCase_			,  dtype=torch.floataa						)







class 		_snake_case  (				_snake_case						,   _snake_case							):




 @register_to_config
 def __init__(		self ,  _lowerCamelCase = 1000 ,  _lowerCamelCase = "fixed_small_log" ,  _lowerCamelCase = True ,  _lowerCamelCase = 1.0 ,  _lowerCamelCase = "epsilon" ,  _lowerCamelCase = "squaredcos_cap_v2" ,  ):
       if beta_schedule != "squaredcos_cap_v2":
             raise ValueError('''UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\''''   )

       a						:List[Any]										=	betas_for_alpha_bar(_lowerCamelCase   )

       a						:Any										=	1.0 - self.betas
       a						:int										=	torch.cumprod(self.alphas ,  dim=0   )
       a						:Union[str, Any]										=	torch.tensor(1.0   )

       # standard deviation of the initial noise distribution
       a						:List[Any]										=	1.0

       # setable values
       a						:Optional[Any]										=	None
       a						:List[str]										=	torch.from_numpy(np.arange(0 ,  _lowerCamelCase   )[::-1].copy()   )

       a						:List[str]										=	variance_type




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None   ):
       return sample




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase = None   ):
       a						:Optional[int]										=	num_inference_steps
       a						:Union[str, Any]										=	(self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1)
       a						:int										=	(np.arange(0 ,  _lowerCamelCase   ) * step_ratio).round()[::-1].copy().astype(np.intaa   )
       a						:List[str]										=	torch.from_numpy(_lowerCamelCase   ).to(_lowerCamelCase   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase=None ,  _lowerCamelCase=None ,  _lowerCamelCase=None   ):
       if prev_timestep is None:
             a						:Union[str, Any]										=	t - 1

       a						:Dict										=	self.alphas_cumprod[t]
       a						:str										=	self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one
       a						:Optional[Any]										=	1 - alpha_prod_t
       a						:Tuple										=	1 - alpha_prod_t_prev

       if prev_timestep == t - 1:
             a						:int										=	self.betas[t]
       else:
             a						:Tuple										=	1 - alpha_prod_t / alpha_prod_t_prev

       # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf)
       # and sample from it to get previous sample
       # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample
       a						:str										=	beta_prod_t_prev / beta_prod_t * beta

       if variance_type is None:
             a						:Optional[int]										=	self.config.variance_type

       # hacks - were probably added for training stability
       if variance_type == "fixed_small_log":
             a						:Dict										=	torch.log(torch.clamp(_lowerCamelCase ,  min=1e-20   )   )
             a						:Optional[Any]										=	torch.exp(0.5 * variance   )
       elif variance_type == "learned_range":
             # NOTE difference with DDPM scheduler
             a						:List[Any]										=	variance.log()
             a						:Any										=	beta.log()

             a						:List[Any]										=	(predicted_variance + 1) / 2
             a						:Dict										=	frac * max_log + (1 - frac) * min_log

       return variance




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase = None ,  _lowerCamelCase=None ,  _lowerCamelCase = True ,  ):
       a						:Optional[int]										=	timestep

       if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range":
             a							,    a						:Optional[int]										=	torch.split(_lowerCamelCase ,  sample.shape[1] ,  dim=1   )
       else:
             a						:int										=	None

       # 1. compute alphas, betas
       if prev_timestep is None:
             a						:Any										=	t - 1

       a						:Tuple										=	self.alphas_cumprod[t]
       a						:Optional[int]										=	self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one
       a						:Tuple										=	1 - alpha_prod_t
       a						:List[str]										=	1 - alpha_prod_t_prev

       if prev_timestep == t - 1:
             a						:Union[str, Any]										=	self.betas[t]
             a						:Optional[Any]										=	self.alphas[t]
       else:
             a						:Dict										=	1 - alpha_prod_t / alpha_prod_t_prev
             a						:Optional[Any]										=	1 - beta

       # 2. compute predicted original sample from predicted noise also called
       # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
       if self.config.prediction_type == "epsilon":
             a						:List[Any]										=	(sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
       elif self.config.prediction_type == "sample":
             a						:List[str]										=	model_output
       else:
             raise ValueError(
                 F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`'''
                 ''' for the UnCLIPScheduler.'''   )

       # 3. Clip "predicted x_0"
       if self.config.clip_sample:
             a						:List[str]										=	torch.clamp(
                 _lowerCamelCase ,  -self.config.clip_sample_range ,  self.config.clip_sample_range   )

       # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
       # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
       a						:List[str]										=	(alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t
       a						:Any										=	alpha ** 0.5 * beta_prod_t_prev / beta_prod_t

       # 5. Compute predicted previous sample µ_t
       # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
       a						:Optional[int]										=	pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample

       # 6. Add noise
       a						:Dict										=	0
       if t > 0:
             a						:Optional[int]										=	randn_tensor(
                 model_output.shape ,  dtype=model_output.dtype ,  generator=_lowerCamelCase ,  device=model_output.device   )

             a						:Dict										=	self._get_variance(
                 _lowerCamelCase ,  predicted_variance=_lowerCamelCase ,  prev_timestep=_lowerCamelCase ,  )

             if self.variance_type == "fixed_small_log":
                   a						:Optional[int]										=	variance
             elif self.variance_type == "learned_range":
                   a						:Union[str, Any]										=	(0.5 * variance).exp()
             else:
                   raise ValueError(
                       F'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`'''
                       ''' for the UnCLIPScheduler.'''   )

             a						:Optional[int]										=	variance * variance_noise

       a						:List[str]										=	pred_prev_sample + variance

       if not return_dict:
             return (pred_prev_sample,)

       return UnCLIPSchedulerOutput(prev_sample=_lowerCamelCase ,  pred_original_sample=_lowerCamelCase   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase ,  _lowerCamelCase ,  ):
       # Make sure alphas_cumprod and timestep have same device and dtype as original_samples
       a						:List[Any]										=	self.alphas_cumprod.to(device=original_samples.device ,  dtype=original_samples.dtype   )
       a						:Optional[Any]										=	timesteps.to(original_samples.device   )

       a						:Tuple										=	alphas_cumprod[timesteps] ** 0.5
       a						:List[Any]										=	sqrt_alpha_prod.flatten()
       while len(sqrt_alpha_prod.shape   ) < len(original_samples.shape   ):
             a						:Any										=	sqrt_alpha_prod.unsqueeze(-1   )

       a						:List[str]										=	(1 - alphas_cumprod[timesteps]) ** 0.5
       a						:Optional[int]										=	sqrt_one_minus_alpha_prod.flatten()
       while len(sqrt_one_minus_alpha_prod.shape   ) < len(original_samples.shape   ):
             a						:List[Any]										=	sqrt_one_minus_alpha_prod.unsqueeze(-1   )

       a						:str										=	sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
       return noisy_samples





