

from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
)



@flax.struct.dataclass
class 				__UpperCAmelCase		(__UpperCamelCase   ):
			__snake_case    :				jnp.ndarray
			__snake_case    :				jnp.ndarray



class 				__UpperCAmelCase		(nn.Module   ):
			__snake_case    :				int
			__snake_case    :				Tuple[int]									=							(16, 32, 96, 256)
			__snake_case    :				jnp.dtype									=							jnp.floataa







			def 							UpperCamelCase				(     self:  str					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  nn.Conv(
									    self.block_out_channels[0]				,     kernel_size=(3, 3)				,     padding=((1, 1), (1, 1))				,     dtype=self.dtype				,     )

									_SCREAMING_SNAKE_CASE     				=  []
									for i in range(len(self.block_out_channels					) - 1					):
															_SCREAMING_SNAKE_CASE     				=  self.block_out_channels[i]
															_SCREAMING_SNAKE_CASE     				=  self.block_out_channels[i + 1]
															_SCREAMING_SNAKE_CASE     				=  nn.Conv(
															    UpperCAmelCase_				,     kernel_size=(3, 3)				,     padding=((1, 1), (1, 1))				,     dtype=self.dtype				,     )
															blocks.append(UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  nn.Conv(
															    UpperCAmelCase_				,     kernel_size=(3, 3)				,     strides=(2, 2)				,     padding=((1, 1), (1, 1))				,     dtype=self.dtype				,     )
															blocks.append(UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  blocks

									_SCREAMING_SNAKE_CASE     				=  nn.Conv(
									    self.conditioning_embedding_channels				,     kernel_size=(3, 3)				,     padding=((1, 1), (1, 1))				,     kernel_init=nn.initializers.zeros_init()				,     bias_init=nn.initializers.zeros_init()				,     dtype=self.dtype				,     )







			def __call__(     self:  Optional[int]				,     UpperCAmelCase_:  List[str]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.conv_in(UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  nn.silu(UpperCAmelCase_					)

									for block in self.blocks:
															_SCREAMING_SNAKE_CASE     				=  block(UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  nn.silu(UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  self.conv_out(UpperCAmelCase_					)

									return embedding



@flax_register_to_config
class 				__UpperCAmelCase		(nn.Module	,__UpperCamelCase	,__UpperCamelCase   ):
			__snake_case    :				int									=							32
			__snake_case    :				int									=							4
			__snake_case    :				Tuple[str]									=							(
			    "CrossAttnDownBlock2D",
			    "CrossAttnDownBlock2D",
			    "CrossAttnDownBlock2D",
			    "DownBlock2D",
			)
			__snake_case    :				Union[bool, Tuple[bool]]									=							False
			__snake_case    :				Tuple[int]									=							(320, 640, 1280, 1280)
			__snake_case    :				int									=							2
			__snake_case    :				Union[int, Tuple[int]]									=							8
			__snake_case    :				Optional[Union[int, Tuple[int]]]									=							None
			__snake_case    :				int									=							1280
			__snake_case    :				float									=							0.0
			__snake_case    :				bool									=							False
			__snake_case    :				jnp.dtype									=							jnp.floataa
			__snake_case    :				bool									=							True
			__snake_case    :				int									=							0
			__snake_case    :				str									=							"rgb"
			__snake_case    :				Tuple[int]									=							(16, 32, 96, 256)







			def 							UpperCamelCase				(     self:  int				,     UpperCAmelCase_:  jax.random.KeyArray					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  (1, self.in_channels, self.sample_size, self.sample_size)
									_SCREAMING_SNAKE_CASE     				=  jnp.zeros(UpperCAmelCase_				,     dtype=jnp.floataa					)
									_SCREAMING_SNAKE_CASE     				=  jnp.ones((1,)				,     dtype=jnp.intaa					)
									_SCREAMING_SNAKE_CASE     				=  jnp.zeros((1, 1, self.cross_attention_dim)				,     dtype=jnp.floataa					)
									_SCREAMING_SNAKE_CASE     				=  (1, 3, self.sample_size * 8, self.sample_size * 8)
									_SCREAMING_SNAKE_CASE     				=  jnp.zeros(UpperCAmelCase_				,     dtype=jnp.floataa					)

									_SCREAMING_SNAKE_CASE     				=  jax.random.split(UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  {"""params""": params_rng, """dropout""": dropout_rng}

									return self.init(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)["params"]







			def 							UpperCamelCase				(     self:  Tuple					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.block_out_channels
									_SCREAMING_SNAKE_CASE     				=  block_out_channels[0] * 4

									# If `num_attention_heads` is not defined (which is the case for most models)
									# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
									# The reason for this behavior is to correct for incorrectly named variables that were introduced
									# when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
									# Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
									# which is why we correct for the naming here.
									_SCREAMING_SNAKE_CASE     				=  self.num_attention_heads or self.attention_head_dim

									# input
									_SCREAMING_SNAKE_CASE     				=  nn.Conv(
									    block_out_channels[0]				,     kernel_size=(3, 3)				,     strides=(1, 1)				,     padding=((1, 1), (1, 1))				,     dtype=self.dtype				,     )

									# time
									_SCREAMING_SNAKE_CASE     				=  FlaxTimesteps(
									    block_out_channels[0]				,     flip_sin_to_cos=self.flip_sin_to_cos				,     freq_shift=self.config.freq_shift					)
									_SCREAMING_SNAKE_CASE     				=  FlaxTimestepEmbedding(UpperCAmelCase_				,     dtype=self.dtype					)

									_SCREAMING_SNAKE_CASE     				=  FlaxControlNetConditioningEmbedding(
									    conditioning_embedding_channels=block_out_channels[0]				,     block_out_channels=self.conditioning_embedding_out_channels				,     )

									_SCREAMING_SNAKE_CASE     				=  self.only_cross_attention
									if isinstance(UpperCAmelCase_				,     UpperCAmelCase_					):
															_SCREAMING_SNAKE_CASE     				=  (only_cross_attention,) * len(self.down_block_types					)

									if isinstance(UpperCAmelCase_				,     UpperCAmelCase_					):
															_SCREAMING_SNAKE_CASE     				=  (num_attention_heads,) * len(self.down_block_types					)

									# down
									_SCREAMING_SNAKE_CASE     				=  []
									_SCREAMING_SNAKE_CASE     				=  []

									_SCREAMING_SNAKE_CASE     				=  block_out_channels[0]

									_SCREAMING_SNAKE_CASE     				=  nn.Conv(
									    UpperCAmelCase_				,     kernel_size=(1, 1)				,     padding="""VALID"""				,     kernel_init=nn.initializers.zeros_init()				,     bias_init=nn.initializers.zeros_init()				,     dtype=self.dtype				,     )
									controlnet_down_blocks.append(UpperCAmelCase_					)

									for i, down_block_type in enumerate(self.down_block_types					):
															_SCREAMING_SNAKE_CASE     				=  output_channel
															_SCREAMING_SNAKE_CASE     				=  block_out_channels[i]
															_SCREAMING_SNAKE_CASE     				=  i == len(UpperCAmelCase_					) - 1

															if down_block_type == "CrossAttnDownBlock2D":
																					_SCREAMING_SNAKE_CASE     				=  FlaxCrossAttnDownBlockaD(
																					    in_channels=UpperCAmelCase_				,     out_channels=UpperCAmelCase_				,     dropout=self.dropout				,     num_layers=self.layers_per_block				,     num_attention_heads=num_attention_heads[i]				,     add_downsample=not is_final_block				,     use_linear_projection=self.use_linear_projection				,     only_cross_attention=only_cross_attention[i]				,     dtype=self.dtype				,     )
															else:
																					_SCREAMING_SNAKE_CASE     				=  FlaxDownBlockaD(
																					    in_channels=UpperCAmelCase_				,     out_channels=UpperCAmelCase_				,     dropout=self.dropout				,     num_layers=self.layers_per_block				,     add_downsample=not is_final_block				,     dtype=self.dtype				,     )

															down_blocks.append(UpperCAmelCase_					)

															for _ in range(self.layers_per_block					):
																					_SCREAMING_SNAKE_CASE     				=  nn.Conv(
																					    UpperCAmelCase_				,     kernel_size=(1, 1)				,     padding="""VALID"""				,     kernel_init=nn.initializers.zeros_init()				,     bias_init=nn.initializers.zeros_init()				,     dtype=self.dtype				,     )
																					controlnet_down_blocks.append(UpperCAmelCase_					)

															if not is_final_block:
																					_SCREAMING_SNAKE_CASE     				=  nn.Conv(
																					    UpperCAmelCase_				,     kernel_size=(1, 1)				,     padding="""VALID"""				,     kernel_init=nn.initializers.zeros_init()				,     bias_init=nn.initializers.zeros_init()				,     dtype=self.dtype				,     )
																					controlnet_down_blocks.append(UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  down_blocks
									_SCREAMING_SNAKE_CASE     				=  controlnet_down_blocks

									# mid
									_SCREAMING_SNAKE_CASE     				=  block_out_channels[-1]
									_SCREAMING_SNAKE_CASE     				=  FlaxUNetMidBlockaDCrossAttn(
									    in_channels=UpperCAmelCase_				,     dropout=self.dropout				,     num_attention_heads=num_attention_heads[-1]				,     use_linear_projection=self.use_linear_projection				,     dtype=self.dtype				,     )

									_SCREAMING_SNAKE_CASE     				=  nn.Conv(
									    UpperCAmelCase_				,     kernel_size=(1, 1)				,     padding="""VALID"""				,     kernel_init=nn.initializers.zeros_init()				,     bias_init=nn.initializers.zeros_init()				,     dtype=self.dtype				,     )







			def __call__(     self:  List[str]				,     UpperCAmelCase_:  Union[str, Any]				,     UpperCAmelCase_:  List[str]				,     UpperCAmelCase_:  List[str]				,     UpperCAmelCase_:  int				,     UpperCAmelCase_:  float = 1.0				,     UpperCAmelCase_:  bool = True				,     UpperCAmelCase_:  bool = False				,     ):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.controlnet_conditioning_channel_order
									if channel_order == "bgr":
															_SCREAMING_SNAKE_CASE     				=  jnp.flip(UpperCAmelCase_				,     axis=1					)

									# 1. time
									if not isinstance(UpperCAmelCase_				,     jnp.ndarray					):
															_SCREAMING_SNAKE_CASE     				=  jnp.array([timesteps]				,     dtype=jnp.intaa					)
									elif isinstance(UpperCAmelCase_				,     jnp.ndarray					) and len(timesteps.shape					) == 0:
															_SCREAMING_SNAKE_CASE     				=  timesteps.astype(dtype=jnp.floataa					)
															_SCREAMING_SNAKE_CASE     				=  jnp.expand_dims(UpperCAmelCase_				,     0					)

									_SCREAMING_SNAKE_CASE     				=  self.time_proj(UpperCAmelCase_					)
									_SCREAMING_SNAKE_CASE     				=  self.time_embedding(UpperCAmelCase_					)

									# 2. pre-process
									_SCREAMING_SNAKE_CASE     				=  jnp.transpose(UpperCAmelCase_				,     (0, 2, 3, 1)					)
									_SCREAMING_SNAKE_CASE     				=  self.conv_in(UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  jnp.transpose(UpperCAmelCase_				,     (0, 2, 3, 1)					)
									_SCREAMING_SNAKE_CASE     				=  self.controlnet_cond_embedding(UpperCAmelCase_					)
									sample += controlnet_cond

									# 3. down
									_SCREAMING_SNAKE_CASE     				=  (sample,)
									for down_block in self.down_blocks:
															if isinstance(UpperCAmelCase_				,     UpperCAmelCase_					):
																					_SCREAMING_SNAKE_CASE     				=  down_block(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     deterministic=not train					)
															else:
																					_SCREAMING_SNAKE_CASE     				=  down_block(UpperCAmelCase_				,     UpperCAmelCase_				,     deterministic=not train					)
															down_block_res_samples += res_samples

									# 4. mid
									_SCREAMING_SNAKE_CASE     				=  self.mid_block(UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_				,     deterministic=not train					)

									# 5. contronet blocks
									_SCREAMING_SNAKE_CASE     				=  ()
									for down_block_res_sample, controlnet_block in zip(UpperCAmelCase_				,     self.controlnet_down_blocks					):
															_SCREAMING_SNAKE_CASE     				=  controlnet_block(UpperCAmelCase_					)
															controlnet_down_block_res_samples += (down_block_res_sample,)

									_SCREAMING_SNAKE_CASE     				=  controlnet_down_block_res_samples

									_SCREAMING_SNAKE_CASE     				=  self.controlnet_mid_block(UpperCAmelCase_					)

									# 6. scaling
									_SCREAMING_SNAKE_CASE     				=  [sample * conditioning_scale for sample in down_block_res_samples]
									mid_block_res_sample *= conditioning_scale

									if not return_dict:
															return (down_block_res_samples, mid_block_res_sample)

									return FlaxControlNetOutput(
									    down_block_res_samples=UpperCAmelCase_				,     mid_block_res_sample=UpperCAmelCase_					)









import json
import os
import unittest

from transformers import OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin



@require_tokenizers
class 				__UpperCAmelCase		(_UpperCAmelCase	,unittest.TestCase   ):
			__snake_case    :				Optional[Any]									=							OpenAIGPTTokenizer
			__snake_case    :				Dict									=							OpenAIGPTTokenizerFast
			__snake_case    :				Optional[Any]									=							True
			__snake_case    :				Dict									=							False







			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




									super().setUp()

									# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
									_SCREAMING_SNAKE_CASE     				=  [
									    """l""",
									    """o""",
									    """w""",
									    """e""",
									    """r""",
									    """s""",
									    """t""",
									    """i""",
									    """d""",
									    """n""",
									    """w</w>""",
									    """r</w>""",
									    """t</w>""",
									    """lo""",
									    """low""",
									    """er</w>""",
									    """low</w>""",
									    """lowest</w>""",
									    """newer</w>""",
									    """wider</w>""",
									    """<unk>""",
									]
									_SCREAMING_SNAKE_CASE     				=  dict(zip(UpperCAmelCase_				,     range(len(UpperCAmelCase_					)					)					)					)
									_SCREAMING_SNAKE_CASE     				=  ["""#version: 0.2""", """l o""", """lo w""", """e r</w>""", """"""]

									_SCREAMING_SNAKE_CASE     				=  os.path.join(self.tmpdirname				,     VOCAB_FILES_NAMES["""vocab_file"""]					)
									_SCREAMING_SNAKE_CASE     				=  os.path.join(self.tmpdirname				,     VOCAB_FILES_NAMES["""merges_file"""]					)
									with open(self.vocab_file				,     """w"""					) as fp:
															fp.write(json.dumps(UpperCAmelCase_					)					)
									with open(self.merges_file				,     """w"""					) as fp:
															fp.write("""\n""".join(UpperCAmelCase_					)					)







			def 							UpperCamelCase				(     self:  List[Any]				,     UpperCAmelCase_:  Dict					):







									'''simple docstring'''




									return "lower newer", "lower newer"







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  OpenAIGPTTokenizer(self.vocab_file				,     self.merges_file					)

									_SCREAMING_SNAKE_CASE     				=  """lower"""
									_SCREAMING_SNAKE_CASE     				=  ["""low""", """er</w>"""]
									_SCREAMING_SNAKE_CASE     				=  tokenizer.tokenize(UpperCAmelCase_					)
									self.assertListEqual(UpperCAmelCase_				,     UpperCAmelCase_					)

									_SCREAMING_SNAKE_CASE     				=  tokens + ["""<unk>"""]
									_SCREAMING_SNAKE_CASE     				=  [14, 15, 20]
									self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_					)				,     UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Optional[Any]				,     UpperCAmelCase_:  Union[str, Any]=15					):







									'''simple docstring'''




									for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
															with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'					):
																					_SCREAMING_SNAKE_CASE     				=  self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_				,     **UpperCAmelCase_					)

																					# Simple input
																					_SCREAMING_SNAKE_CASE     				=  """This is a simple input"""
																					_SCREAMING_SNAKE_CASE     				=  ["""This is a simple input 1""", """This is a simple input 2"""]
																					_SCREAMING_SNAKE_CASE     				=  ("""This is a simple input""", """This is a pair""")
																					_SCREAMING_SNAKE_CASE     				=  [
																					    ("""This is a simple input 1""", """This is a simple input 2"""),
																					    ("""This is a simple pair 1""", """This is a simple pair 2"""),
																					]

																					# Simple input tests
																					self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""					)

																					# Simple input
																					self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""					)

																					# Simple input
																					self.assertRaises(
																					    UpperCAmelCase_				,     tokenizer_r.batch_encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""				,     )

																					# Pair input
																					self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""					)

																					# Pair input
																					self.assertRaises(UpperCAmelCase_				,     tokenizer_r.encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""					)

																					# Pair input
																					self.assertRaises(
																					    UpperCAmelCase_				,     tokenizer_r.batch_encode_plus				,     UpperCAmelCase_				,     max_length=UpperCAmelCase_				,     padding="""max_length"""				,     )







			def 							UpperCamelCase				(     self:  List[Any]					):







									'''simple docstring'''




									pass



@require_ftfy
@require_spacy
@require_tokenizers
class 				__UpperCAmelCase		(_UpperCAmelCase   ):
			pass

