
"""simple docstring"""





from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block



@dataclass
class __lowerCAmelCase					(       SCREAMING_SNAKE_CASE_   ):




			"""simple docstring"""







			snake_case						   =					42





class __lowerCAmelCase					(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_   ):




			"""simple docstring"""







			@register_to_config
			def __init__(					self    :       List[str]							, _snake_case    :       int = 65_536							, _snake_case    :       Optional[int] = None							, _snake_case    :       Optional[int] = 2							, _snake_case    :       Optional[Any] = 2							, _snake_case    :       Dict = 0							, _snake_case    :       Dict = "fourier"							, _snake_case    :       Any = True							, _snake_case    :       Optional[Any] = False							, _snake_case    :       Tuple = 0.0							, _snake_case    :       int = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")							, _snake_case    :       Optional[Any] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")							, _snake_case    :       int = "UNetMidBlock1D"							, _snake_case    :       Any = None							, _snake_case    :       Union[str, Any] = (32, 32, 64)							, _snake_case    :       Any = None							, _snake_case    :       Optional[Any] = 8							, _snake_case    :       List[Any] = 1							, _snake_case    :       Optional[int] = False							, )   ->			List[str]:







								"""simple docstring"""
								super().__init__()
								A_								=    sample_size

								# time
								if time_embedding_type == "fourier":
													A_								=    GaussianFourierProjection(
													    embedding_size=8							, set_W_to_weight=snake_case__							, log=snake_case__							, flip_sin_to_cos=snake_case__						)
													A_								=    2 * block_out_channels[0]
								elif time_embedding_type == "positional":
													A_								=    Timesteps(
													    block_out_channels[0]							, flip_sin_to_cos=snake_case__							, downscale_freq_shift=snake_case__						)
													A_								=    block_out_channels[0]

								if use_timestep_embedding:
													A_								=    block_out_channels[0] * 4
													A_								=    TimestepEmbedding(
													    in_channels=snake_case__							, time_embed_dim=snake_case__							, act_fn=snake_case__							, out_dim=block_out_channels[0]							, )

								A_								=    nn.ModuleList([]						)
								A_								=    None
								A_								=    nn.ModuleList([]						)
								A_								=    None

								# down
								A_								=    in_channels
								for i, down_block_type in enumerate(snake_case__						):
													A_								=    output_channel
													A_								=    block_out_channels[i]

													if i == 0:
																		input_channel += extra_in_channels

													A_								=    i == len(snake_case__						) - 1

													A_								=    get_down_block(
													    snake_case__							, num_layers=snake_case__							, in_channels=snake_case__							, out_channels=snake_case__							, temb_channels=block_out_channels[0]							, add_downsample=not is_final_block or downsample_each_block							, )
													self.down_blocks.append(snake_case__						)

								# mid
								A_								=    get_mid_block(
								    snake_case__							, in_channels=block_out_channels[-1]							, mid_channels=block_out_channels[-1]							, out_channels=block_out_channels[-1]							, embed_dim=block_out_channels[0]							, num_layers=snake_case__							, add_downsample=snake_case__							, )

								# up
								A_								=    list(reversed(snake_case__						)						)
								A_								=    reversed_block_out_channels[0]
								if out_block_type is None:
													A_								=    out_channels
								else:
													A_								=    block_out_channels[0]

								for i, up_block_type in enumerate(snake_case__						):
													A_								=    output_channel
													A_								=    (
													    reversed_block_out_channels[i + 1] if i < len(snake_case__						) - 1 else final_upsample_channels
													)

													A_								=    i == len(snake_case__						) - 1

													A_								=    get_up_block(
													    snake_case__							, num_layers=snake_case__							, in_channels=snake_case__							, out_channels=snake_case__							, temb_channels=block_out_channels[0]							, add_upsample=not is_final_block							, )
													self.up_blocks.append(snake_case__						)
													A_								=    output_channel

								# out
								A_								=    norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4							, 32						)
								A_								=    get_out_block(
								    out_block_type=snake_case__							, num_groups_out=snake_case__							, embed_dim=block_out_channels[0]							, out_channels=snake_case__							, act_fn=snake_case__							, fc_dim=block_out_channels[-1] // 4							, )






			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[Any]							, _snake_case    :       Tuple							, _snake_case    :       Optional[Any] = True							, )   ->			str:







								"""simple docstring"""
								A_								=    timestep
								if not torch.is_tensor(snake_case__						):
													A_								=    torch.tensor([timesteps]							, dtype=torch.long							, device=sample.device						)
								elif torch.is_tensor(snake_case__						) and len(timesteps.shape						) == 0:
													A_								=    timesteps[None].to(sample.device						)

								A_								=    self.time_proj(snake_case__						)
								if self.config.use_timestep_embedding:
													A_								=    self.time_mlp(snake_case__						)
								else:
													A_								=    timestep_embed[..., None]
													A_								=    timestep_embed.repeat([1, 1, sample.shape[2]]						).to(sample.dtype						)
													A_								=    timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:])						)

								# 2. down
								A_								=    ()
								for downsample_block in self.down_blocks:
													A_								=    downsample_block(hidden_states=snake_case__							, temb=snake_case__						)
													down_block_res_samples += res_samples

								# 3. mid
								if self.mid_block:
													A_								=    self.mid_block(snake_case__							, snake_case__						)

								# 4. up
								for i, upsample_block in enumerate(self.up_blocks						):
													A_								=    down_block_res_samples[-1:]
													A_								=    down_block_res_samples[:-1]
													A_								=    upsample_block(snake_case__							, res_hidden_states_tuple=snake_case__							, temb=snake_case__						)

								# 5. post-process
								if self.out_block:
													A_								=    self.out_block(snake_case__							, snake_case__						)

								if not return_dict:
													return (sample,)

								return UNetaDOutput(sample=snake_case__						)








'''simple docstring'''







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

import numpy as np
from datasets import Dataset

from transformers.models.realm.configuration_realm import RealmConfig
from transformers.models.realm.retrieval_realm import _REALM_BLOCK_RECORDS_FILENAME, RealmRetriever
from transformers.models.realm.tokenization_realm import VOCAB_FILES_NAMES, RealmTokenizer
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							tempfile.mkdtemp()
            _lowerCAmelCase     :				List[str]       =							5

            # Realm tok
            _lowerCAmelCase     :				str       =							[
                '[UNK]',
                '[CLS]',
                '[SEP]',
                '[PAD]',
                '[MASK]',
                'test',
                'question',
                'this',
                'is',
                'the',
                'first',
                'second',
                'third',
                'fourth',
                'fifth',
                'record',
                'want',
                '##want',
                '##ed',
                'wa',
                'un',
                'runn',
                '##ing',
                ',',
                'low',
                'lowest',
            ]
            _lowerCAmelCase     :				Union[str, Any]       =							os.path.join(self.tmpdirname   ,						'realm_tokenizer' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )
            _lowerCAmelCase     :				Dict       =							os.path.join(snake_case__   ,						VOCAB_FILES_NAMES['vocab_file'] )
            with open(self.vocab_file   ,						'w'   ,						encoding='utf-8' ) as vocab_writer:
                   vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )

            _lowerCAmelCase     :				List[str]       =							os.path.join(self.tmpdirname   ,						'realm_block_records' )
            os.makedirs(snake_case__   ,						exist_ok=snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            return RealmTokenizer.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_tokenizer' ) )







     def a						(			self ):

            '''simple docstring'''

            shutil.rmtree(self.tmpdirname )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							RealmConfig(num_block_records=self.num_block_records )
            return config







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							Dataset.from_dict(
                {
                    'id': ['0', '1'],
                    'question': ['foo', 'bar'],
                    'answers': [['Foo', 'Bar'], ['Bar']],
                } )
            return dataset







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							np.array(
                [
                    b'This is the first record',
                    b'This is the second record',
                    b'This is the third record',
                    b'This is the fourth record',
                    b'This is the fifth record',
                    b'This is a longer longer longer record',
                ]   ,						dtype=snake_case__   ,						)
            return block_records







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							RealmRetriever(
                block_records=self.get_dummy_block_records()   ,						tokenizer=self.get_tokenizer()   ,						)
            return retriever







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[int]       =							self.get_config()
            _lowerCAmelCase     :				List[Any]       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				Any       =							retriever.tokenizer

            _lowerCAmelCase     :				Tuple       =							np.array([0, 3]   ,						dtype='long' )
            _lowerCAmelCase     :				Dict       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				int       =							tokenizer(
                ['the fourth']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Tuple       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				Union[str, Any]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(len(snake_case__ )   ,						2 )
            self.assertEqual(concat_inputs.input_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.attention_mask.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.token_type_ids.shape   ,						(2, 10) )
            self.assertEqual(concat_inputs.special_tokens_mask.shape   ,						(2, 10) )
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[0] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'first', 'record', '[SEP]']   ,						)
            self.assertEqual(
                tokenizer.convert_ids_to_tokens(concat_inputs.input_ids[1] )   ,						['[CLS]', 'test', 'question', '[SEP]', 'this', 'is', 'the', 'fourth', 'record', '[SEP]']   ,						)







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				int       =							self.get_config()
            _lowerCAmelCase     :				int       =							self.get_dummy_retriever()
            _lowerCAmelCase     :				List[str]       =							retriever.tokenizer

            _lowerCAmelCase     :				List[Any]       =							np.array([0, 3, 5]   ,						dtype='long' )
            _lowerCAmelCase     :				str       =							tokenizer(['Test question'] ).input_ids
            _lowerCAmelCase     :				Union[str, Any]       =							tokenizer(
                ['the fourth', 'longer longer']   ,						add_special_tokens=snake_case__   ,						return_token_type_ids=snake_case__   ,						return_attention_mask=snake_case__   ,						).input_ids
            _lowerCAmelCase     :				Optional[int]       =							config.reader_seq_len

            _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase     :				List[str]       =							retriever(
                snake_case__   ,						snake_case__   ,						answer_ids=snake_case__   ,						max_length=snake_case__   ,						return_tensors='np' )

            self.assertEqual([False, True, True]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [6, -1, -1], [6, 7, 8]]   ,						snake_case__ )
            self.assertEqual([[-1, -1, -1], [7, -1, -1], [7, 8, 9]]   ,						snake_case__ )







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.get_dummy_retriever()
            retriever.save_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )

            # Test local path
            _lowerCAmelCase     :				Union[str, Any]       =							retriever.from_pretrained(os.path.join(self.tmpdirname   ,						'realm_block_records' ) )
            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

            # Test mocked remote path
            with patch('transformers.models.realm.retrieval_realm.hf_hub_download' ) as mock_hf_hub_download:
                   _lowerCAmelCase     :				Any       =							os.path.join(
                       os.path.join(self.tmpdirname   ,						'realm_block_records' )   ,						_REALM_BLOCK_RECORDS_FILENAME )
                   _lowerCAmelCase     :				str       =							RealmRetriever.from_pretrained('google/realm-cc-news-pretrained-openqa' )

            self.assertEqual(retriever.block_records[0]   ,						b'This is the first record' )

