
import collections
import os
from typing import List, Optional, Tuple

from transformers.utils import is_jieba_available, requires_backends


if is_jieba_available():
		import jieba

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase						:      str									= logging.get_logger(__name__)

lowercase						:      str									= {'vocab_file': 'vocab.txt'}

lowercase						:      Optional[int]									= {
    'vocab_file': {
        'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt',
    },
}

lowercase						:      str									= {
    'openbmb/cpm-ant-10b': 1024,
}




def 			_SCREAMING_SNAKE_CASE      (	_lowerCamelCase				:    int)      ->					Optional[Any]:






							'''simple docstring'''





							__UpperCamelCase			:     Tuple         =      collections.OrderedDict()
							with open(_lowerCamelCase		,						"r"		,						encoding="utf-8") as reader:
														__UpperCamelCase			:     Optional[Any]         =      reader.readlines()
							for index, token in enumerate(_lowerCamelCase):
														__UpperCamelCase			:     Any         =      token.rstrip("\n")
														__UpperCamelCase			:     List[str]         =      index
							return vocab




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	def __init__(      self	:Optional[Any]  ,     a	:Tuple  ,     a	:Dict="<unk>"  ,     a	:Union[str, Any]=2_0_0		)	->				Union[str, Any]:
								__UpperCamelCase			:     List[Any]         =      vocab
								__UpperCamelCase			:     Any         =      unk_token
								__UpperCamelCase			:     int         =      max_input_chars_per_word







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:Union[str, Any]		)	->				str:
								__UpperCamelCase			:     List[Any]         =      list(a		)
								if len(a		) > self.max_input_chars_per_word:
															return [self.unk_token]

								__UpperCamelCase			:     Tuple         =      0
								__UpperCamelCase			:     Any         =      []
								while start < len(a		):
															__UpperCamelCase			:     Optional[Any]         =      len(a		)
															__UpperCamelCase			:     Tuple         =      None
															while start < end:
																						__UpperCamelCase			:     Dict         =      "".join(chars[start:end]		)
																						if substr in self.vocab:
																													__UpperCamelCase			:     Optional[int]         =      substr
																													break
																						end -= 1
															if cur_substr is None:
																						sub_tokens.append(self.unk_token		)
																						start += 1
															else:
																						sub_tokens.append(a		)
																						__UpperCamelCase			:     int         =      end

								return sub_tokens




class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  VOCAB_FILES_NAMES
	_A			=  PRETRAINED_VOCAB_FILES_MAP
	_A			=  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_A			=  ['input_ids', 'attention_mask']
	_A			=  False







	def __init__(      self	:Optional[Any]  ,     a	:Union[str, Any]  ,     a	:str="<d>"  ,     a	:Union[str, Any]="</d>"  ,     a	:List[Any]="<s>"  ,     a	:List[Any]="</s>"  ,     a	:Dict="<pad>"  ,     a	:List[str]="<unk>"  ,     a	:int="</n>"  ,     a	:List[Any]="</_>"  ,     a	:Union[str, Any]="left"  ,     **a	:Tuple  ,     )	->				Optional[Any]:
								requires_backends(self  ,     ["jieba"]		)
								super().__init__(
								    bod_token=a  ,     eod_token=a  ,     bos_token=a  ,     eos_token=a  ,     pad_token=a  ,     unk_token=a  ,     line_token=a  ,     space_token=a  ,     padding_side=a  ,     **a  ,     )
								__UpperCamelCase			:     Union[str, Any]         =      bod_token
								__UpperCamelCase			:     int         =      eod_token
								__UpperCamelCase			:     Union[str, Any]         =      load_vocab(a		)
								__UpperCamelCase			:     Optional[Any]         =      self.encoder[space_token]
								__UpperCamelCase			:     int         =      self.encoder[line_token]

								del self.encoder[space_token]
								del self.encoder[line_token]

								__UpperCamelCase			:     Optional[Any]         =      collections.OrderedDict(sorted(self.encoder.items()  ,     key=lambda a		: x[1]		)		)
								__UpperCamelCase			:     str         =      {v: k for k, v in self.encoder.items()}

								__UpperCamelCase			:     str         =      WordpieceTokenizer(vocab=self.encoder  ,     unk_token=self.unk_token		)







	@property
	def      _lowerCamelCase       (      self	:int		)	->				str:
								return self.encoder[self.bod_token]







	@property
	def      _lowerCamelCase       (      self	:List[Any]		)	->				Union[str, Any]:
								return self.encoder[self.eod_token]







	@property
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				Any:
								return self.encoder["\n"]







	@property
	def      _lowerCamelCase       (      self	:Union[str, Any]		)	->				int:
								return len(self.encoder		)







	def      _lowerCamelCase       (      self	:Tuple		)	->				List[Any]:
								return dict(self.encoder  ,     **self.added_tokens_encoder		)







	def      _lowerCamelCase       (      self	:str  ,     a	:List[str]		)	->				Any:
								__UpperCamelCase			:     Any         =      []
								for x in jieba.cut(a  ,     cut_all=a		):
															output_tokens.extend(self.wordpiece_tokenizer.tokenize(a		)		)
								return output_tokens







	def      _lowerCamelCase       (      self	:List[Any]  ,     a	:Dict  ,     **a	:int		)	->				List[str]:
								__UpperCamelCase			:     Tuple         =      [i for i in token_ids if i >= 0]
								__UpperCamelCase			:     int         =      [
								    x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id
								]
								return super()._decode(a  ,     **a		)







	def      _lowerCamelCase       (      self	:str  ,     a	:List[str]		)	->				Any:
								return token in self.encoder







	def      _lowerCamelCase       (      self	:Optional[Any]  ,     a	:List[str]		)	->				str:
								return "".join(a		)







	def      _lowerCamelCase       (      self	:Optional[Any]  ,     a	:str		)	->				str:
								return self.encoder.get(a  ,     self.encoder.get(self.unk_token		)		)







	def      _lowerCamelCase       (      self	:Optional[Any]  ,     a	:str		)	->				Union[str, Any]:
								return self.decoder.get(a  ,     self.unk_token		)







	def      _lowerCamelCase       (      self	:Tuple  ,     a	:str  ,     a	:Optional[str] = None		)	->				Tuple[str]:
								if os.path.isdir(a		):
															__UpperCamelCase			:     Union[str, Any]         =      os.path.join(
															    a  ,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]		)
								else:
															__UpperCamelCase			:     Union[str, Any]         =      (filename_prefix + "-" if filename_prefix else "") + save_directory
								__UpperCamelCase			:     Dict         =      0
								if " " in self.encoder:
															__UpperCamelCase			:     int         =      self.encoder[" "]
															del self.encoder[" "]
								if "\n" in self.encoder:
															__UpperCamelCase			:     List[Any]         =      self.encoder["\n"]
															del self.encoder["\n"]
								__UpperCamelCase			:     Dict         =      collections.OrderedDict(sorted(self.encoder.items()  ,     key=lambda a		: x[1]		)		)
								with open(a  ,     "w"  ,     encoding="utf-8"		) as writer:
															for token, token_index in self.encoder.items():
																						if index != token_index:
																													logger.warning(
																													    f'Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'
																													    " Please check that the vocabulary is not corrupted!"		)
																													__UpperCamelCase			:     Dict         =      token_index
																						writer.write(token + "\n"		)
																						index += 1
								return (vocab_file,)







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:List[int]  ,     a	:List[int] = None		)	->				List[int]:
								if token_ids_a is None:
															return [self.bos_token_id] + token_ids_a
								return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a







	def      _lowerCamelCase       (      self	:Optional[Any]  ,     a	:List[int]  ,     a	:Optional[List[int]] = None  ,     a	:bool = False		)	->				List[int]:

								if already_has_special_tokens:
															return super().get_special_tokens_mask(
															    token_ids_a=a  ,     token_ids_a=a  ,     already_has_special_tokens=a		)

								if token_ids_a is not None:
															return [1] + ([0] * len(a		)) + [1] + ([0] * len(a		))
								return [1] + ([0] * len(a		))

from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
		from .deepspeed import (
		    DeepSpeedEngineWrapper,
		    DeepSpeedOptimizerWrapper,
		    DeepSpeedSchedulerWrapper,
		    DummyOptim,
		    DummyScheduler,
		    HfDeepSpeedConfig,
		)

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers