

"""simple docstring"""






import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


_lowerCAmelCase						=		logging.getLogger(__name__)

def 		lowerCamelCase__		(					_lowerCamelCase=2 ,   _lowerCamelCase=3 ,   _lowerCamelCase=16 ,   _lowerCamelCase = 10 ,   _lowerCamelCase = 2   ):

    '''simple docstring'''



    def get_dataset(_lowerCamelCase   ):
        _lowerCAmelCase       :   Optional[Any]  =    torch.randn(batch_size * n_batches ,   1   )
        return TensorDataset(_lowerCamelCase ,   a * x + b + 0.1 * torch.randn(batch_size * n_batches ,   1   )   )

    _lowerCAmelCase       :   Any  =    get_dataset(_lowerCamelCase   )
    _lowerCAmelCase       :   str  =    get_dataset(_lowerCamelCase   )
    _lowerCAmelCase       :   Optional[Any]  =    DataLoader(_lowerCamelCase ,   shuffle=_lowerCamelCase ,   batch_size=_lowerCamelCase ,   num_workers=4   )
    _lowerCAmelCase       :   int  =    DataLoader(_lowerCamelCase ,   shuffle=_lowerCamelCase ,   batch_size=_lowerCamelCase ,   num_workers=4   )
    return (train_dataloader, valid_dataloader)

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase=None   ):

    '''simple docstring'''



    _lowerCAmelCase       :   int  =    []
    for epoch in range(_lowerCamelCase   ):
        # Train quickly
        model.train()
        for batch in dataloader:
            _lowerCAmelCase       :   Union[str, Any]  =    batch
            _lowerCAmelCase       :   Union[str, Any]  =    model(_lowerCamelCase   )
            _lowerCAmelCase       :   int  =    torch.nn.functional.mse_loss(_lowerCamelCase ,   _lowerCamelCase   )
            accelerator.backward(_lowerCamelCase   )
            optimizer.step()
            optimizer.zero_grad()
        rands.append(random.random()   )  # Introduce some randomness
        if scheduler is not None:
            scheduler.step()
    return rands







class 	__UpperCamelCase    (    nn.Module						):

  def __init__(		self      ):
      '''simple docstring'''

      super().__init__()
      _lowerCAmelCase       :   int  =    nn.Parameter(torch.randn(1      )      )
      _lowerCAmelCase       :   Dict  =    nn.Parameter(torch.randn(1      )      )







  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      return x * self.a + self.b







class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdir:
          set_seed(42      )
          _lowerCAmelCase       :   Union[str, Any]  =    DummyModel()
          _lowerCAmelCase       :   List[Any]  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   Optional[Any]  =    dummy_dataloaders()
          _lowerCAmelCase       :   str  =    ProjectConfiguration(total_limit=1    ,project_dir=_A    ,automatic_checkpoint_naming=_A      )
          # Train baseline
          _lowerCAmelCase       :   Any  =    Accelerator(project_config=_A      )
          _lowerCAmelCase       :   str  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A      )
          # Save initial
          accelerator.save_state()

          # Save second state
          accelerator.save_state()
          self.assertEqual(len(os.listdir(accelerator.project_dir      )      )    ,1      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdir:
          set_seed(42      )
          _lowerCAmelCase       :   int  =    DummyModel()
          _lowerCAmelCase       :   Any  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   Dict  =    dummy_dataloaders()
          # Train baseline
          _lowerCAmelCase       :   Any  =    Accelerator()
          _lowerCAmelCase       :   List[str]  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A      )
          # Save initial
          _lowerCAmelCase       :   Any  =    os.path.join(_A    ,'initial'      )
          accelerator.save_state(_A      )
          (_lowerCAmelCase)       :   List[Any]  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   Any  =    optimizer.state_dict()
          _lowerCAmelCase       :   Any  =    train(3    ,_A    ,_A    ,_A    ,_A      )
          (_lowerCAmelCase)       :   List[Any]  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   List[str]  =    optimizer.state_dict()

          # Train partially
          set_seed(42      )
          _lowerCAmelCase       :   Dict  =    DummyModel()
          _lowerCAmelCase       :   Any  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   int  =    dummy_dataloaders()
          _lowerCAmelCase       :   str  =    Accelerator()
          _lowerCAmelCase       :   int  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A      )
          accelerator.load_state(_A      )
          (_lowerCAmelCase)       :   List[str]  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   Any  =    optimizer.state_dict()
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )

          _lowerCAmelCase       :   List[str]  =    train(2    ,_A    ,_A    ,_A    ,_A      )
          # Save everything
          _lowerCAmelCase       :   List[str]  =    os.path.join(_A    ,'checkpoint'      )
          accelerator.save_state(_A      )

          # Load everything back in and make sure all states work
          accelerator.load_state(_A      )
          test_rands += train(1    ,_A    ,_A    ,_A    ,_A      )
          (_lowerCAmelCase)       :   Tuple  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   str  =    optimizer.state_dict()
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdir:
          set_seed(42      )
          _lowerCAmelCase       :   int  =    DummyModel()
          _lowerCAmelCase       :   List[Any]  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   List[Any]  =    dummy_dataloaders()
          _lowerCAmelCase       :   Union[str, Any]  =    ProjectConfiguration(automatic_checkpoint_naming=_A      )

          # Train baseline
          _lowerCAmelCase       :   List[Any]  =    Accelerator(project_dir=_A    ,project_config=_A      )
          _lowerCAmelCase       :   str  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A      )
          # Save initial
          accelerator.save_state()
          (_lowerCAmelCase)       :   Union[str, Any]  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   str  =    optimizer.state_dict()
          _lowerCAmelCase       :   Optional[Any]  =    train(3    ,_A    ,_A    ,_A    ,_A      )
          (_lowerCAmelCase)       :   int  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   Union[str, Any]  =    optimizer.state_dict()

          # Train partially
          set_seed(42      )
          _lowerCAmelCase       :   List[Any]  =    DummyModel()
          _lowerCAmelCase       :   Tuple  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   Dict  =    dummy_dataloaders()
          _lowerCAmelCase       :   Dict  =    ProjectConfiguration(iteration=1    ,automatic_checkpoint_naming=_A      )
          _lowerCAmelCase       :   List[str]  =    Accelerator(project_dir=_A    ,project_config=_A      )
          _lowerCAmelCase       :   List[Any]  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A      )
          accelerator.load_state(os.path.join(_A    ,'checkpoints'    ,'checkpoint_0'      )      )
          (_lowerCAmelCase)       :   List[str]  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   List[str]  =    optimizer.state_dict()
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )

          _lowerCAmelCase       :   Dict  =    train(2    ,_A    ,_A    ,_A    ,_A      )
          # Save everything
          accelerator.save_state()

          # Load everything back in and make sure all states work
          accelerator.load_state(os.path.join(_A    ,'checkpoints'    ,'checkpoint_1'      )      )
          test_rands += train(1    ,_A    ,_A    ,_A    ,_A      )
          (_lowerCAmelCase)       :   str  =    model.a.item(), model.b.item()
          _lowerCAmelCase       :   Dict  =    optimizer.state_dict()
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )
          self.assertEqual(_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    torch.tensor([1, 2, 3]      )
      _lowerCAmelCase       :   Union[str, Any]  =    torch.tensor([2, 3, 4]      )
      _lowerCAmelCase       :   str  =    DummyModel()
      _lowerCAmelCase       :   Union[str, Any]  =    torch.optim.Adam(net.parameters()      )
      _lowerCAmelCase       :   Any  =    Accelerator()
      with self.assertRaises(_A      ) as ve:
          accelerator.register_for_checkpointing(_A    ,_A    ,_A    ,_A      )
      _lowerCAmelCase       :   int  =    str(ve.exception      )
      self.assertTrue('Item at index 0' in message      )
      self.assertTrue('Item at index 1' in message      )
      self.assertFalse('Item at index 2' in message      )
      self.assertFalse('Item at index 3' in message      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdir:
          set_seed(42      )
          _lowerCAmelCase       :   str  =    DummyModel()
          _lowerCAmelCase       :   Optional[Any]  =    torch.optim.Adam(params=model.parameters()    ,lr=1E-3      )
          _lowerCAmelCase       :   Any  =    torch.optim.lr_scheduler.StepLR(_A    ,step_size=1    ,gamma=0.9_9      )
          _lowerCAmelCase       :   Optional[Any]  =    dummy_dataloaders()
          _lowerCAmelCase       :   Optional[Any]  =    ProjectConfiguration(automatic_checkpoint_naming=_A      )
          # Train baseline
          _lowerCAmelCase       :   Optional[Any]  =    Accelerator(project_dir=_A    ,project_config=_A      )
          _lowerCAmelCase       :   Optional[int]  =    accelerator.prepare(
              _A    ,_A    ,_A    ,_A    ,_A      )
          # Save initial
          accelerator.save_state()
          _lowerCAmelCase       :   str  =    scheduler.state_dict()
          train(3    ,_A    ,_A    ,_A    ,_A    ,_A      )
          self.assertNotEqual(_A    ,scheduler.state_dict()      )

          # Load everything back in and make sure all states work
          accelerator.load_state(os.path.join(_A    ,'checkpoints'    ,'checkpoint_0'      )      )
          self.assertEqual(_A    ,scheduler.state_dict()      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      with tempfile.TemporaryDirectory() as tmpdir:
          set_seed(42      )
          _lowerCAmelCase       :   Any  =    DummyModel()
          _lowerCAmelCase       :   Tuple  =    ProjectConfiguration(automatic_checkpoint_naming=_A    ,total_limit=2      )
          # Train baseline
          _lowerCAmelCase       :   int  =    Accelerator(project_dir=_A    ,project_config=_A      )
          _lowerCAmelCase       :   Dict  =    accelerator.prepare(_A      )
          # Save 3 states:
          for _ in range(11      ):
              accelerator.save_state()
          self.assertTrue(not os.path.exists(os.path.join(_A    ,'checkpoints'    ,'checkpoint_0'      )      )      )
          self.assertTrue(os.path.exists(os.path.join(_A    ,'checkpoints'    ,'checkpoint_9'      )      )      )
          self.assertTrue(os.path.exists(os.path.join(_A    ,'checkpoints'    ,'checkpoint_10'      )      )      )







  @require_cuda
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    ['torchrun', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__      )]
      execute_subprocess_async(_A    ,env=os.environ.copy()      )


if __name__ == "__main__":
 _lowerCAmelCase						=		"""/tmp/accelerate/state_checkpointing"""
 _lowerCAmelCase						=		DummyModel()
 _lowerCAmelCase						=		torch.optim.Adam(params=model.parameters(), lr=1E-3)
 _lowerCAmelCase						=		torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
 _lowerCAmelCase	,   _lowerCAmelCase						=		dummy_dataloaders()
 _lowerCAmelCase						=		ProjectConfiguration(automatic_checkpoint_naming=True)
 # Train baseline
 _lowerCAmelCase						=		Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""")
 if accelerator.process_index == 0:
  if os.path.exists(savedir):
   shutil.rmtree(savedir)
  os.makedirs(savedir)
 _lowerCAmelCase	,   _lowerCAmelCase	,   _lowerCAmelCase	,   _lowerCAmelCase	,   _lowerCAmelCase						=		accelerator.prepare(
     model, optimizer, train_dataloader, valid_dataloader, scheduler
 )
 _lowerCAmelCase	,   _lowerCAmelCase						=		accelerator.prepare(model, optimizer)
 train(3, model, train_dataloader, optimizer, accelerator, scheduler)
 # Check that the intial optimizer is loaded on the GPU
 for group in optimizer.param_groups:
  _lowerCAmelCase						=		group["""params"""][0].device
  break
 assert param_device.type == accelerator.device.type
 _lowerCAmelCase						=		model.cpu()
 accelerator.wait_for_everyone()
 accelerator.save_state()
 accelerator.wait_for_everyone()

 # Check CPU state
 accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""")
 for group in optimizer.param_groups:
  _lowerCAmelCase						=		group["""params"""][0].device
  break
 assert (
     param_device.type == torch.device("""cpu""").type
 ), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

 # Check device state
 model.to(accelerator.device)
 accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""")
 for group in optimizer.param_groups:
  _lowerCAmelCase						=		group["""params"""][0].device
  break
 assert (
     param_device.type == accelerator.device.type
 ), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

 # Check error
 with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""):
  accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""")
 accelerator.wait_for_everyone()
 if accelerator.process_index == 0:
  shutil.rmtree(savedir)
 accelerator.wait_for_everyone()








"""simple docstring"""






import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 	__UpperCamelCase    (    a__							,							unittest.TestCase						):
  _UpperCAmelCase          =		LDMTextToImagePipeline
  _UpperCAmelCase          =		TEXT_TO_IMAGE_PARAMS - {
      "negative_prompt",
      "negative_prompt_embeds",
      "cross_attention_kwargs",
      "prompt_embeds",
  }
  _UpperCAmelCase          =		PipelineTesterMixin.required_optional_params - {
      "num_images_per_prompt",
      "callback",
      "callback_steps",
  }
  _UpperCAmelCase          =		TEXT_TO_IMAGE_BATCH_PARAMS
  _UpperCAmelCase          =		False

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(0      )
      _lowerCAmelCase       :   Optional[int]  =    UNetaDConditionModel(
          block_out_channels=(32, 64)    ,layers_per_block=2    ,sample_size=32    ,in_channels=4    ,out_channels=4    ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,cross_attention_dim=32    ,)
      _lowerCAmelCase       :   Union[str, Any]  =    DDIMScheduler(
          beta_start=0.0_0_0_8_5    ,beta_end=0.0_1_2    ,beta_schedule='scaled_linear'    ,clip_sample=_A    ,set_alpha_to_one=_A    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Union[str, Any]  =    AutoencoderKL(
          block_out_channels=(32, 64)    ,in_channels=3    ,out_channels=3    ,down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D')    ,up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D')    ,latent_channels=4    ,)
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Dict  =    CLIPTextConfig(
          bos_token_id=0    ,eos_token_id=2    ,hidden_size=32    ,intermediate_size=37    ,layer_norm_eps=1E-05    ,num_attention_heads=4    ,num_hidden_layers=5    ,pad_token_id=1    ,vocab_size=1000    ,)
      _lowerCAmelCase       :   Tuple  =    CLIPTextModel(_A      )
      _lowerCAmelCase       :   Any  =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

      _lowerCAmelCase       :   List[str]  =    {
          'unet': unet,
          'scheduler': scheduler,
          'vqvae': vae,
          'bert': text_encoder,
          'tokenizer': tokenizer,
      }
      return components

  def __lowerCamelCase		(		self    ,_A    ,_A=0      ):
      '''simple docstring'''

      if str(_A      ).startswith('mps'      ):
          _lowerCAmelCase       :   int  =    torch.manual_seed(_A      )
      else:
          _lowerCAmelCase       :   Optional[Any]  =    torch.Generator(device=_A      ).manual_seed(_A      )
      _lowerCAmelCase       :   List[Any]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator

      _lowerCAmelCase       :   int  =    self.get_dummy_components()
      _lowerCAmelCase       :   str  =    LDMTextToImagePipeline(**_A      )
      pipe.to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   List[Any]  =    self.get_dummy_inputs(_A      )
      _lowerCAmelCase       :   Any  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Optional[int]  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 16, 16, 3)
      _lowerCAmelCase       :   Tuple  =    np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]      )

      assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-3







@slow
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   Optional[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   List[str]  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   Optional[Any]  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   List[Any]  =    pipe(**_A      ).images
      _lowerCAmelCase       :   Dict  =    image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 256, 256, 3)
      _lowerCAmelCase       :   str  =    np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]      )
      _lowerCAmelCase       :   Dict  =    np.abs(expected_slice - image_slice      ).max()
      assert max_diff < 1E-3







@nightly
@require_torch_gpu
class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

  def __lowerCamelCase		(		self    ,_A    ,_A=torch.floataa    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    torch.manual_seed(_A      )
      _lowerCAmelCase       :   Optional[int]  =    np.random.RandomState(_A      ).standard_normal((1, 4, 32, 32)      )
      _lowerCAmelCase       :   List[Any]  =    torch.from_numpy(_A      ).to(device=_A    ,dtype=_A      )
      _lowerCAmelCase       :   int  =    {
          'prompt': 'A painting of a squirrel eating a burger',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 50,
          'guidance_scale': 6.0,
          'output_type': 'numpy',
      }
      return inputs







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'      ).to(_A      )
      pipe.set_progress_bar_config(disable=_A      )

      _lowerCAmelCase       :   str  =    self.get_inputs(_A      )
      _lowerCAmelCase       :   Union[str, Any]  =    pipe(**_A      ).images[0]

      _lowerCAmelCase       :   int  =    load_numpy(
          'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'      )
      _lowerCAmelCase       :   List[str]  =    np.abs(expected_image - image      ).max()
      assert max_diff < 1E-3





