"""simple docstring"""







import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


__SCREAMING_SNAKE_CASE								=logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE								={"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}

__SCREAMING_SNAKE_CASE								={
    "vocab_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/vocab.txt",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/vocab.txt",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt"
        ),
        "bert-base-multilingual-cased": "https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt",
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt"
        ),
        "bert-base-german-dbmdz-cased": "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt",
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt"
        ),
    },
    "tokenizer_file": {
        "bert-base-uncased": "https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json",
        "bert-large-uncased": "https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json",
        "bert-base-cased": "https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json",
        "bert-large-cased": "https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json",
        "bert-base-multilingual-uncased": (
            "https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json"
        ),
        "bert-base-multilingual-cased": (
            "https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-chinese": "https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json",
        "bert-base-german-cased": "https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json",
        "bert-large-uncased-whole-word-masking": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking": (
            "https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json"
        ),
        "bert-large-uncased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-large-cased-whole-word-masking-finetuned-squad": (
            "https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json"
        ),
        "bert-base-cased-finetuned-mrpc": (
            "https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-cased": (
            "https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json"
        ),
        "bert-base-german-dbmdz-uncased": (
            "https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-cased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json"
        ),
        "TurkuNLP/bert-base-finnish-uncased-v1": (
            "https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json"
        ),
        "wietsedv/bert-base-dutch-cased": (
            "https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json"
        ),
    },
}

__SCREAMING_SNAKE_CASE								={
    "bert-base-uncased": 512,
    "bert-large-uncased": 512,
    "bert-base-cased": 512,
    "bert-large-cased": 512,
    "bert-base-multilingual-uncased": 512,
    "bert-base-multilingual-cased": 512,
    "bert-base-chinese": 512,
    "bert-base-german-cased": 512,
    "bert-large-uncased-whole-word-masking": 512,
    "bert-large-cased-whole-word-masking": 512,
    "bert-large-uncased-whole-word-masking-finetuned-squad": 512,
    "bert-large-cased-whole-word-masking-finetuned-squad": 512,
    "bert-base-cased-finetuned-mrpc": 512,
    "bert-base-german-dbmdz-cased": 512,
    "bert-base-german-dbmdz-uncased": 512,
    "TurkuNLP/bert-base-finnish-cased-v1": 512,
    "TurkuNLP/bert-base-finnish-uncased-v1": 512,
    "wietsedv/bert-base-dutch-cased": 512,
}

__SCREAMING_SNAKE_CASE								={
    "bert-base-uncased": {"do_lower_case": True},
    "bert-large-uncased": {"do_lower_case": True},
    "bert-base-cased": {"do_lower_case": False},
    "bert-large-cased": {"do_lower_case": False},
    "bert-base-multilingual-uncased": {"do_lower_case": True},
    "bert-base-multilingual-cased": {"do_lower_case": False},
    "bert-base-chinese": {"do_lower_case": False},
    "bert-base-german-cased": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking": {"do_lower_case": False},
    "bert-large-uncased-whole-word-masking-finetuned-squad": {"do_lower_case": True},
    "bert-large-cased-whole-word-masking-finetuned-squad": {"do_lower_case": False},
    "bert-base-cased-finetuned-mrpc": {"do_lower_case": False},
    "bert-base-german-dbmdz-cased": {"do_lower_case": False},
    "bert-base-german-dbmdz-uncased": {"do_lower_case": True},
    "TurkuNLP/bert-base-finnish-cased-v1": {"do_lower_case": False},
    "TurkuNLP/bert-base-finnish-uncased-v1": {"do_lower_case": True},
    "wietsedv/bert-base-dutch-cased": {"do_lower_case": False},
}







class  UpperCamelCase	(    lowercase_						):
   lowercase							=						VOCAB_FILES_NAMES
   lowercase							=						PRETRAINED_VOCAB_FILES_MAP
   lowercase							=						PRETRAINED_INIT_CONFIGURATION
   lowercase							=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   lowercase							=						BertTokenizer
   def __init__(    self  ,__UpperCamelCase=None  ,__UpperCamelCase=None  ,__UpperCamelCase=True  ,__UpperCamelCase="[UNK]"  ,__UpperCamelCase="[SEP]"  ,__UpperCamelCase="[PAD]"  ,__UpperCamelCase="[CLS]"  ,__UpperCamelCase="[MASK]"  ,__UpperCamelCase=True  ,__UpperCamelCase=None  ,**__UpperCamelCase  ,)			->   List[Any]:


        '''simple docstring'''


        super().__init__(
            __UpperCamelCase  ,tokenizer_file=__UpperCamelCase  ,do_lower_case=__UpperCamelCase  ,unk_token=__UpperCamelCase  ,sep_token=__UpperCamelCase  ,pad_token=__UpperCamelCase  ,cls_token=__UpperCamelCase  ,mask_token=__UpperCamelCase  ,tokenize_chinese_chars=__UpperCamelCase  ,strip_accents=__UpperCamelCase  ,**__UpperCamelCase  ,)

        lowercase_			:       int									=			json.loads(self.backend_tokenizer.normalizer.__getstate__()    )
        if (
            normalizer_state.get('lowercase'  ,__UpperCamelCase    ) != do_lower_case
            or normalizer_state.get('strip_accents'  ,__UpperCamelCase    ) != strip_accents
            or normalizer_state.get('handle_chinese_chars'  ,__UpperCamelCase    ) != tokenize_chinese_chars
        ):
             lowercase_			:       Optional[Any]									=			getattr(__UpperCamelCase  ,normalizer_state.pop('type'    )    )
             lowercase_			:       Union[str, Any]									=			do_lower_case
             lowercase_			:       Optional[int]									=			strip_accents
             lowercase_			:       str									=			tokenize_chinese_chars
             lowercase_			:       Any									=			normalizer_class(**__UpperCamelCase    )

        lowercase_			:       int									=			do_lower_case
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase=None    )			->   str:


        '''simple docstring'''


        lowercase_			:       int									=			[self.cls_token_id] + token_ids_a + [self.sep_token_id]

        if token_ids_a:
             output += token_ids_a + [self.sep_token_id]

        return output
   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = None    )			->   List[int]:


        '''simple docstring'''


        lowercase_			:       str									=			[self.sep_token_id]
        lowercase_			:       Any									=			[self.cls_token_id]
        if token_ids_a is None:
             return len(cls + token_ids_a + sep    ) * [0]
        return len(cls + token_ids_a + sep    ) * [0] + len(token_ids_a + sep    ) * [1]







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase  ,__UpperCamelCase = None    )			->   Tuple[str]:


        '''simple docstring'''


        lowercase_			:       Union[str, Any]									=			self._tokenizer.model.save(__UpperCamelCase  ,name=__UpperCamelCase    )
        return tuple(__UpperCamelCase    )


"""simple docstring"""







import os
import unittest
from tempfile import TemporaryDirectory

import torch
import torch.nn as nn

from accelerate.utils import (
    OffloadedWeightsLoader,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
)







class  UpperCamelCase	(    nn.Module						):
   def __init__(    self    )			->   Any:


        '''simple docstring'''


        super().__init__()
        lowercase_			:       Dict									=			nn.Linear(3  ,4    )
        lowercase_			:       Union[str, Any]									=			nn.BatchNormad(4    )
        lowercase_			:       Union[str, Any]									=			nn.Linear(4  ,5    )







   def     _UpperCAmelCase     (    self  ,__UpperCamelCase    )			->   int:


        '''simple docstring'''


        return self.lineara(self.batchnorm(self.lineara(__UpperCamelCase    )    )    )







class  UpperCamelCase	(    unittest.TestCase						):
   def     _UpperCAmelCase     (    self    )			->   Dict:


        '''simple docstring'''


        lowercase_			:       int									=			ModelForTest()
        with TemporaryDirectory() as tmp_dir:
             offload_state_dict(__UpperCamelCase  ,model.state_dict()    )
             lowercase_			:       str									=			os.path.join(__UpperCamelCase  ,'index.json'    )
             self.assertTrue(os.path.isfile(__UpperCamelCase    )    )
             # TODO: add tests on what is inside the index

             for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]:
                  lowercase_			:       int									=			os.path.join(__UpperCamelCase  ,f'''{key}.dat'''    )
                  self.assertTrue(os.path.isfile(__UpperCamelCase    )    )
                  # TODO: add tests on the fact weights are properly loaded
   def     _UpperCAmelCase     (    self    )			->   Tuple:


        '''simple docstring'''


        lowercase_			:       List[str]									=			[torch.floataa, torch.floataa, torch.bfloataa]

        for dtype in dtypes:
             lowercase_			:       Tuple									=			torch.randn(2  ,3  ,dtype=__UpperCamelCase    )
             with TemporaryDirectory() as tmp_dir:
                  lowercase_			:       List[str]									=			offload_weight(__UpperCamelCase  ,'weight'  ,__UpperCamelCase  ,{}    )
                  lowercase_			:       str									=			os.path.join(__UpperCamelCase  ,'weight.dat'    )
                  self.assertTrue(os.path.isfile(__UpperCamelCase    )    )
                  self.assertDictEqual(__UpperCamelCase  ,{'weight': {'shape': [2, 3], 'dtype': str(__UpperCamelCase    ).split('.'    )[1]}}    )

                  lowercase_			:       Optional[Any]									=			load_offloaded_weight(__UpperCamelCase  ,index['weight']    )
                  self.assertTrue(torch.equal(__UpperCamelCase  ,__UpperCamelCase    )    )
   def     _UpperCAmelCase     (    self    )			->   List[Any]:


        '''simple docstring'''


        lowercase_			:       List[str]									=			ModelForTest()
        lowercase_			:       Optional[int]									=			model.state_dict()
        lowercase_			:       int									=			{k: v for k, v in state_dict.items() if 'linear2' not in k}
        lowercase_			:       Optional[Any]									=			{k: v for k, v in state_dict.items() if 'linear2' in k}

        with TemporaryDirectory() as tmp_dir:
             offload_state_dict(__UpperCamelCase  ,__UpperCamelCase    )
             lowercase_			:       Tuple									=			OffloadedWeightsLoader(state_dict=__UpperCamelCase  ,save_folder=__UpperCamelCase    )

             # Every key is there with the right value
             self.assertEqual(sorted(__UpperCamelCase    )  ,sorted(state_dict.keys()    )    )
             for key, param in state_dict.items():
                  self.assertTrue(torch.allclose(__UpperCamelCase  ,weight_map[key]    )    )

        lowercase_			:       int									=			{k: v for k, v in state_dict.items() if 'weight' in k}
        lowercase_			:       int									=			{k: v for k, v in state_dict.items() if 'weight' not in k}

        with TemporaryDirectory() as tmp_dir:
             offload_state_dict(__UpperCamelCase  ,__UpperCamelCase    )
             lowercase_			:       int									=			OffloadedWeightsLoader(state_dict=__UpperCamelCase  ,save_folder=__UpperCamelCase    )

             # Every key is there with the right value
             self.assertEqual(sorted(__UpperCamelCase    )  ,sorted(state_dict.keys()    )    )
             for key, param in state_dict.items():
                  self.assertTrue(torch.allclose(__UpperCamelCase  ,weight_map[key]    )    )

        with TemporaryDirectory() as tmp_dir:
             offload_state_dict(__UpperCamelCase  ,__UpperCamelCase    )
             # Duplicates are removed
             lowercase_			:       Tuple									=			OffloadedWeightsLoader(state_dict=__UpperCamelCase  ,save_folder=__UpperCamelCase    )

             # Every key is there with the right value
             self.assertEqual(sorted(__UpperCamelCase    )  ,sorted(state_dict.keys()    )    )
             for key, param in state_dict.items():
                  self.assertTrue(torch.allclose(__UpperCamelCase  ,weight_map[key]    )    )







   def     _UpperCAmelCase     (    self    )			->   Union[str, Any]:


        '''simple docstring'''


        lowercase_			:       Optional[int]									=			{'a.1': 0, 'a.10': 1, 'a.2': 2}
        lowercase_			:       int									=			extract_submodules_state_dict(__UpperCamelCase  ,['a.1', 'a.2']    )
        self.assertDictEqual(__UpperCamelCase  ,{'a.1': 0, 'a.2': 2}    )

        lowercase_			:       Union[str, Any]									=			{'a.1.a': 0, 'a.10.a': 1, 'a.2.a': 2}
        lowercase_			:       Optional[int]									=			extract_submodules_state_dict(__UpperCamelCase  ,['a.1', 'a.2']    )
        self.assertDictEqual(__UpperCamelCase  ,{'a.1.a': 0, 'a.2.a': 2}    )

