

import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

import pytest
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


UpperCAmelCase__ :     Any				    =    logging.getLogger(__name__)






def 					__lowercase      (     _A=2						,    _A=3						,    _A=16						,    _A = 10						,    _A = 2			)     ->						Union[str, Any]:






      def get_dataset(_A			):
            SCREAMING_SNAKE_CASE :      int       =   torch.randn(batch_size * n_batches						,    1			)
            return TensorDataset(_UpperCamelCase						,    a * x + b + 0.1 * torch.randn(batch_size * n_batches						,    1			)			)

      SCREAMING_SNAKE_CASE :      Dict       =   get_dataset(_UpperCamelCase			)
      SCREAMING_SNAKE_CASE :      str       =   get_dataset(_UpperCamelCase			)
      SCREAMING_SNAKE_CASE :      Optional[Any]       =   DataLoader(_UpperCamelCase						,    shuffle=_UpperCamelCase						,    batch_size=_UpperCamelCase						,    num_workers=4			)
      SCREAMING_SNAKE_CASE :      str       =   DataLoader(_UpperCamelCase						,    shuffle=_UpperCamelCase						,    batch_size=_UpperCamelCase						,    num_workers=4			)
      return (train_dataloader, valid_dataloader)






def 					__lowercase      (     _A						,    _A						,    _A						,    _A						,    _A						,    _A=None			)     ->						Optional[int]:
      SCREAMING_SNAKE_CASE :      List[Any]       =   []
      for epoch in range(_UpperCamelCase			):
            # Train quickly
            model.train()
            for batch in dataloader:
                  SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Optional[Any]       =   batch
                  SCREAMING_SNAKE_CASE :      str       =   model(_UpperCamelCase			)
                  SCREAMING_SNAKE_CASE :      str       =   torch.nn.functional.mse_loss(_UpperCamelCase						,    _UpperCamelCase			)
                  accelerator.backward(_UpperCamelCase			)
                  optimizer.step()
                  optimizer.zero_grad()
            rands.append(random.random()			)  # Introduce some randomness
            if scheduler is not None:
                  scheduler.step()
      return rands







class        a__       (   nn.Module       ):







  """simple docstring"""




  def __init__(			self    : List[Any]		)					->str:
        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE :      Any       =   nn.Parameter(torch.randn(1		)		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   nn.Parameter(torch.randn(1		)		)




  def  _lowercase      (			self    : Optional[Any]				,				UpperCAmelCase__    : Tuple		)					->str:
        """simple docstring"""







        return x * self.a + self.b







class        a__       (   unittest.TestCase       ):







  """simple docstring"""




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







        with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      List[str]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      Dict       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Dict       =   dummy_dataloaders()
              SCREAMING_SNAKE_CASE :      int       =   ProjectConfiguration(total_limit=1				,				project_dir=UpperCAmelCase__				,				automatic_checkpoint_naming=UpperCAmelCase__		)
              # Train baseline
              SCREAMING_SNAKE_CASE :      List[str]       =   Accelerator(project_config=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Optional[int]       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save initial
              accelerator.save_state()

              # Save second state
              accelerator.save_state()
              self.assertEqual(len(os.listdir(accelerator.project_dir		)		)				,				1		)


  def  _lowercase      (			self    : int		)					->int:
        """simple docstring"""







        with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      int       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Optional[Any]       =   dummy_dataloaders()
              # Train baseline
              SCREAMING_SNAKE_CASE :      Optional[int]       =   Accelerator()
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Union[str, Any]       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save initial
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   os.path.join(UpperCAmelCase__				,				"""initial"""		)
              accelerator.save_state(UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      List[str]       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      List[Any]       =   optimizer.state_dict()
              SCREAMING_SNAKE_CASE :      Dict       =   train(3				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Optional[Any]       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      int       =   optimizer.state_dict()

              # Train partially
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      List[Any]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      Tuple       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      str       =   dummy_dataloaders()
              SCREAMING_SNAKE_CASE :      List[str]       =   Accelerator()
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Dict       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              accelerator.load_state(UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Tuple       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      Dict       =   optimizer.state_dict()
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      int       =   train(2				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save everything
              SCREAMING_SNAKE_CASE :      Any       =   os.path.join(UpperCAmelCase__				,				"""checkpoint"""		)
              accelerator.save_state(UpperCAmelCase__		)

              # Load everything back in and make sure all states work
              accelerator.load_state(UpperCAmelCase__		)
              test_rands += train(1				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Dict       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      List[str]       =   optimizer.state_dict()
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)


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







        with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      List[str]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      List[Any]       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Union[str, Any]       =   dummy_dataloaders()
              SCREAMING_SNAKE_CASE :      int       =   ProjectConfiguration(automatic_checkpoint_naming=UpperCAmelCase__		)

              # Train baseline
              SCREAMING_SNAKE_CASE :      Any       =   Accelerator(project_dir=UpperCAmelCase__				,				project_config=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Any       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save initial
              accelerator.save_state()
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Optional[int]       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      int       =   optimizer.state_dict()
              SCREAMING_SNAKE_CASE :      str       =   train(3				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Dict       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   optimizer.state_dict()

              # Train partially
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      int       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Tuple       =   dummy_dataloaders()
              SCREAMING_SNAKE_CASE :      List[Any]       =   ProjectConfiguration(iteration=1				,				automatic_checkpoint_naming=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Any       =   Accelerator(project_dir=UpperCAmelCase__				,				project_config=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Optional[Any]       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              accelerator.load_state(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_0"""		)		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      List[str]       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      Optional[int]       =   optimizer.state_dict()
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE :      Tuple       =   train(2				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save everything
              accelerator.save_state()

              # Load everything back in and make sure all states work
              accelerator.load_state(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_1"""		)		)
              test_rands += train(1				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              ((SCREAMING_SNAKE_CASE)     ,	(SCREAMING_SNAKE_CASE)) :      Optional[Any]       =   model.a.item(), model.b.item()
              SCREAMING_SNAKE_CASE :      List[Any]       =   optimizer.state_dict()
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertEqual(UpperCAmelCase__				,				UpperCAmelCase__		)


  def  _lowercase      (			self    : Optional[int]		)					->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   torch.tensor([1, 2, 3]		)
        SCREAMING_SNAKE_CASE :      Any       =   torch.tensor([2, 3, 4]		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   DummyModel()
        SCREAMING_SNAKE_CASE :      int       =   torch.optim.Adam(net.parameters()		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   Accelerator()
        with self.assertRaises(UpperCAmelCase__		) as ve:
              accelerator.register_for_checkpointing(UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      str       =   str(ve.exception		)
        self.assertTrue("""Item at index 0""" in message		)
        self.assertTrue("""Item at index 1""" in message		)
        self.assertFalse("""Item at index 2""" in message		)
        self.assertFalse("""Item at index 3""" in message		)


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







        with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      List[str]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   torch.optim.Adam(params=model.parameters()				,				lr=1e-3		)
              SCREAMING_SNAKE_CASE :      Dict       =   torch.optim.lr_scheduler.StepLR(UpperCAmelCase__				,				step_size=1				,				gamma=0.99		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Union[str, Any]       =   dummy_dataloaders()
              SCREAMING_SNAKE_CASE :      Tuple       =   ProjectConfiguration(automatic_checkpoint_naming=UpperCAmelCase__		)
              # Train baseline
              SCREAMING_SNAKE_CASE :      Dict       =   Accelerator(project_dir=UpperCAmelCase__				,				project_config=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Optional[Any]       =   accelerator.prepare(
                  UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              # Save initial
              accelerator.save_state()
              SCREAMING_SNAKE_CASE :      Optional[int]       =   scheduler.state_dict()
              train(3				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)
              self.assertNotEqual(UpperCAmelCase__				,				scheduler.state_dict()		)

              # Load everything back in and make sure all states work
              accelerator.load_state(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_0"""		)		)
              self.assertEqual(UpperCAmelCase__				,				scheduler.state_dict()		)


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







        with tempfile.TemporaryDirectory() as tmpdir:
              set_seed(4_2		)
              SCREAMING_SNAKE_CASE :      List[Any]       =   DummyModel()
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   ProjectConfiguration(automatic_checkpoint_naming=UpperCAmelCase__				,				total_limit=2		)
              # Train baseline
              SCREAMING_SNAKE_CASE :      int       =   Accelerator(project_dir=UpperCAmelCase__				,				project_config=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Tuple       =   accelerator.prepare(UpperCAmelCase__		)
              # Save 3 states:
              for _ in range(1_1		):
                    accelerator.save_state()
              self.assertTrue(not os.path.exists(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_0"""		)		)		)
              self.assertTrue(os.path.exists(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_9"""		)		)		)
              self.assertTrue(os.path.exists(os.path.join(UpperCAmelCase__				,				"""checkpoints"""				,				"""checkpoint_10"""		)		)		)




  @require_cuda
  def  _lowercase      (			self    : Optional[Any]		)					->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      int       =   ["""torchrun""", f"--nproc_per_node={torch.cuda.device_count()}", inspect.getfile(self.__class__		)]
        execute_subprocess_async(UpperCAmelCase__				,				env=os.environ.copy()		)


if __name__ == "__main__":
  UpperCAmelCase__ :     str				    =    """/tmp/accelerate/state_checkpointing"""
  UpperCAmelCase__ :     Any				    =    DummyModel()
  UpperCAmelCase__ :     List[str]				    =    torch.optim.Adam(params=model.parameters(), lr=1E-3)
  UpperCAmelCase__ :     Any				    =    torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
  UpperCAmelCase__    ,   UpperCAmelCase__ :     int				    =    dummy_dataloaders()
  UpperCAmelCase__ :     List[Any]				    =    ProjectConfiguration(automatic_checkpoint_naming=True)
  # Train baseline
  UpperCAmelCase__ :     Any				    =    Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""")
  if accelerator.process_index == 0:
    if os.path.exists(savedir):
      shutil.rmtree(savedir)
    os.makedirs(savedir)
  UpperCAmelCase__    ,   UpperCAmelCase__    ,   UpperCAmelCase__    ,   UpperCAmelCase__    ,   UpperCAmelCase__ :     Optional[int]				    =    accelerator.prepare(
      model, optimizer, train_dataloader, valid_dataloader, scheduler
  )
  UpperCAmelCase__    ,   UpperCAmelCase__ :     List[str]				    =    accelerator.prepare(model, optimizer)
  train(3, model, train_dataloader, optimizer, accelerator, scheduler)
  # Check that the intial optimizer is loaded on the GPU
  for group in optimizer.param_groups:
    UpperCAmelCase__ :     int				    =    group["""params"""][0].device
    break
  assert param_device.type == accelerator.device.type
  UpperCAmelCase__ :     Optional[int]				    =    model.cpu()
  accelerator.wait_for_everyone()
  accelerator.save_state()
  accelerator.wait_for_everyone()

  # Check CPU state
  accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""")
  for group in optimizer.param_groups:
    UpperCAmelCase__ :     Union[str, Any]				    =    group["""params"""][0].device
    break
  assert (
      param_device.type == torch.device("""cpu""").type
  ), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

  # Check device state
  model.to(accelerator.device)
  accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""")
  for group in optimizer.param_groups:
    UpperCAmelCase__ :     str				    =    group["""params"""][0].device
    break
  assert (
      param_device.type == accelerator.device.type
  ), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

  # Check error
  with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""):
    accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""")
  accelerator.wait_for_everyone()
  if accelerator.process_index == 0:
    shutil.rmtree(savedir)
  accelerator.wait_for_everyone()







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

import numpy as np
from datasets import Dataset

from transformers import is_faiss_available
from transformers.models.bart.configuration_bart import BartConfig
from transformers.models.bart.tokenization_bart import BartTokenizer
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES
from transformers.models.dpr.configuration_dpr import DPRConfig
from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer
from transformers.models.rag.configuration_rag import RagConfig
from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES
from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch


if is_faiss_available():
  import faiss







@require_faiss
class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




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







        SCREAMING_SNAKE_CASE :      List[Any]       =   tempfile.mkdtemp()
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   8

        # DPR tok
        SCREAMING_SNAKE_CASE :      List[str]       =   [
            """[UNK]""",
            """[CLS]""",
            """[SEP]""",
            """[PAD]""",
            """[MASK]""",
            """want""",
            """##want""",
            """##ed""",
            """wa""",
            """un""",
            """runn""",
            """##ing""",
            """,""",
            """low""",
            """lowest""",
        ]
        SCREAMING_SNAKE_CASE :      Any       =   os.path.join(self.tmpdirname				,				"""dpr_tokenizer"""		)
        os.makedirs(UpperCAmelCase__				,				exist_ok=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Any       =   os.path.join(UpperCAmelCase__				,				DPR_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]		)		)

        # BART tok
        SCREAMING_SNAKE_CASE :      List[str]       =   [
            """l""",
            """o""",
            """w""",
            """e""",
            """r""",
            """s""",
            """t""",
            """i""",
            """d""",
            """n""",
            """\u0120""",
            """\u0120l""",
            """\u0120n""",
            """\u0120lo""",
            """\u0120low""",
            """er""",
            """\u0120lowest""",
            """\u0120newer""",
            """\u0120wider""",
            """<unk>""",
        ]
        SCREAMING_SNAKE_CASE :      List[Any]       =   dict(zip(UpperCAmelCase__				,				range(len(UpperCAmelCase__		)		)		)		)
        SCREAMING_SNAKE_CASE :      Dict       =   ["""#version: 0.2""", """\u0120 l""", """\u0120l o""", """\u0120lo w""", """e r""", """"""]
        SCREAMING_SNAKE_CASE :      List[Any]       =   {"""unk_token""": """<unk>"""}

        SCREAMING_SNAKE_CASE :      int       =   os.path.join(self.tmpdirname				,				"""bart_tokenizer"""		)
        os.makedirs(UpperCAmelCase__				,				exist_ok=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   os.path.join(UpperCAmelCase__				,				BART_VOCAB_FILES_NAMES["""vocab_file"""]		)
        SCREAMING_SNAKE_CASE :      Optional[int]       =   os.path.join(UpperCAmelCase__				,				BART_VOCAB_FILES_NAMES["""merges_file"""]		)
        with open(self.vocab_file				,				"""w"""				,				encoding="""utf-8"""		) as fp:
              fp.write(json.dumps(UpperCAmelCase__		) + """\n"""		)
        with open(self.merges_file				,				"""w"""				,				encoding="""utf-8"""		) as fp:
              fp.write("""\n""".join(UpperCAmelCase__		)		)


  def  _lowercase      (			self    : Optional[Any]		)					->DPRQuestionEncoderTokenizer:
        """simple docstring"""







        return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname				,				"""dpr_tokenizer"""		)		)


  def  _lowercase      (			self    : Optional[Any]		)					->DPRContextEncoderTokenizer:
        """simple docstring"""







        return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname				,				"""dpr_tokenizer"""		)		)


  def  _lowercase      (			self    : Optional[int]		)					->BartTokenizer:
        """simple docstring"""







        return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname				,				"""bart_tokenizer"""		)		)


  def  _lowercase      (			self    : Any		)					->List[str]:
        """simple docstring"""







        shutil.rmtree(self.tmpdirname		)


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







        SCREAMING_SNAKE_CASE :      str       =   Dataset.from_dict(
            {
                """id""": ["""0""", """1"""],
                """text""": ["""foo""", """bar"""],
                """title""": ["""Foo""", """Bar"""],
                """embeddings""": [np.ones(self.retrieval_vector_size		), 2 * np.ones(self.retrieval_vector_size		)],
            }		)
        dataset.add_faiss_index("""embeddings"""				,				string_factory="""Flat"""				,				metric_type=faiss.METRIC_INNER_PRODUCT		)
        return dataset


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







        SCREAMING_SNAKE_CASE :      int       =   self.get_dummy_dataset()
        SCREAMING_SNAKE_CASE :      str       =   RagConfig(
            retrieval_vector_size=self.retrieval_vector_size				,				question_encoder=DPRConfig().to_dict()				,				generator=BartConfig().to_dict()				,				)
        with patch("""transformers.models.rag.retrieval_rag.load_dataset"""		) as mock_load_dataset:
              SCREAMING_SNAKE_CASE :      Tuple       =   dataset
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   RagRetriever(
                  UpperCAmelCase__				,				question_encoder_tokenizer=self.get_dpr_tokenizer()				,				generator_tokenizer=self.get_bart_tokenizer()				,				)
        return retriever


  def  _lowercase      (			self    : List[Any]				,				UpperCAmelCase__    : bool		)					->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   self.get_dummy_dataset()
        SCREAMING_SNAKE_CASE :      Dict       =   RagConfig(
            retrieval_vector_size=self.retrieval_vector_size				,				question_encoder=DPRConfig().to_dict()				,				generator=BartConfig().to_dict()				,				index_name="""custom"""				,				)
        if from_disk:
              SCREAMING_SNAKE_CASE :      List[str]       =   os.path.join(self.tmpdirname				,				"""dataset"""		)
              SCREAMING_SNAKE_CASE :      Any       =   os.path.join(self.tmpdirname				,				"""index.faiss"""		)
              dataset.get_index("""embeddings"""		).save(os.path.join(self.tmpdirname				,				"""index.faiss"""		)		)
              dataset.drop_index("""embeddings"""		)
              dataset.save_to_disk(os.path.join(self.tmpdirname				,				"""dataset"""		)		)
              del dataset
              SCREAMING_SNAKE_CASE :      Any       =   RagRetriever(
                  UpperCAmelCase__				,				question_encoder_tokenizer=self.get_dpr_tokenizer()				,				generator_tokenizer=self.get_bart_tokenizer()				,				)
        else:
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   RagRetriever(
                  UpperCAmelCase__				,				question_encoder_tokenizer=self.get_dpr_tokenizer()				,				generator_tokenizer=self.get_bart_tokenizer()				,				index=CustomHFIndex(config.retrieval_vector_size				,				UpperCAmelCase__		)				,				)
        return retriever


  def  _lowercase      (			self    : int		)					->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[Any]       =   Dataset.from_dict(
            {
                """id""": ["""0""", """1"""],
                """text""": ["""foo""", """bar"""],
                """title""": ["""Foo""", """Bar"""],
                """embeddings""": [np.ones(self.retrieval_vector_size + 1		), 2 * np.ones(self.retrieval_vector_size + 1		)],
            }		)
        dataset.add_faiss_index("""embeddings"""				,				string_factory="""Flat"""				,				metric_type=faiss.METRIC_INNER_PRODUCT		)

        SCREAMING_SNAKE_CASE :      Any       =   os.path.join(self.tmpdirname				,				"""hf_bert_base.hnswSQ8_correct_phi_128.c_index"""		)
        dataset.save_faiss_index("""embeddings"""				,				index_file_name + """.index.dpr"""		)
        pickle.dump(dataset["""id"""]				,				open(index_file_name + """.index_meta.dpr"""				,				"""wb"""		)		)

        SCREAMING_SNAKE_CASE :      Optional[Any]       =   os.path.join(self.tmpdirname				,				"""psgs_w100.tsv.pkl"""		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   {sample["""id"""]: [sample["""text"""], sample["""title"""]] for sample in dataset}
        pickle.dump(UpperCAmelCase__				,				open(UpperCAmelCase__				,				"""wb"""		)		)

        SCREAMING_SNAKE_CASE :      str       =   RagConfig(
            retrieval_vector_size=self.retrieval_vector_size				,				question_encoder=DPRConfig().to_dict()				,				generator=BartConfig().to_dict()				,				index_name="""legacy"""				,				index_path=self.tmpdirname				,				)
        SCREAMING_SNAKE_CASE :      Any       =   RagRetriever(
            UpperCAmelCase__				,				question_encoder_tokenizer=self.get_dpr_tokenizer()				,				generator_tokenizer=self.get_bart_tokenizer()		)
        return retriever


  def  _lowercase      (			self    : Dict		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   1
        SCREAMING_SNAKE_CASE :      str       =   self.get_dummy_canonical_hf_index_retriever()
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Union[str, Any]       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=UpperCAmelCase__		)
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertEqual(len(UpperCAmelCase__		)				,				2		)
        self.assertEqual(sorted(doc_dicts[0]		)				,				["""embeddings""", """id""", """text""", """title"""]		)
        self.assertEqual(len(doc_dicts[0]["""id"""]		)				,				UpperCAmelCase__		)
        self.assertEqual(doc_dicts[0]["""id"""][0]				,				"""1"""		)  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["""id"""][0]				,				"""0"""		)  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist()				,				[[1], [0]]		)


  def  _lowercase      (			self    : List[str]		)					->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.get_dummy_canonical_hf_index_retriever()
        with tempfile.TemporaryDirectory() as tmp_dirname:
              with patch("""transformers.models.rag.retrieval_rag.load_dataset"""		) as mock_load_dataset:
                    SCREAMING_SNAKE_CASE :      Optional[int]       =   self.get_dummy_dataset()
                    retriever.save_pretrained(UpperCAmelCase__		)
                    SCREAMING_SNAKE_CASE :      List[Any]       =   RagRetriever.from_pretrained(UpperCAmelCase__		)
                    self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
                    SCREAMING_SNAKE_CASE :      Union[str, Any]       =   np.array(
                        [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
                    SCREAMING_SNAKE_CASE :      Dict       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=1		)
                    self.assertTrue(out is not None		)


  def  _lowercase      (			self    : List[Any]		)					->List[str]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   1
        SCREAMING_SNAKE_CASE :      str       =   self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      str       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      List[str]       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=UpperCAmelCase__		)
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertEqual(len(UpperCAmelCase__		)				,				2		)
        self.assertEqual(sorted(doc_dicts[0]		)				,				["""embeddings""", """id""", """text""", """title"""]		)
        self.assertEqual(len(doc_dicts[0]["""id"""]		)				,				UpperCAmelCase__		)
        self.assertEqual(doc_dicts[0]["""id"""][0]				,				"""1"""		)  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["""id"""][0]				,				"""0"""		)  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist()				,				[[1], [0]]		)


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







        SCREAMING_SNAKE_CASE :      List[str]       =   self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__		)
        with tempfile.TemporaryDirectory() as tmp_dirname:
              retriever.save_pretrained(UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   RagRetriever.from_pretrained(UpperCAmelCase__		)
              self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   np.array(
                  [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
              SCREAMING_SNAKE_CASE :      int       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=1		)
              self.assertTrue(out is not None		)


  def  _lowercase      (			self    : Dict		)					->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   1
        SCREAMING_SNAKE_CASE :      List[str]       =   self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      List[Any]       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=UpperCAmelCase__		)
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertEqual(len(UpperCAmelCase__		)				,				2		)
        self.assertEqual(sorted(doc_dicts[0]		)				,				["""embeddings""", """id""", """text""", """title"""]		)
        self.assertEqual(len(doc_dicts[0]["""id"""]		)				,				UpperCAmelCase__		)
        self.assertEqual(doc_dicts[0]["""id"""][0]				,				"""1"""		)  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["""id"""][0]				,				"""0"""		)  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist()				,				[[1], [0]]		)


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







        SCREAMING_SNAKE_CASE :      Dict       =   self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__		)
        with tempfile.TemporaryDirectory() as tmp_dirname:
              retriever.save_pretrained(UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      str       =   RagRetriever.from_pretrained(UpperCAmelCase__		)
              self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Optional[int]       =   np.array(
                  [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=1		)
              self.assertTrue(out is not None		)


  def  _lowercase      (			self    : Tuple		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Tuple       =   1
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.get_dummy_legacy_index_retriever()
        SCREAMING_SNAKE_CASE :      int       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      List[Any]       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=UpperCAmelCase__		)
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertEqual(len(UpperCAmelCase__		)				,				2		)
        self.assertEqual(sorted(doc_dicts[0]		)				,				["""text""", """title"""]		)
        self.assertEqual(len(doc_dicts[0]["""text"""]		)				,				UpperCAmelCase__		)
        self.assertEqual(doc_dicts[0]["""text"""][0]				,				"""bar"""		)  # max inner product is reached with second doc
        self.assertEqual(doc_dicts[1]["""text"""][0]				,				"""foo"""		)  # max inner product is reached with first doc
        self.assertListEqual(doc_ids.tolist()				,				[[1], [0]]		)


  def  _lowercase      (			self    : Any		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.get_dummy_legacy_index_retriever()
        with tempfile.TemporaryDirectory() as tmp_dirname:
              retriever.save_pretrained(UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   RagRetriever.from_pretrained(UpperCAmelCase__		)
              self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      str       =   np.array(
                  [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
              SCREAMING_SNAKE_CASE :      Dict       =   retriever.retrieve(UpperCAmelCase__				,				n_docs=1		)
              self.assertTrue(out is not None		)


  @require_torch
  @require_tokenizers
  @require_sentencepiece
  def  _lowercase      (			self    : Tuple		)					->Tuple:
        """simple docstring"""







        import torch

        SCREAMING_SNAKE_CASE :      int       =   1
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.get_dummy_canonical_hf_index_retriever()
        SCREAMING_SNAKE_CASE :      str       =   [[5, 7], [1_0, 1_1]]
        SCREAMING_SNAKE_CASE :      Tuple       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE :      int       =   retriever(UpperCAmelCase__				,				UpperCAmelCase__				,				prefix=retriever.config.generator.prefix				,				n_docs=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      List[Any]       =   (
            out["""context_input_ids"""],
            out["""context_attention_mask"""],
            out["""retrieved_doc_embeds"""],
        )
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
        self.assertIsInstance(UpperCAmelCase__				,				UpperCAmelCase__		)
        self.assertIsInstance(UpperCAmelCase__				,				np.ndarray		)

        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   retriever(
            UpperCAmelCase__				,				UpperCAmelCase__				,				prefix=retriever.config.generator.prefix				,				n_docs=UpperCAmelCase__				,				return_tensors="""pt"""				,				)
        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Union[str, Any]       =   (  # noqa: F841
            out["""context_input_ids"""],
            out["""context_attention_mask"""],
            out["""retrieved_doc_embeds"""],
            out["""doc_ids"""],
        )
        self.assertEqual(retrieved_doc_embeds.shape				,				(2, n_docs, self.retrieval_vector_size)		)
        self.assertIsInstance(UpperCAmelCase__				,				torch.Tensor		)
        self.assertIsInstance(UpperCAmelCase__				,				torch.Tensor		)
        self.assertIsInstance(UpperCAmelCase__				,				torch.Tensor		)




  @require_torch
  @require_tokenizers
  @require_sentencepiece
  def  _lowercase      (			self    : Union[str, Any]		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Dict       =   self.get_dpr_ctx_encoder_tokenizer()
        SCREAMING_SNAKE_CASE :      Optional[int]       =   1
        SCREAMING_SNAKE_CASE :      List[Any]       =   self.get_dummy_custom_hf_index_retriever(from_disk=UpperCAmelCase__		)
        retriever.set_ctx_encoder_tokenizer(UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      List[str]       =   [[5, 7], [1_0, 1_1]]
        SCREAMING_SNAKE_CASE :      Optional[int]       =   np.array(
            [np.ones(self.retrieval_vector_size		), -np.ones(self.retrieval_vector_size		)]				,				dtype=np.floataa		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   retriever(UpperCAmelCase__				,				UpperCAmelCase__				,				prefix=retriever.config.generator.prefix				,				n_docs=UpperCAmelCase__		)

        self.assertEqual(
            len(UpperCAmelCase__		)				,				6		)  # check whether the retriever output consist of 6 attributes including tokenized docs
        self.assertEqual(
            all(k in out for k in ("""tokenized_doc_ids""", """tokenized_doc_attention_mask""")		)				,				UpperCAmelCase__		)  # check for doc token related keys in dictionary.




