

import random


class 					A		:







    """simple docstring"""





    def __init__( self					:			Tuple,lowercase_					:			list[list[float]],lowercase_					:			list[int],lowercase_					:			float = 0.01,lowercase_					:			int = 1_0_0_0,lowercase_					:			float = -1,)->       None:





        '''simple docstring'''







        A__        =  sample
        if len(self.sample						) == 0:
            raise ValueError('Sample data can not be empty'						)
        A__        =  target
        if len(self.target						) == 0:
            raise ValueError('Target data can not be empty'						)
        if len(self.sample						) != len(self.target						):
            raise ValueError('Sample data and Target data do not have matching lengths'						)
        A__        =  learning_rate
        A__        =  epoch_number
        A__        =  bias
        A__        =  len(__UpperCamelCase						)
        A__        =  len(sample[0]						)  # number of columns in dataset
        A__        =  []


    def 		snake_case__	( self					:			Tuple						)->       None:





        '''simple docstring'''







        for sample in self.sample:
            sample.insert(0,self.bias						)

        for _ in range(self.col_sample						):
            self.weight.append(random.random()						)

        self.weight.insert(0,self.bias						)

        A__        =  0

        while True:
            A__        =  False
            for i in range(self.number_sample						):
                A__        =  0
                for j in range(self.col_sample + 1						):
                    A__        =  u + self.weight[j] * self.sample[i][j]
                A__        =  self.sign(__UpperCamelCase						)
                if y != self.target[i]:
                    for j in range(self.col_sample + 1						):
                        A__        =  (
                            self.weight[j]
                            + self.learning_rate
                            * (self.target[i] - y)
                            * self.sample[i][j]
                        )
                    A__        =  True
            # print('Epoch: \n',epoch_count)
            A__        =  epoch_count + 1
            # if you want control the epoch or just by error
            if not has_misclassified:
                print(('\nEpoch:\n', epoch_count)						)
                print('------------------------\n'						)
                # if epoch_count > self.epoch_number or not error:
                break


    def 		snake_case__	( self					:			List[str],lowercase_					:			list[float]						)->       None:





        '''simple docstring'''







        if len(self.sample						) == 0:
            raise ValueError('Sample data can not be empty'						)
        sample.insert(0,self.bias						)
        A__        =  0
        for i in range(self.col_sample + 1						):
            A__        =  u + self.weight[i] * sample[i]

        A__        =  self.sign(__UpperCamelCase						)

        if y == -1:
            print(('Sample: ', sample)						)
            print('classification: P1'						)
        else:
            print(('Sample: ', sample)						)
            print('classification: P2'						)


    def 		snake_case__	( self					:			Union[str, Any],lowercase_					:			float						)->       int:





        '''simple docstring'''







        return 1 if u >= 0 else -1




lowercase_									=    [
    [-0.6_508, 0.1_097, 4.0_009],
    [-1.4_492, 0.8_896, 4.4_005],
    [2.0_850, 0.6_876, 12.0_710],
    [0.2_626, 1.1_476, 7.7_985],
    [0.6_418, 1.0_234, 7.0_427],
    [0.2_569, 0.6_730, 8.3_265],
    [1.1_155, 0.6_043, 7.4_446],
    [0.0_914, 0.3_399, 7.0_677],
    [0.0_121, 0.5_256, 4.6_316],
    [-0.0_429, 0.4_660, 5.4_323],
    [0.4_340, 0.6_870, 8.2_287],
    [0.2_735, 1.0_287, 7.1_934],
    [0.4_839, 0.4_851, 7.4_850],
    [0.4_089, -0.1_267, 5.5_019],
    [1.4_391, 0.1_614, 8.5_843],
    [-0.9_115, -0.1_973, 2.1_962],
    [0.3_654, 1.0_475, 7.4_858],
    [0.2_144, 0.7_515, 7.1_699],
    [0.2_013, 1.0_014, 6.5_489],
    [0.6_483, 0.2_183, 5.8_991],
    [-0.1_147, 0.2_242, 7.2_435],
    [-0.7_970, 0.8_795, 3.8_762],
    [-1.0_625, 0.6_366, 2.4_707],
    [0.5_307, 0.1_285, 5.6_883],
    [-1.2_200, 0.7_777, 1.7_252],
    [0.3_957, 0.1_076, 5.6_623],
    [-0.1_013, 0.5_989, 7.1_812],
    [2.4_482, 0.9_455, 11.2_095],
    [2.0_149, 0.6_192, 10.9_263],
    [0.2_012, 0.2_611, 5.4_631],
]

lowercase_									=    [
    -1,
    -1,
    -1,
    1,
    1,
    -1,
    1,
    -1,
    1,
    1,
    -1,
    1,
    -1,
    -1,
    -1,
    -1,
    1,
    1,
    1,
    1,
    -1,
    1,
    1,
    1,
    1,
    -1,
    -1,
    1,
    -1,
    1,
]


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     lowercase_									=    Perceptron(
         sample=samples, target=target, learning_rate=0.01, epoch_number=1000, bias=-1
     )
     network.training()
     print("Finished training perceptron")
     print("Enter values to predict or q to exit")
     while True:
          lowercase_									=    []
          for i in range(len(samples[0])):
               lowercase_									=    input("value: ").strip()
               if user_input == "q":
                    break
               lowercase_									=    float(user_input)
               sample.insert(i, observation)
          network.sort(sample)






'''simple docstring'''



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
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 PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class 			_SCREAMING_SNAKE_CASE				(lowercase__,	lowercase__,	unittest.TestCase      ):
			A__								=  StableDiffusionXLPipeline
			A__								=  TEXT_TO_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_BATCH_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS
			A__								=  TEXT_TO_IMAGE_IMAGE_PARAMS



			def 				lowerCAmelCase (     self		:						List[str]			)      ->      Tuple:
							"""simple docstring"""





							torch.manual_seed(0			)
							snake_case__      :   Any      =    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''')    ,			attention_head_dim=(2, 4)    ,			use_linear_projection=__UpperCamelCase    ,			addition_embed_type='''text_time'''    ,			addition_time_embed_dim=8    ,			transformer_layers_per_block=(1, 2)    ,			projection_class_embeddings_input_dim=80    ,			cross_attention_dim=64    ,			)
							snake_case__      :   Tuple      =    EulerDiscreteScheduler(
							    beta_start=0.00085    ,			beta_end=0.012    ,			steps_offset=1    ,			beta_schedule='''scaled_linear'''    ,			timestep_spacing='''leading'''    ,			)
							torch.manual_seed(0			)
							snake_case__      :   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    ,			sample_size=128    ,			)
							torch.manual_seed(0			)
							snake_case__      :   List[Any]      =    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    ,			hidden_act='''gelu'''    ,			projection_dim=32    ,			)
							snake_case__      :   List[str]      =    CLIPTextModel(__UpperCamelCase			)
							snake_case__      :   Dict      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   Optional[int]      =    CLIPTextModelWithProjection(__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''    ,			local_files_only=__UpperCamelCase			)

							snake_case__      :   List[str]      =    {
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''vae''': vae,
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''text_encoder_2''': text_encoder_a,
							    '''tokenizer_2''': tokenizer_a,
							    # "safety_checker": None,
							    # "feature_extractor": None,
							}
							return components



			def 				lowerCAmelCase (     self		:						Union[str, Any]    ,			__UpperCamelCase		:						int    ,			__UpperCamelCase		:						Union[str, Any]=0			)      ->      Optional[Any]:
							"""simple docstring"""





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



			def 				lowerCAmelCase (     self		:						List[Any]			)      ->      Tuple:
							"""simple docstring"""





							snake_case__      :   Any      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							snake_case__      :   Union[str, Any]      =    self.get_dummy_components()
							snake_case__      :   List[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   Optional[int]      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Dict      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Union[str, Any]      =    sd_pipe(**__UpperCamelCase			).images
							snake_case__      :   List[Any]      =    image[0, -3:, -3:, -1]

							assert image.shape == (1, 64, 64, 3)
							snake_case__      :   Union[str, Any]      =    np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]			)

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



			def 				lowerCAmelCase (     self		:						Optional[Any]			)      ->      Optional[int]:
							"""simple docstring"""





							snake_case__      :   List[str]      =    self.get_dummy_components()
							snake_case__      :   Optional[Any]      =    StableDiffusionXLPipeline(**__UpperCamelCase			)
							snake_case__      :   str      =    sd_pipe.to(__UpperCamelCase			)
							snake_case__      :   Tuple      =    sd_pipe.to(__UpperCamelCase			)
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							# forward without prompt embeds
							snake_case__      :   str      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    3 * ['''this is a negative prompt''']
							snake_case__      :   Optional[int]      =    negative_prompt
							snake_case__      :   Tuple      =    3 * [inputs['''prompt''']]

							snake_case__      :   Tuple      =    sd_pipe(**__UpperCamelCase			)
							snake_case__      :   str      =    output.images[0, -3:, -3:, -1]

							# forward with prompt embeds
							snake_case__      :   Tuple      =    self.get_dummy_inputs(__UpperCamelCase			)
							snake_case__      :   List[Any]      =    3 * ['''this is a negative prompt''']
							snake_case__      :   List[Any]      =    3 * [inputs.pop('''prompt'''			)]

							(
							    (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      (
							    snake_case__
							)  ,      
							)      :   List[Any]      =    sd_pipe.encode_prompt(__UpperCamelCase    ,			negative_prompt=__UpperCamelCase			)

							snake_case__      :   Dict      =    sd_pipe(
							    **__UpperCamelCase    ,			prompt_embeds=__UpperCamelCase    ,			negative_prompt_embeds=__UpperCamelCase    ,			pooled_prompt_embeds=__UpperCamelCase    ,			negative_pooled_prompt_embeds=__UpperCamelCase    ,			)
							snake_case__      :   Optional[Any]      =    output.images[0, -3:, -3:, -1]

							# make sure that it's equal
							assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()			).max() < 1e-4



			def 				lowerCAmelCase (     self		:						Dict			)      ->      Dict:
							"""simple docstring"""





							super().test_attention_slicing_forward_pass(expected_max_diff=3e-3			)







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





							super().test_inference_batch_single_identical(expected_max_diff=3e-3			)






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



			def 				lowerCAmelCase (     self		:						Union[str, Any]			)      ->      Union[str, Any]:
							"""simple docstring"""





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



			def 				lowerCAmelCase (     self		:						Tuple    ,			__UpperCamelCase		:						Optional[int]    ,			__UpperCamelCase		:						List[str]="cpu"    ,			__UpperCamelCase		:						Tuple=torch.floataa    ,			__UpperCamelCase		:						List[str]=0			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    torch.Generator(device=__UpperCamelCase			).manual_seed(__UpperCamelCase			)
							snake_case__      :   int      =    np.random.RandomState(__UpperCamelCase			).standard_normal((1, 4, 64, 64)			)
							snake_case__      :   List[Any]      =    torch.from_numpy(__UpperCamelCase			).to(device=__UpperCamelCase    ,			dtype=__UpperCamelCase			)
							snake_case__      :   int      =    {
							    '''prompt''': '''a photograph of an astronaut riding a horse''',
							    '''latents''': latents,
							    '''generator''': generator,
							    '''num_inference_steps''': 3,
							    '''guidance_scale''': 7.5,
							    '''output_type''': '''numpy''',
							}
							return inputs







			def 				lowerCAmelCase (     self		:						int			)      ->      Dict:
							"""simple docstring"""





							snake_case__      :   Dict      =    DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''			)
							pipe.to(__UpperCamelCase			)
							pipe.set_progress_bar_config(disable=__UpperCamelCase			)

							snake_case__      :   Optional[Any]      =    self.get_inputs(__UpperCamelCase			)
							snake_case__      :   Any      =    pipe(**__UpperCamelCase			).images
							snake_case__      :   Optional[int]      =    image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 512, 512, 3)
							snake_case__      :   Tuple      =    np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]			)
							assert np.abs(image_slice - expected_slice			).max() < 7e-3




