


'''simple docstring'''

import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       Dict            =       KandinskyPriorPipeline
 _lowerCamelCase			:       Dict            =       ['prompt']
 _lowerCamelCase			:       List[str]            =       ['prompt', 'negative_prompt']
 _lowerCamelCase			:       Tuple            =       [
     'num_images_per_prompt',
     'generator',
     'num_inference_steps',
     'latents',
     'negative_prompt',
     'guidance_scale',
     'output_type',
     'return_dict',
 ]
 _lowerCamelCase			:       Tuple            =       False

 @property
 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						List[Any]       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    return self.time_input_dim

 @property
 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    return self.time_input_dim * 4

 @property
 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    return 100

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )
    return tokenizer

 @property
 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPTextConfig(
        bos_token_id=0,       eos_token_id=2,       hidden_size=self.text_embedder_hidden_size,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       layer_norm_eps=1e-0_5,       num_attention_heads=4,       num_hidden_layers=5,       pad_token_id=1,       vocab_size=1000,       )
    return CLIPTextModelWithProjection(a_       )

 @property
 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    torch.manual_seed(0       )

    UpperCamelCase__			    =    {
        "num_attention_heads": 2,
        "attention_head_dim": 12,
        "embedding_dim": self.text_embedder_hidden_size,
        "num_layers": 1,
    }

    UpperCamelCase__			    =    PriorTransformer(**a_       )
    # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
    UpperCamelCase__			    =    nn.Parameter(torch.ones(model.clip_std.shape       )       )
    return model

 @property
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPVisionConfig(
        hidden_size=self.text_embedder_hidden_size,       image_size=224,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       num_attention_heads=4,       num_channels=3,       num_hidden_layers=5,       patch_size=14,       )

    UpperCamelCase__			    =    CLIPVisionModelWithProjection(a_       )
    return model

 @property
 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPImageProcessor(
        crop_size=224,       do_center_crop=a_,       do_normalize=a_,       do_resize=a_,       image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073],       image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711],       resample=3,       size=224,       )

    return image_processor

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.dummy_prior
    UpperCamelCase__			    =    self.dummy_image_encoder
    UpperCamelCase__			    =    self.dummy_text_encoder
    UpperCamelCase__			    =    self.dummy_tokenizer
    UpperCamelCase__			    =    self.dummy_image_processor

    UpperCamelCase__			    =    UnCLIPScheduler(
        variance_type="fixed_small_log",       prediction_type="sample",       num_train_timesteps=1000,       clip_sample=a_,       clip_sample_range=10.0,       )

    UpperCamelCase__			    =    {
        "prior": prior,
        "image_encoder": image_encoder,
        "text_encoder": text_encoder,
        "tokenizer": tokenizer,
        "scheduler": scheduler,
        "image_processor": image_processor,
    }

    return components

 def 		lowercase_    (			self			:						Optional[Any],       a_			:						List[Any],       a_			:						List[str]=0       ):





    """simple docstring"""



    if str(a_       ).startswith("mps"       ):
       UpperCamelCase__			    =    torch.manual_seed(a_       )
    else:
       UpperCamelCase__			    =    torch.Generator(device=a_       ).manual_seed(a_       )
    UpperCamelCase__			    =    {
        "prompt": "horse",
        "generator": generator,
        "guidance_scale": 4.0,
        "num_inference_steps": 2,
        "output_type": "np",
    }
    return inputs

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    "cpu"

    UpperCamelCase__			    =    self.get_dummy_components()

    UpperCamelCase__			    =    self.pipeline_class(**a_       )
    UpperCamelCase__			    =    pipe.to(a_       )

    pipe.set_progress_bar_config(disable=a_       )

    UpperCamelCase__			    =    pipe(**self.get_dummy_inputs(a_       )       )
    UpperCamelCase__			    =    output.image_embeds

    UpperCamelCase__			    =    pipe(
        **self.get_dummy_inputs(a_       ),       return_dict=a_,       )[0]

    UpperCamelCase__			    =    image[0, -10:]
    UpperCamelCase__			    =    image_from_tuple[0, -10:]

    assert image.shape == (1, 32)

    UpperCamelCase__			    =    np.array(
        [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]       )

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

 @skip_mps
 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    True
    UpperCamelCase__			    =    False

    self._test_inference_batch_single_identical(
        test_max_difference=a_,       relax_max_difference=a_,       test_mean_pixel_difference=a_,       )

 @skip_mps
 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    False

    self._test_attention_slicing_forward_pass(
        test_max_difference=a_,       test_mean_pixel_difference=a_,       )



'''simple docstring'''


import os
import sys
from pathlib import Path

import pytest

from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node

from .utils import execute_subprocess_async, get_torch_dist_unique_port, require_torch






def 			__lowerCAmelCase			():
		_UpperCAmelCase		:							Optional[int]             =   Dataset.from_dict({"i": range(17 )} )
		_UpperCAmelCase		:							int             =   len(__lowerCAmelCase )
		_UpperCAmelCase		:							Dict             =   3
		_UpperCAmelCase		:							str             =   [
		    split_dataset_by_node(__lowerCAmelCase   ,			rank=__lowerCAmelCase   ,			world_size=__lowerCAmelCase ) for rank in range(__lowerCAmelCase )
		]
		assert sum(len(__lowerCAmelCase ) for ds in datasets_per_rank ) == full_size
		assert len({tuple(x.values() ) for ds in datasets_per_rank for x in ds} ) == full_size






def 			__lowerCAmelCase			():
		def gen():
				return ({"i": i} for i in range(17 ))

		_UpperCAmelCase		:							Any             =   3
		_UpperCAmelCase		:							Any             =   IterableDataset.from_generator(__lowerCAmelCase )
		_UpperCAmelCase		:							str             =   len(list(__lowerCAmelCase ) )
		_UpperCAmelCase		:							Tuple             =   [
		    split_dataset_by_node(__lowerCAmelCase   ,			rank=__lowerCAmelCase   ,			world_size=__lowerCAmelCase ) for rank in range(__lowerCAmelCase )
		]
		assert sum(len(list(__lowerCAmelCase ) ) for ds in datasets_per_rank ) == full_size
		assert len({tuple(x.values() ) for ds in datasets_per_rank for x in ds} ) == full_size






@pytest.mark.parametrize("shards_per_node"   ,			[1, 2, 3] )
def 			__lowerCAmelCase			(__lowerCAmelCase ):
		def gen(__lowerCAmelCase ):
				for shard in shards:
						yield from ({"i": i, "shard": shard} for i in range(17 ))

		_UpperCAmelCase		:							Tuple             =   3
		_UpperCAmelCase		:							Tuple             =   shards_per_node * world_size
		_UpperCAmelCase		:							Optional[int]             =   {"shards": [F"""shard_{shard_idx}.txt""" for shard_idx in range(__lowerCAmelCase )]}
		_UpperCAmelCase		:							int             =   IterableDataset.from_generator(__lowerCAmelCase   ,			gen_kwargs=__lowerCAmelCase )
		_UpperCAmelCase		:							Any             =   len(list(__lowerCAmelCase ) )
		assert full_ds.n_shards == world_size * shards_per_node
		_UpperCAmelCase		:							Optional[Any]             =   [
		    split_dataset_by_node(__lowerCAmelCase   ,			rank=__lowerCAmelCase   ,			world_size=__lowerCAmelCase ) for rank in range(__lowerCAmelCase )
		]
		assert [ds.n_shards for ds in datasets_per_rank] == [shards_per_node] * world_size
		assert sum(len(list(__lowerCAmelCase ) ) for ds in datasets_per_rank ) == full_size
		assert len({tuple(x.values() ) for ds in datasets_per_rank for x in ds} ) == full_size






def 			__lowerCAmelCase			():
		def gen():
				return ({"i": i} for i in range(17 ))

		_UpperCAmelCase		:							List[str]             =   2
		_UpperCAmelCase		:							int             =   IterableDataset.from_generator(__lowerCAmelCase )
		_UpperCAmelCase		:							Union[str, Any]             =   len(list(__lowerCAmelCase ) )

		_UpperCAmelCase		:							int             =   split_dataset_by_node(__lowerCAmelCase   ,			rank=0   ,			world_size=__lowerCAmelCase ).shuffle(seed=42 )
		assert len(list(__lowerCAmelCase ) ) == 1 + full_size // world_size
		with pytest.raises(__lowerCAmelCase ):
				split_dataset_by_node(__lowerCAmelCase   ,			rank=0   ,			world_size=__lowerCAmelCase ).shuffle()

		_UpperCAmelCase		:							Dict             =   split_dataset_by_node(full_ds.shuffle(seed=42 )   ,			rank=0   ,			world_size=__lowerCAmelCase )
		assert len(list(__lowerCAmelCase ) ) == 1 + full_size // world_size
		with pytest.raises(__lowerCAmelCase ):
				split_dataset_by_node(full_ds.shuffle()   ,			rank=0   ,			world_size=__lowerCAmelCase )






@pytest.mark.parametrize("streaming"   ,			[False, True] )
@require_torch
@pytest.mark.skipif(os.name == "nt"   ,			reason="execute_subprocess_async doesn't support windows" )
@pytest.mark.integration
def 			__lowerCAmelCase			(__lowerCAmelCase ):
		_UpperCAmelCase		:							Union[str, Any]             =   2
		_UpperCAmelCase		:							Dict             =   get_torch_dist_unique_port()
		_UpperCAmelCase		:							int             =   Path(__lowerCAmelCase ).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
		_UpperCAmelCase		:							List[Any]             =   F"""
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    """.split()
		_UpperCAmelCase		:							List[str]             =   F"""
        --streaming={streaming}
    """.split()
		_UpperCAmelCase		:							Tuple             =   [sys.executable] + distributed_args + args
		execute_subprocess_async(__lowerCAmelCase   ,			env=os.environ.copy() )






@pytest.mark.parametrize(
    "nproc_per_node, num_workers"   ,			[
        (2, 2),  # each node has 2 shards and each worker has 1 shards
        (3, 2),  # each node uses all the shards but skips examples, and each worker has 2 shards
    ]   ,			)
@require_torch
@pytest.mark.skipif(os.name == "nt"   ,			reason="execute_subprocess_async doesn't support windows" )
@pytest.mark.integration
def 			__lowerCAmelCase			(__lowerCAmelCase   ,			__lowerCAmelCase ):
		_UpperCAmelCase		:							Tuple             =   True
		_UpperCAmelCase		:							int             =   get_torch_dist_unique_port()
		_UpperCAmelCase		:							Optional[int]             =   Path(__lowerCAmelCase ).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
		_UpperCAmelCase		:							List[str]             =   F"""
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    """.split()
		_UpperCAmelCase		:							int             =   F"""
        --streaming={streaming}
        --num_workers={num_workers}
    """.split()
		_UpperCAmelCase		:							Optional[int]             =   [sys.executable] + distributed_args + args
		execute_subprocess_async(__lowerCAmelCase   ,			env=os.environ.copy() )



