

from arguments import TokenizerTrainingArguments
from datasets import load_dataset
from tqdm import tqdm

from transformers import AutoTokenizer, HfArgumentParser
from transformers.models.gpta.tokenization_gpta import bytes_to_unicode
def   _lowerCAmelCase(						__A=10      ):
  for _ in tqdm(range(0 ,							args.n_examples ,							__A      )      ):
    yield [next(__A      )[args.text_column] for _ in range(__A      )]


# Configuration
lowerCAmelCase__							=			HfArgumentParser(TokenizerTrainingArguments)
lowerCAmelCase__							=			parser.parse_args()

# Base tokenizer
lowerCAmelCase__							=			AutoTokenizer.from_pretrained(args.base_tokenizer)
lowerCAmelCase__							=			list(bytes_to_unicode().values())

# Load dataset
lowerCAmelCase__							=			load_dataset(args.dataset_name, split="train", streaming=True)
lowerCAmelCase__							=			iter(dataset)


# Training and saving
lowerCAmelCase__							=			tokenizer.train_new_from_iterator(
    batch_iterator(), vocab_size=args.vocab_size, initial_alphabet=base_vocab
)





new_tokenizer.save_pretrained(args.tokenizer_name, push_to_hub=args.push_to_hub)






import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available
def   _lowerCAmelCase(						__A ,							__A ,							__A ,							__A=None      ):
  UpperCAmelCase          =	None
  # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
  if str(weight.dtype      ) == "torch.bfloat16":
    # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
    UpperCAmelCase          =	weight.view(torch.intaa      )
    UpperCAmelCase          =	"bfloat16"
  UpperCAmelCase          =	weight.cpu().numpy()
  UpperCAmelCase          =	os.path.join(__A ,							F"{weight_name}.dat"      )
  if index is not None:
    if dtype is None:
      UpperCAmelCase          =	str(array.dtype      )
    UpperCAmelCase          =	{"dtype": dtype, "shape": list(array.shape      )}
  if array.ndim == 0:
    UpperCAmelCase          =	array[None]
  UpperCAmelCase          =	np.memmap(__A ,							dtype=array.dtype ,							mode="w+" ,							shape=array.shape      )
  UpperCAmelCase          =	array[:]
  file_array.flush()
  return index
def   _lowerCAmelCase(						__A ,							__A      ):
  UpperCAmelCase          =	tuple(weight_info["shape"]      )
  if shape == ():
    # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
    UpperCAmelCase          =	(1,)

  UpperCAmelCase          =	weight_info["dtype"]
  if dtype == "bfloat16":
    # NumPy does not support bfloat16 so this was saved as a int16
    UpperCAmelCase          =	"int16"

  UpperCAmelCase          =	np.memmap(__A ,							dtype=__A ,							shape=__A ,							mode="r"      )

  if len(weight_info["shape"]      ) == 0:
    UpperCAmelCase          =	weight[0]
  UpperCAmelCase          =	torch.tensor(__A      )
  if weight_info["dtype"] == "bfloat16":
    UpperCAmelCase          =	weight.view(torch.bfloataa      )

  return weight
def   _lowerCAmelCase(						__A ,							__A      ):
  if index is None or len(__A      ) == 0:
    # Nothing to save
    return

  UpperCAmelCase          =	os.path.join(__A ,							"index.json"      )
  if os.path.isfile(__A      ):
    with open(__A ,							"r" ,							encoding="utf-8"      ) as f:
      UpperCAmelCase          =	json.load(__A      )
  else:
    UpperCAmelCase          =	{}
  current_index.update(__A      )

  with open(__A ,							"w" ,							encoding="utf-8"      ) as f:
    json.dump(__A ,							__A ,							indent=2      )
def   _lowerCAmelCase(						__A ,							__A      ):
  os.makedirs(__A ,							exist_ok=__A      )
  UpperCAmelCase          =	{}
  for name, parameter in state_dict.items():
    UpperCAmelCase          =	offload_weight(__A ,							__A ,							__A ,							index=__A      )

  # Update index
  save_offload_index(__A ,							__A      )






class     __magic_name__     (							_snake_case     ):


 def __init__(    self		:			Tuple      ,    lowerCAmelCase__		:			Mapping      ,    lowerCAmelCase__		:			str     )     ->   Tuple:
   UpperCAmelCase          =	dataset
   UpperCAmelCase          =	prefix


 def __getitem__(    self		:			Dict      ,    lowerCAmelCase__		:			Any     )     ->   Optional[int]:
   return self.dataset[f"{self.prefix}{key}"]


 def __iter__(    self		:			Optional[int]     )     ->   Any:
   return iter([key for key in self.dataset if key.startswith(self.prefix     )]     )


 def __len__(    self		:			Union[str, Any]     )     ->   int:
   return len(self.dataset     )






class     __magic_name__     (							_snake_case     ):


 def __init__(    self		:			Optional[int]      ,    lowerCAmelCase__		:			Dict[str, torch.Tensor] = None      ,    lowerCAmelCase__		:			Optional[Union[str, os.PathLike]] = None      ,    lowerCAmelCase__		:			Mapping = None      ,    lowerCAmelCase__		:			Dict=None      ,    )     ->   Dict:
   if state_dict is None and save_folder is None:
     raise ValueError("Need either a `state_dict` or a `save_folder` containing offloaded weights."     )

   UpperCAmelCase          =	{} if state_dict is None else state_dict
   UpperCAmelCase          =	save_folder
   if index is None and save_folder is not None:
     with open(os.path.join(lowerCAmelCase__      ,    "index.json"     )     ) as f:
       UpperCAmelCase          =	json.load(lowerCAmelCase__     )
   UpperCAmelCase          =	{} if index is None else index
   UpperCAmelCase          =	list(self.state_dict.keys()     )
   self.all_keys.extend([key for key in self.index if key not in self.all_keys]     )
   UpperCAmelCase          =	device


 def __getitem__(    self		:			str      ,    lowerCAmelCase__		:			str     )     ->   Dict:
   # State dict gets priority
   if key in self.state_dict:
     return self.state_dict[key]
   UpperCAmelCase          =	self.index[key]
   if weight_info.get("safetensors_file"     ) is not None:
     if not is_safetensors_available():
       raise ImportError("These offloaded weights require the use of safetensors: `pip install safetensors`."     )

     from safetensors import safe_open

     UpperCAmelCase          =	"cpu" if self.device is None else self.device
     with safe_open(weight_info["safetensors_file"]      ,    framework="pt"      ,    device=lowerCAmelCase__     ) as f:
       UpperCAmelCase          =	f.get_tensor(weight_info.get("weight_name"      ,    lowerCAmelCase__     )     )

     if "dtype" in weight_info:
       return tensor.to(getattr(lowerCAmelCase__      ,    weight_info["dtype"]     )     )
     else:
       return tensor

   UpperCAmelCase          =	os.path.join(self.save_folder      ,    f"{key}.dat"     )
   return load_offloaded_weight(lowerCAmelCase__      ,    lowerCAmelCase__     )


 def __iter__(    self		:			str     )     ->   Dict:
   return iter(self.all_keys     )


 def __len__(    self		:			Optional[Any]     )     ->   List[Any]:
   return len(self.all_keys     )

def   _lowerCAmelCase(						__A ,							__A      ):
  UpperCAmelCase          =	{}
  for module_name in submodule_names:
    # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
    # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
    result.update(
        {
            key: param
            for key, param in state_dict.items()
            if key == module_name or key.startswith(module_name + "."      )
        }      )
  return result



