
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("""3.8"""):
				import importlib_metadata
else:
				import importlib.metadata as importlib_metadata






def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_=False		)		->		int:
					'''simple docstring'''


					try:
										SCREAMING_SNAKE_CASE__													= os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										SCREAMING_SNAKE_CASE__													= default
					else:
										# KEY is set, convert it to True or False.
										try:
															SCREAMING_SNAKE_CASE__													= strtobool(UpperCamelCase_		)
										except ValueError:
															# More values are supported, but let's keep the message simple.
															raise ValueError(F'If set, {key} must be yes or no.'		)
					return _value


__snake_case								=  parse_flag_from_env("""RUN_SLOW""", default=False)
__snake_case								=  parse_flag_from_env("""RUN_REMOTE""", default=False)
__snake_case								=  parse_flag_from_env("""RUN_LOCAL""", default=True)
__snake_case								=  parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
__snake_case								=  pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
__snake_case								=  pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
__snake_case								=  pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
__snake_case								=  pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("""soundfile""") is None or version.parse(importlib_metadata.version("""soundfile""")) < version.parse("""0.12.0"""),
    reason="""test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; """,
)

# Beam
__snake_case								=  pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("""0.3.2"""),
    reason="""test requires apache-beam and a compatible dill version""",
)

# Dill-cloudpickle compatibility
__snake_case								=  pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
__snake_case								=  pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)






def 							_lowercase							(     UpperCamelCase_		)		->		Optional[Any]:
					'''simple docstring'''


					try:
										import faiss  # noqa
					except ImportError:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires faiss'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		str:
					'''simple docstring'''


					try:
										import regex  # noqa
					except ImportError:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires regex'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		List[str]:
					'''simple docstring'''


					try:
										import elasticsearch  # noqa
					except ImportError:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires elasticsearch'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		List[Any]:
					'''simple docstring'''


					try:
										import sqlalchemy  # noqa
					except ImportError:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires sqlalchemy'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		str:
					'''simple docstring'''


					if not config.TORCH_AVAILABLE:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires PyTorch'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		int:
					'''simple docstring'''


					if not config.TF_AVAILABLE:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires TensorFlow'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		str:
					'''simple docstring'''


					if not config.JAX_AVAILABLE:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires JAX'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Tuple:
					'''simple docstring'''


					if not config.PIL_AVAILABLE:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires Pillow'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Optional[int]:
					'''simple docstring'''


					try:
										import transformers  # noqa F401
					except ImportError:
										return unittest.skip('test requires transformers'		)(UpperCamelCase_		)
					else:
										return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		List[str]:
					'''simple docstring'''


					try:
										import tiktoken  # noqa F401
					except ImportError:
										return unittest.skip('test requires tiktoken'		)(UpperCamelCase_		)
					else:
										return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Dict:
					'''simple docstring'''


					try:
										import spacy  # noqa F401
					except ImportError:
										return unittest.skip('test requires spacy'		)(UpperCamelCase_		)
					else:
										return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Any:
					'''simple docstring'''


					def _require_spacy_model(UpperCamelCase_		):
										try:
															import spacy  # noqa F401

															spacy.load(UpperCamelCase_		)
										except ImportError:
															return unittest.skip('test requires spacy'		)(UpperCamelCase_		)
										except OSError:
															return unittest.skip('test requires spacy model \'{}\''.format(UpperCamelCase_		)		)(UpperCamelCase_		)
										else:
															return test_case

					return _require_spacy_model






def 							_lowercase							(     UpperCamelCase_		)		->		Tuple:
					'''simple docstring'''


					try:
										import pyspark  # noqa F401
					except ImportError:
										return unittest.skip('test requires pyspark'		)(UpperCamelCase_		)
					else:
										return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Optional[Any]:
					'''simple docstring'''


					try:
										import joblibspark  # noqa F401
					except ImportError:
										return unittest.skip('test requires joblibspark'		)(UpperCamelCase_		)
					else:
										return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Any:
					'''simple docstring'''


					if not _run_slow_tests or _run_slow_tests == 0:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test is slow'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Optional[Any]:
					'''simple docstring'''


					if not _run_local_tests or _run_local_tests == 0:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test is local'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Dict:
					'''simple docstring'''


					if not _run_packaged_tests or _run_packaged_tests == 0:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test is packaged'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     UpperCamelCase_		)		->		Dict:
					'''simple docstring'''


					if not _run_remote_tests or _run_remote_tests == 0:
										SCREAMING_SNAKE_CASE__													= unittest.skip('test requires remote'		)(UpperCamelCase_		)
					return test_case






def 							_lowercase							(     *UpperCamelCase_		)		->		Dict:
					'''simple docstring'''


					def decorate(cls		):
										for name, fn in cls.__dict__.items():
															if callable(UpperCamelCase_		) and name.startswith('test'		):
																				for decorator in decorators:
																									SCREAMING_SNAKE_CASE__													= decorator(UpperCamelCase_		)
																				setattr(cls	,	UpperCamelCase_	,	UpperCamelCase_		)
										return cls

					return decorate




class 						lowercase__  (						_UpperCAmelCase  ):
	pass





class 						lowercase__  (						_UpperCAmelCase  ):
	A__    :   Union[str, Any]				       =0
	A__    :   int				       =1
	A__    :   Dict				       =2






@contextmanager
def 							_lowercase							(     UpperCamelCase_=OfflineSimulationMode.CONNECTION_FAILS	,	UpperCamelCase_=1e-16		)		->		Dict:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__													= requests.Session().request

					def timeout_request(UpperCamelCase_	,	UpperCamelCase_	,	UpperCamelCase_	,	**UpperCamelCase_		):
										# Change the url to an invalid url so that the connection hangs
										SCREAMING_SNAKE_CASE__													= 'https://10.255.255.1'
										if kwargs.get('timeout'		) is None:
															raise RequestWouldHangIndefinitelyError(
															    F'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'		)
										SCREAMING_SNAKE_CASE__													= timeout
										try:
															return online_request(UpperCamelCase_	,	UpperCamelCase_	,	**UpperCamelCase_		)
										except Exception as e:
															# The following changes in the error are just here to make the offline timeout error prettier
															SCREAMING_SNAKE_CASE__													= url
															SCREAMING_SNAKE_CASE__													= e.args[0]
															SCREAMING_SNAKE_CASE__													= (max_retry_error.args[0].replace('10.255.255.1'	,	F'OfflineMock[{url}]'		),)
															SCREAMING_SNAKE_CASE__													= (max_retry_error,)
															raise

					def raise_connection_error(UpperCamelCase_	,	UpperCamelCase_	,	**UpperCamelCase_		):
										raise requests.ConnectionError('Offline mode is enabled.'	,	request=UpperCamelCase_		)

					if mode is OfflineSimulationMode.CONNECTION_FAILS:
										with patch('requests.Session.send'	,	UpperCamelCase_		):
															yield
					elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
										# inspired from https://stackoverflow.com/a/904609
										with patch('requests.Session.request'	,	UpperCamelCase_		):
															yield
					elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
										with patch('datasets.config.HF_DATASETS_OFFLINE'	,	UpperCamelCase_		):
															yield
					else:
										raise ValueError('Please use a value from the OfflineSimulationMode enum.'		)






@contextmanager
def 							_lowercase							(     *UpperCamelCase_	,	**UpperCamelCase_		)		->		str:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__													= str(Path().resolve()		)
					with tempfile.TemporaryDirectory(*UpperCamelCase_	,	**UpperCamelCase_		) as tmp_dir:
										try:
															os.chdir(UpperCamelCase_		)
															yield
										finally:
															os.chdir(UpperCamelCase_		)






@contextmanager
def 							_lowercase							(     )		->		int:
					'''simple docstring'''


					import gc

					gc.collect()
					SCREAMING_SNAKE_CASE__													= pa.total_allocated_bytes()
					yield
					assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."






@contextmanager
def 							_lowercase							(     )		->		str:
					'''simple docstring'''


					import gc

					gc.collect()
					SCREAMING_SNAKE_CASE__													= pa.total_allocated_bytes()
					yield
					assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."






def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_		)		->		List[Any]:
					'''simple docstring'''


					return deepcopy(UpperCamelCase_		).integers(0	,	100	,	10		).tolist() == deepcopy(UpperCamelCase_		).integers(0	,	100	,	10		).tolist()






def 							_lowercase							(     UpperCamelCase_		)		->		str:
					'''simple docstring'''


					import decorator
					from requests.exceptions import HTTPError

					def _wrapper(UpperCamelCase_	,	*UpperCamelCase_	,	**UpperCamelCase_		):
										try:
															return func(*UpperCamelCase_	,	**UpperCamelCase_		)
										except HTTPError as err:
															if str(UpperCamelCase_		).startswith('500'		) or str(UpperCamelCase_		).startswith('502'		):
																				pytest.xfail(str(UpperCamelCase_		)		)
															raise err

					return decorator.decorator(_wrapper	,	UpperCamelCase_		)




class 						lowercase__  :
	def __init__(			self							:   Union[str, Any]       ,   UpperCAmelCase_							:   List[str]       ,   UpperCAmelCase_							:   Optional[int]       ,   UpperCAmelCase_							:   Any							):
						SCREAMING_SNAKE_CASE__													= returncode
						SCREAMING_SNAKE_CASE__													= stdout
						SCREAMING_SNAKE_CASE__													= stderr






async def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_		)		->		Union[str, Any]:
					'''simple docstring'''


					while True:
										SCREAMING_SNAKE_CASE__													= await stream.readline()
										if line:
															callback(UpperCamelCase_		)
										else:
															break






async def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_=None	,	UpperCamelCase_=None	,	UpperCamelCase_=None	,	UpperCamelCase_=False	,	UpperCamelCase_=False		)		->		_RunOutput:
					'''simple docstring'''


					if echo:
										print('\nRunning: '	,	' '.join(UpperCamelCase_		)		)

					SCREAMING_SNAKE_CASE__													= await asyncio.create_subprocess_exec(
					    cmd[0]	,	*cmd[1:]	,	stdin=UpperCamelCase_	,	stdout=asyncio.subprocess.PIPE	,	stderr=asyncio.subprocess.PIPE	,	env=UpperCamelCase_	,	)

					# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
					# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
					#
					# If it starts hanging, will need to switch to the following code. The problem is that no data
					# will be seen until it's done and if it hangs for example there will be no debug info.
					# out, err = await p.communicate()
					# return _RunOutput(p.returncode, out, err)

					SCREAMING_SNAKE_CASE__													= []
					SCREAMING_SNAKE_CASE__													= []

					def tee(UpperCamelCase_	,	UpperCamelCase_	,	UpperCamelCase_	,	UpperCamelCase_=""		):
										SCREAMING_SNAKE_CASE__													= line.decode('utf-8'		).rstrip()
										sink.append(UpperCamelCase_		)
										if not quiet:
															print(UpperCamelCase_	,	UpperCamelCase_	,	file=UpperCamelCase_		)

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        _read_stream(p.stdout	,	lambda UpperCamelCase_		: tee(UpperCamelCase_	,	UpperCamelCase_	,	sys.stdout	,	label='stdout:'		)		),
					        _read_stream(p.stderr	,	lambda UpperCamelCase_		: tee(UpperCamelCase_	,	UpperCamelCase_	,	sys.stderr	,	label='stderr:'		)		),
					    ]	,	timeout=UpperCamelCase_	,	)
					return _RunOutput(await p.wait()	,	UpperCamelCase_	,	UpperCamelCase_		)






def 							_lowercase							(     UpperCamelCase_	,	UpperCamelCase_=None	,	UpperCamelCase_=None	,	UpperCamelCase_=180	,	UpperCamelCase_=False	,	UpperCamelCase_=True		)		->		_RunOutput:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__													= asyncio.get_event_loop()
					SCREAMING_SNAKE_CASE__													= loop.run_until_complete(
					    _stream_subprocess(UpperCamelCase_	,	env=UpperCamelCase_	,	stdin=UpperCamelCase_	,	timeout=UpperCamelCase_	,	quiet=UpperCamelCase_	,	echo=UpperCamelCase_		)		)

					SCREAMING_SNAKE_CASE__													= ' '.join(UpperCamelCase_		)
					if result.returncode > 0:
										SCREAMING_SNAKE_CASE__													= '\n'.join(result.stderr		)
										raise RuntimeError(
										    F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
										    F'The combined stderr from workers follows:\n{stderr}'		)

					# check that the subprocess actually did run and produced some output, should the test rely on
					# the remote side to do the testing
					if not result.stdout and not result.stderr:
										raise RuntimeError(F'\'{cmd_str}\' produced no output.'		)

					return result






def 							_lowercase							(     )		->		str:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__													= os.environ.get('PYTEST_XDIST_WORKER'	,	'gw0'		)
					SCREAMING_SNAKE_CASE__													= re.sub(r'^gw'	,	''	,	UpperCamelCase_	,	0	,	re.M		)
					return int(UpperCamelCase_		)






def 							_lowercase							(     )		->		Dict:
					'''simple docstring'''


					SCREAMING_SNAKE_CASE__													= 29500
					SCREAMING_SNAKE_CASE__													= pytest_xdist_worker_id()
					return port + uniq_delta







import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD




class 						lowercase__  (						nn.Module  ):
	A__    :   int
	A__    :   int
	A__    :   float				       =0.0
	A__    :   int				       =1
	A__    :   int				       =1
	A__    :   bool				       =True
	A__    :   bool				       =False
	A__    :   bool				       =False
	A__    :   bool				       =False
	A__    :   jnp.dtype				       =jnp.floataa
	def      A_				(			self							:   Optional[Any]							):
						SCREAMING_SNAKE_CASE__													= []
						SCREAMING_SNAKE_CASE__													= []

						for i in range(self.num_layers							):
											SCREAMING_SNAKE_CASE__													= self.in_channels if i == 0 else self.out_channels

											SCREAMING_SNAKE_CASE__													= FlaxResnetBlockaD(
											    in_channels=UpperCAmelCase_       ,   out_channels=self.out_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
											resnets.append(UpperCAmelCase_							)

											SCREAMING_SNAKE_CASE__													= FlaxTransformeraDModel(
											    in_channels=self.out_channels       ,   n_heads=self.num_attention_heads       ,   d_head=self.out_channels // self.num_attention_heads       ,   depth=1       ,   use_linear_projection=self.use_linear_projection       ,   only_cross_attention=self.only_cross_attention       ,   use_memory_efficient_attention=self.use_memory_efficient_attention       ,   dtype=self.dtype       ,   )
											attentions.append(UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= resnets
						SCREAMING_SNAKE_CASE__													= attentions

						if self.add_downsample:
											SCREAMING_SNAKE_CASE__													= FlaxDownsampleaD(self.out_channels       ,   dtype=self.dtype							)





	def __call__(			self							:   int       ,   UpperCAmelCase_							:   str       ,   UpperCAmelCase_							:   Tuple       ,   UpperCAmelCase_							:   Dict       ,   UpperCAmelCase_							:   int=True							):
						SCREAMING_SNAKE_CASE__													= ()

						for resnet, attn in zip(self.resnets       ,   self.attentions							):
											SCREAMING_SNAKE_CASE__													= resnet(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)
											SCREAMING_SNAKE_CASE__													= attn(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)
											output_states += (hidden_states,)

						if self.add_downsample:
											SCREAMING_SNAKE_CASE__													= self.downsamplers_a(UpperCAmelCase_							)
											output_states += (hidden_states,)

						return hidden_states, output_states





class 						lowercase__  (						nn.Module  ):
	A__    :   int
	A__    :   int
	A__    :   float				       =0.0
	A__    :   int				       =1
	A__    :   bool				       =True
	A__    :   jnp.dtype				       =jnp.floataa
	def      A_				(			self							:   List[str]							):
						SCREAMING_SNAKE_CASE__													= []

						for i in range(self.num_layers							):
											SCREAMING_SNAKE_CASE__													= self.in_channels if i == 0 else self.out_channels

											SCREAMING_SNAKE_CASE__													= FlaxResnetBlockaD(
											    in_channels=UpperCAmelCase_       ,   out_channels=self.out_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
											resnets.append(UpperCAmelCase_							)
						SCREAMING_SNAKE_CASE__													= resnets

						if self.add_downsample:
											SCREAMING_SNAKE_CASE__													= FlaxDownsampleaD(self.out_channels       ,   dtype=self.dtype							)





	def __call__(			self							:   List[str]       ,   UpperCAmelCase_							:   Any       ,   UpperCAmelCase_							:   Union[str, Any]       ,   UpperCAmelCase_							:   List[Any]=True							):
						SCREAMING_SNAKE_CASE__													= ()

						for resnet in self.resnets:
											SCREAMING_SNAKE_CASE__													= resnet(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)
											output_states += (hidden_states,)

						if self.add_downsample:
											SCREAMING_SNAKE_CASE__													= self.downsamplers_a(UpperCAmelCase_							)
											output_states += (hidden_states,)

						return hidden_states, output_states





class 						lowercase__  (						nn.Module  ):
	A__    :   int
	A__    :   int
	A__    :   int
	A__    :   float				       =0.0
	A__    :   int				       =1
	A__    :   int				       =1
	A__    :   bool				       =True
	A__    :   bool				       =False
	A__    :   bool				       =False
	A__    :   bool				       =False
	A__    :   jnp.dtype				       =jnp.floataa
	def      A_				(			self							:   List[str]							):
						SCREAMING_SNAKE_CASE__													= []
						SCREAMING_SNAKE_CASE__													= []

						for i in range(self.num_layers							):
											SCREAMING_SNAKE_CASE__													= self.in_channels if (i == self.num_layers - 1) else self.out_channels
											SCREAMING_SNAKE_CASE__													= self.prev_output_channel if i == 0 else self.out_channels

											SCREAMING_SNAKE_CASE__													= FlaxResnetBlockaD(
											    in_channels=resnet_in_channels + res_skip_channels       ,   out_channels=self.out_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
											resnets.append(UpperCAmelCase_							)

											SCREAMING_SNAKE_CASE__													= FlaxTransformeraDModel(
											    in_channels=self.out_channels       ,   n_heads=self.num_attention_heads       ,   d_head=self.out_channels // self.num_attention_heads       ,   depth=1       ,   use_linear_projection=self.use_linear_projection       ,   only_cross_attention=self.only_cross_attention       ,   use_memory_efficient_attention=self.use_memory_efficient_attention       ,   dtype=self.dtype       ,   )
											attentions.append(UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= resnets
						SCREAMING_SNAKE_CASE__													= attentions

						if self.add_upsample:
											SCREAMING_SNAKE_CASE__													= FlaxUpsampleaD(self.out_channels       ,   dtype=self.dtype							)





	def __call__(			self							:   str       ,   UpperCAmelCase_							:   str       ,   UpperCAmelCase_							:   Any       ,   UpperCAmelCase_							:   str       ,   UpperCAmelCase_							:   Any       ,   UpperCAmelCase_							:   Union[str, Any]=True							):
						for resnet, attn in zip(self.resnets       ,   self.attentions							):
											# pop res hidden states
											SCREAMING_SNAKE_CASE__													= res_hidden_states_tuple[-1]
											SCREAMING_SNAKE_CASE__													= res_hidden_states_tuple[:-1]
											SCREAMING_SNAKE_CASE__													= jnp.concatenate((hidden_states, res_hidden_states)       ,   axis=-1							)

											SCREAMING_SNAKE_CASE__													= resnet(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)
											SCREAMING_SNAKE_CASE__													= attn(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)

						if self.add_upsample:
											SCREAMING_SNAKE_CASE__													= self.upsamplers_a(UpperCAmelCase_							)

						return hidden_states





class 						lowercase__  (						nn.Module  ):
	A__    :   int
	A__    :   int
	A__    :   int
	A__    :   float				       =0.0
	A__    :   int				       =1
	A__    :   bool				       =True
	A__    :   jnp.dtype				       =jnp.floataa
	def      A_				(			self							:   List[Any]							):
						SCREAMING_SNAKE_CASE__													= []

						for i in range(self.num_layers							):
											SCREAMING_SNAKE_CASE__													= self.in_channels if (i == self.num_layers - 1) else self.out_channels
											SCREAMING_SNAKE_CASE__													= self.prev_output_channel if i == 0 else self.out_channels

											SCREAMING_SNAKE_CASE__													= FlaxResnetBlockaD(
											    in_channels=resnet_in_channels + res_skip_channels       ,   out_channels=self.out_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
											resnets.append(UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= resnets

						if self.add_upsample:
											SCREAMING_SNAKE_CASE__													= FlaxUpsampleaD(self.out_channels       ,   dtype=self.dtype							)





	def __call__(			self							:   Tuple       ,   UpperCAmelCase_							:   Any       ,   UpperCAmelCase_							:   Any       ,   UpperCAmelCase_							:   Dict       ,   UpperCAmelCase_							:   Dict=True							):
						for resnet in self.resnets:
											# pop res hidden states
											SCREAMING_SNAKE_CASE__													= res_hidden_states_tuple[-1]
											SCREAMING_SNAKE_CASE__													= res_hidden_states_tuple[:-1]
											SCREAMING_SNAKE_CASE__													= jnp.concatenate((hidden_states, res_hidden_states)       ,   axis=-1							)

											SCREAMING_SNAKE_CASE__													= resnet(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)

						if self.add_upsample:
											SCREAMING_SNAKE_CASE__													= self.upsamplers_a(UpperCAmelCase_							)

						return hidden_states





class 						lowercase__  (						nn.Module  ):
	A__    :   int
	A__    :   float				       =0.0
	A__    :   int				       =1
	A__    :   int				       =1
	A__    :   bool				       =False
	A__    :   bool				       =False
	A__    :   jnp.dtype				       =jnp.floataa
	def      A_				(			self							:   Optional[int]							):
						# there is always at least one resnet
						SCREAMING_SNAKE_CASE__													= [
						    FlaxResnetBlockaD(
						        in_channels=self.in_channels       ,   out_channels=self.in_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
						]

						SCREAMING_SNAKE_CASE__													= []

						for _ in range(self.num_layers							):
											SCREAMING_SNAKE_CASE__													= FlaxTransformeraDModel(
											    in_channels=self.in_channels       ,   n_heads=self.num_attention_heads       ,   d_head=self.in_channels // self.num_attention_heads       ,   depth=1       ,   use_linear_projection=self.use_linear_projection       ,   use_memory_efficient_attention=self.use_memory_efficient_attention       ,   dtype=self.dtype       ,   )
											attentions.append(UpperCAmelCase_							)

											SCREAMING_SNAKE_CASE__													= FlaxResnetBlockaD(
											    in_channels=self.in_channels       ,   out_channels=self.in_channels       ,   dropout_prob=self.dropout       ,   dtype=self.dtype       ,   )
											resnets.append(UpperCAmelCase_							)

						SCREAMING_SNAKE_CASE__													= resnets
						SCREAMING_SNAKE_CASE__													= attentions





	def __call__(			self							:   str       ,   UpperCAmelCase_							:   Union[str, Any]       ,   UpperCAmelCase_							:   Optional[int]       ,   UpperCAmelCase_							:   List[str]       ,   UpperCAmelCase_							:   Any=True							):
						SCREAMING_SNAKE_CASE__													= self.resnets[0](UpperCAmelCase_       ,   UpperCAmelCase_							)
						for attn, resnet in zip(self.attentions       ,   self.resnets[1:]							):
											SCREAMING_SNAKE_CASE__													= attn(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)
											SCREAMING_SNAKE_CASE__													= resnet(UpperCAmelCase_       ,   UpperCAmelCase_       ,   deterministic=UpperCAmelCase_							)

						return hidden_states





