


'''simple docstring'''






import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil




class 						a__							(				a__    ):





							'''simple docstring'''






							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														lowerCAmelCase__			  =      pa.array(TypedSequence([1, 2, 3]  )  )
														self.assertEqual(arr.type   ,       pa.intaa()  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				str:
														with self.assertRaises(lowerCamelCase_  ):
																					lowerCAmelCase__			  =      pa.array(TypedSequence([1, 2, 3]  )   ,       type=pa.intaa()  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[str]:
														with self.assertRaises(lowerCamelCase_  ):
																					lowerCAmelCase__			  =      pa.array(TypedSequence([1, 2, 3]   ,       try_type=Value('''bool'''  )   ,       type=Value('''int64'''  )  )  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[Any]:
														lowerCAmelCase__			  =      pa.array(TypedSequence([1, 2, 3]   ,       type=Value('''int32'''  )  )  )
														self.assertEqual(arr.type   ,       pa.intaa()  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[Any]:
														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
																					lowerCAmelCase__			  =      pa.array(TypedSequence(['''foo''', '''bar''']   ,       type=Value('''int64'''  )  )  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[Any]:
														lowerCAmelCase__			  =      pa.array(TypedSequence([1, 2, 3]   ,       try_type=Value('''int32'''  )  )  )
														self.assertEqual(arr.type   ,       pa.intaa()  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														lowerCAmelCase__			  =      pa.array(TypedSequence(['''foo''', '''bar''']   ,       try_type=Value('''int64'''  )  )  )
														self.assertEqual(arr.type   ,       pa.string()  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      pa.array(TypedSequence([[[1, 2, 3]]]   ,       type=ArrayaD((1, 3)   ,       '''int64'''  )  )  )
														self.assertEqual(arr.type   ,       ArrayaDExtensionType((1, 3)   ,       '''int64'''  )  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				str:
														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)  ):
																					lowerCAmelCase__			  =      pa.array(TypedSequence(['''foo''', '''bar''']   ,       type=ArrayaD((1, 3)   ,       '''int64'''  )  )  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														lowerCAmelCase__			  =      pa.array(TypedSequence([[[1, 2, 3]]]   ,       try_type=ArrayaD((1, 3)   ,       '''int64'''  )  )  )
														self.assertEqual(arr.type   ,       ArrayaDExtensionType((1, 3)   ,       '''int64'''  )  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[Any]:
														lowerCAmelCase__			  =      pa.array(TypedSequence(['''foo''', '''bar''']   ,       try_type=ArrayaD((1, 3)   ,       '''int64'''  )  )  )
														self.assertEqual(arr.type   ,       pa.string()  )







							@require_pil
							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Dict:
														import PIL.Image

														lowerCAmelCase__			  =      PIL.Image.fromarray(np.arange(10   ,       dtype=np.uinta  ).reshape(2   ,       5  )  )
														with patch(
														    '''datasets.arrow_writer.cast_to_python_objects'''   ,       side_effect=lowerCamelCase_  ) as mock_cast_to_python_objects:
																					lowerCAmelCase__			  =      pa.array(TypedSequence([{'''path''': None, '''bytes''': b'''image_bytes'''}, pil_image]   ,       type=Image()  )  )
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      mock_cast_to_python_objects.call_args_list[-1]
																					self.assertIn('''optimize_list_casting'''   ,       lowerCamelCase_  )
																					self.assertFalse(kwargs['''optimize_list_casting''']  )


def    _snake_case  (	A					,       A			)		->       str:
							lowerCAmelCase__			  =      pa.BufferReader(A			) if isinstance(A					,       pa.Buffer			) else pa.memory_map(A			)
							lowerCAmelCase__			  =      pa.ipc.open_stream(A			)
							lowerCAmelCase__			  =      f.read_all()
							assert len(pa_table.to_batches()			) == expected_num_chunks
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
							del pa_table


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 1, 10]			)
@pytest.mark.parametrize(
    '''fields'''					,       [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]			)
def    _snake_case  (	A					,       A			)		->       Tuple:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							lowerCAmelCase__			  =      pa.schema(A			) if fields else None
							with ArrowWriter(stream=A					,       schema=A					,       writer_batch_size=A			) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}			)
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														lowerCAmelCase__			  =      {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(A					,       metadata=writer._schema.metadata			)
							_check_output(output.getvalue()					,       expected_num_chunks=num_examples if writer_batch_size == 1 else 1			)


def    _snake_case  (	)		->       Dict:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							lowerCAmelCase__			  =      Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']			)}			)
							with ArrowWriter(stream=A					,       features=A			) as writer:
														writer.write({'''labels''': 0}			)
														writer.write({'''labels''': 1}			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert writer._schema == features.arrow_schema
							assert writer._schema.metadata == features.arrow_schema.metadata
							lowerCAmelCase__			  =      pa.BufferReader(output.getvalue()			)
							lowerCAmelCase__			  =      pa.ipc.open_stream(A			)
							lowerCAmelCase__			  =      f.read_all()
							lowerCAmelCase__			  =      pa_table.schema
							assert pa_table.num_rows == 2
							assert schema == features.arrow_schema
							assert schema.metadata == features.arrow_schema.metadata
							assert features == Features.from_arrow_schema(A			)


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 1, 10]			)
def    _snake_case  (	A			)		->       Optional[int]:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ArrowWriter(
							    stream=A					,       writer_batch_size=A					,       hash_salt='''split_name'''					,       check_duplicates=A					,       ) as writer:
														with pytest.raises(A			):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}					,       key=[1, 2]			)
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 2, 10]			)
def    _snake_case  (	A			)		->       int:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ArrowWriter(
							    stream=A					,       writer_batch_size=A					,       hash_salt='''split_name'''					,       check_duplicates=A					,       ) as writer:
														with pytest.raises(A			):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}					,       key=10			)
																					writer.write({'''col_1''': '''bar''', '''col_2''': 2}					,       key=10			)
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 2, 10]			)
def    _snake_case  (	A			)		->       int:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ArrowWriter(
							    stream=A					,       writer_batch_size=A					,       hash_salt='''split_name'''					,       check_duplicates=A					,       ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}					,       key=1			)
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}					,       key=2			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_check_output(output.getvalue()					,       expected_num_chunks=num_examples if writer_batch_size == 1 else 1			)


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 1, 10]			)
@pytest.mark.parametrize(
    '''fields'''					,       [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]			)
def    _snake_case  (	A					,       A			)		->       Dict:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							lowerCAmelCase__			  =      pa.schema(A			) if fields else None
							with ArrowWriter(stream=A					,       schema=A					,       writer_batch_size=A			) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}			)
														writer.write_batch({'''col_1''': [], '''col_2''': []}			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														lowerCAmelCase__			  =      {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(A					,       metadata=writer._schema.metadata			)
							_check_output(output.getvalue()					,       expected_num_chunks=num_examples if writer_batch_size == 1 else 1			)


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 1, 10]			)
@pytest.mark.parametrize(
    '''fields'''					,       [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]			)
def    _snake_case  (	A					,       A			)		->       int:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							lowerCAmelCase__			  =      pa.schema(A			) if fields else None
							with ArrowWriter(stream=A					,       schema=A					,       writer_batch_size=A			) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}			)			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														lowerCAmelCase__			  =      {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(A					,       metadata=writer._schema.metadata			)
							_check_output(output.getvalue()					,       expected_num_chunks=num_examples if writer_batch_size == 1 else 1			)


@pytest.mark.parametrize('''writer_batch_size'''					,       [None, 1, 10]			)
@pytest.mark.parametrize(
    '''fields'''					,       [None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]			)
def    _snake_case  (	A					,       A			)		->       Any:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							lowerCAmelCase__			  =      pa.schema(A			) if fields else None
							with ArrowWriter(stream=A					,       schema=A					,       writer_batch_size=A			) as writer:
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}			)			)
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}			)			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														lowerCAmelCase__			  =      {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(A					,       metadata=writer._schema.metadata			)
							_check_output(output.getvalue()					,       expected_num_chunks=num_examples if writer_batch_size == 1 else 1			)


def    _snake_case  (	)		->       Dict:
							with tempfile.TemporaryDirectory() as tmp_dir:
														lowerCAmelCase__			  =      {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
														lowerCAmelCase__			  =      os.path.join(A					,       '''test.arrow'''			)
														with ArrowWriter(path=A					,       schema=pa.schema(A			)			) as writer:
																					writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}			)
																					lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
														assert num_examples == 2
														assert num_bytes > 0
														assert writer._schema == pa.schema(A					,       metadata=writer._schema.metadata			)
														_check_output(A					,       1			)


def    _snake_case  (	A			)		->       str:
							if pa.types.is_list(A			):
														return get_base_dtype(arr_type.value_type			)
							else:
														return arr_type


def    _snake_case  (	A					,       A			)		->       Tuple:
							if isinstance(lst[0]					,       A			):
														change_first_primitive_element_in_list(lst[0]					,       A			)
							else:
														lowerCAmelCase__			  =      value


@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''					,       [(None, pa.intaa()), (Value('''int32'''			), pa.intaa())]			)
@pytest.mark.parametrize('''sequence'''					,       [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]			)
def    _snake_case  (	A					,       A					,       A			)		->       Optional[int]:
							lowerCAmelCase__			  =      pa.array(TypedSequence(A					,       optimized_int_type=A			)			)
							assert get_base_dtype(arr.type			) == expected_dtype


@pytest.mark.parametrize(
    '''col, expected_dtype'''					,       [
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]					,       )
@pytest.mark.parametrize('''sequence'''					,       [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]			)
def    _snake_case  (	A					,       A					,       A			)		->       Dict:
							# in range
							lowerCAmelCase__			  =      pa.array(OptimizedTypedSequence(A					,       col=A			)			)
							assert get_base_dtype(arr.type			) == expected_dtype

							# not in range
							if col != "other":
														# avoids errors due to in-place modifications
														lowerCAmelCase__			  =      copy.deepcopy(A			)
														lowerCAmelCase__			  =      np.iinfo(expected_dtype.to_pandas_dtype()			).max + 1
														change_first_primitive_element_in_list(A					,       A			)
														lowerCAmelCase__			  =      pa.array(OptimizedTypedSequence(A					,       col=A			)			)
														assert get_base_dtype(arr.type			) == pa.intaa()


@pytest.mark.parametrize('''raise_exception'''					,       [False, True]			)
def    _snake_case  (	A					,       A			)		->       List[str]:
							lowerCAmelCase__			  =      str(tmp_path / '''dataset-train.arrow'''			)
							try:
														with ArrowWriter(path=A			) as writer:
																					if raise_exception:
																												raise pa.lib.ArrowInvalid()
																					else:
																												writer.stream.close()
							except pa.lib.ArrowInvalid:
														pass
							finally:
														assert writer.stream.closed


def    _snake_case  (	A			)		->       Optional[int]:
							lowerCAmelCase__			  =      '''mock://dataset-train.arrow'''
							with ArrowWriter(path=A					,       storage_options=mockfs.storage_options			) as writer:
														assert isinstance(writer._fs					,       type(A			)			)
														assert writer._fs.storage_options == mockfs.storage_options
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}			)
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert mockfs.exists(A			)


def    _snake_case  (	)		->       Union[str, Any]:
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ParquetWriter(stream=A			) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}			)
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}			)
														lowerCAmelCase__  ,   lowerCAmelCase__			  =      writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							lowerCAmelCase__			  =      pa.BufferReader(output.getvalue()			)
							lowerCAmelCase__			  =      pq.read_table(A			)
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}


@require_pil
@pytest.mark.parametrize('''embed_local_files'''					,       [False, True]			)
def    _snake_case  (	A					,       A			)		->       Optional[int]:
							import PIL.Image

							lowerCAmelCase__			  =      str(tmp_path / '''test_image_rgb.jpg'''			)
							PIL.Image.fromarray(np.zeros((5, 5)					,       dtype=np.uinta			)			).save(A					,       format='''png'''			)
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ParquetWriter(
							    stream=A					,       features=Features({'''image''': Image()}			)					,       embed_local_files=A			) as writer:
														writer.write({'''image''': image_path}			)
														writer.finalize()
							lowerCAmelCase__			  =      pa.BufferReader(output.getvalue()			)
							lowerCAmelCase__			  =      pq.read_table(A			)
							lowerCAmelCase__			  =      pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']					,       A			)
														with open(A					,       '''rb'''			) as f:
																					assert out["image"][0]["bytes"] == f.read()
							else:
														assert out["image"][0]["path"] == image_path
														assert out["image"][0]["bytes"] is None






def    _snake_case  (	)		->       Optional[Any]:
							lowerCAmelCase__			  =      pa.schema([pa.field('''col_1'''					,       pa.string()					,       nullable=A			)]			)
							lowerCAmelCase__			  =      pa.BufferOutputStream()
							with ArrowWriter(stream=A			) as writer:
														writer._build_writer(inferred_schema=A			)
														assert writer._schema == pa.schema([pa.field('''col_1'''					,       pa.string()			)]			)



'''simple docstring'''






import gc
import unittest

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

from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class 						a__							(				a__							,							a__							,							a__							,							unittest.TestCase    ):





							'''simple docstring'''






							lowercase__     :  Optional[Any]      		= AltDiffusionPipeline
							lowercase__     :  Dict      		= TEXT_TO_IMAGE_PARAMS
							lowercase__     :  str      		= TEXT_TO_IMAGE_BATCH_PARAMS
							lowercase__     :  Any      		= TEXT_TO_IMAGE_IMAGE_PARAMS
							lowercase__     :  List[str]      		= TEXT_TO_IMAGE_IMAGE_PARAMS







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				str:
														torch.manual_seed(0  )
														lowerCAmelCase__			  =      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__			  =      DDIMScheduler(
														    beta_start=0.00_085   ,       beta_end=0.012   ,       beta_schedule='''scaled_linear'''   ,       clip_sample=lowerCamelCase_   ,       set_alpha_to_one=lowerCamelCase_   ,       )
														torch.manual_seed(0  )
														lowerCAmelCase__			  =      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   ,       )

														# TODO: address the non-deterministic text encoder (fails for save-load tests)
														# torch.manual_seed(0)
														# text_encoder_config = RobertaSeriesConfig(
														#     hidden_size=32,
														#     project_dim=32,
														#     intermediate_size=37,
														#     layer_norm_eps=1e-05,
														#     num_attention_heads=4,
														#     num_hidden_layers=5,
														#     vocab_size=5002,
														# )
														# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)

														torch.manual_seed(0  )
														lowerCAmelCase__			  =      CLIPTextConfig(
														    bos_token_id=0   ,       eos_token_id=2   ,       hidden_size=32   ,       projection_dim=32   ,       intermediate_size=37   ,       layer_norm_eps=1e-05   ,       num_attention_heads=4   ,       num_hidden_layers=5   ,       pad_token_id=1   ,       vocab_size=50_02   ,       )
														lowerCAmelCase__			  =      CLIPTextModel(lowerCamelCase_  )

														lowerCAmelCase__			  =      XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''  )
														lowerCAmelCase__			  =      77

														lowerCAmelCase__			  =      {
														    '''unet''': unet,
														    '''scheduler''': scheduler,
														    '''vae''': vae,
														    '''text_encoder''': text_encoder,
														    '''tokenizer''': tokenizer,
														    '''safety_checker''': None,
														    '''feature_extractor''': None,
														}
														return components







							def     __SCREAMING_SNAKE_CASE				(						self   ,       lowerCamelCase_   ,       lowerCamelCase_=0  )			->				List[str]:
														if str(lowerCamelCase_  ).startswith('''mps'''  ):
																					lowerCAmelCase__			  =      torch.manual_seed(lowerCamelCase_  )
														else:
																					lowerCAmelCase__			  =      torch.Generator(device=lowerCamelCase_  ).manual_seed(lowerCamelCase_  )
														lowerCAmelCase__			  =      {
														    '''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     __SCREAMING_SNAKE_CASE				(						self  )			->				Union[str, Any]:
														super().test_attention_slicing_forward_pass(expected_max_diff=3e-3  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Optional[int]:
														super().test_inference_batch_single_identical(expected_max_diff=3e-3  )







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[str]:
														lowerCAmelCase__			  =      '''cpu'''  # ensure determinism for the device-dependent torch.Generator

														lowerCAmelCase__			  =      self.get_dummy_components()
														torch.manual_seed(0  )
														lowerCAmelCase__			  =      RobertaSeriesConfig(
														    hidden_size=32   ,       project_dim=32   ,       intermediate_size=37   ,       layer_norm_eps=1e-05   ,       num_attention_heads=4   ,       num_hidden_layers=5   ,       vocab_size=50_02   ,       )
														# TODO: remove after fixing the non-deterministic text encoder
														lowerCAmelCase__			  =      RobertaSeriesModelWithTransformation(lowerCamelCase_  )
														lowerCAmelCase__			  =      text_encoder

														lowerCAmelCase__			  =      AltDiffusionPipeline(**lowerCamelCase_  )
														lowerCAmelCase__			  =      alt_pipe.to(lowerCamelCase_  )
														alt_pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      self.get_dummy_inputs(lowerCamelCase_  )
														lowerCAmelCase__			  =      '''A photo of an astronaut'''
														lowerCAmelCase__			  =      alt_pipe(**lowerCamelCase_  )
														lowerCAmelCase__			  =      output.images
														lowerCAmelCase__			  =      image[0, -3:, -3:, -1]

														assert image.shape == (1, 64, 64, 3)
														lowerCAmelCase__			  =      np.array(
														    [0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093]  )

														assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[Any]:
														lowerCAmelCase__			  =      '''cpu'''  # ensure determinism for the device-dependent torch.Generator

														lowerCAmelCase__			  =      self.get_dummy_components()
														lowerCAmelCase__			  =      PNDMScheduler(skip_prk_steps=lowerCamelCase_  )
														torch.manual_seed(0  )
														lowerCAmelCase__			  =      RobertaSeriesConfig(
														    hidden_size=32   ,       project_dim=32   ,       intermediate_size=37   ,       layer_norm_eps=1e-05   ,       num_attention_heads=4   ,       num_hidden_layers=5   ,       vocab_size=50_02   ,       )
														# TODO: remove after fixing the non-deterministic text encoder
														lowerCAmelCase__			  =      RobertaSeriesModelWithTransformation(lowerCamelCase_  )
														lowerCAmelCase__			  =      text_encoder
														lowerCAmelCase__			  =      AltDiffusionPipeline(**lowerCamelCase_  )
														lowerCAmelCase__			  =      alt_pipe.to(lowerCamelCase_  )
														alt_pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      self.get_dummy_inputs(lowerCamelCase_  )
														lowerCAmelCase__			  =      alt_pipe(**lowerCamelCase_  )
														lowerCAmelCase__			  =      output.images
														lowerCAmelCase__			  =      image[0, -3:, -3:, -1]

														assert image.shape == (1, 64, 64, 3)
														lowerCAmelCase__			  =      np.array(
														    [0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237]  )

														assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2




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





							'''simple docstring'''






							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Tuple:
														# clean up the VRAM after each test
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				List[Any]:
														# make sure here that pndm scheduler skips prk
														lowerCAmelCase__			  =      AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''   ,       safety_checker=lowerCamelCase_  )
														lowerCAmelCase__			  =      alt_pipe.to(lowerCamelCase_  )
														alt_pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      '''A painting of a squirrel eating a burger'''
														lowerCAmelCase__			  =      torch.manual_seed(0  )
														lowerCAmelCase__			  =      alt_pipe([prompt]   ,       generator=lowerCamelCase_   ,       guidance_scale=6.0   ,       num_inference_steps=20   ,       output_type='''np'''  )

														lowerCAmelCase__			  =      output.images

														lowerCAmelCase__			  =      image[0, -3:, -3:, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														lowerCAmelCase__			  =      np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586]  )

														assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2







							def     __SCREAMING_SNAKE_CASE				(						self  )			->				Any:
														lowerCAmelCase__			  =      DDIMScheduler.from_pretrained('''BAAI/AltDiffusion'''   ,       subfolder='''scheduler'''  )

														lowerCAmelCase__			  =      AltDiffusionPipeline.from_pretrained('''BAAI/AltDiffusion'''   ,       scheduler=lowerCamelCase_   ,       safety_checker=lowerCamelCase_  )
														lowerCAmelCase__			  =      alt_pipe.to(lowerCamelCase_  )
														alt_pipe.set_progress_bar_config(disable=lowerCamelCase_  )

														lowerCAmelCase__			  =      '''A painting of a squirrel eating a burger'''
														lowerCAmelCase__			  =      torch.manual_seed(0  )

														lowerCAmelCase__			  =      alt_pipe([prompt]   ,       generator=lowerCamelCase_   ,       num_inference_steps=2   ,       output_type='''numpy'''  )
														lowerCAmelCase__			  =      output.images

														lowerCAmelCase__			  =      image[0, -3:, -3:, -1]

														assert image.shape == (1, 5_12, 5_12, 3)
														lowerCAmelCase__			  =      np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323]  )

														assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2