
'''simple docstring'''





import os
import sys
from pathlib import Path

import pytest

from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node

from .utils import execute_subprocess_async, get_torch_dist_unique_port, require_torch
def 	snake_case_							(				):
      snake_case_    							=				Dataset.from_dict({"i": range(17      )}      )
      snake_case_    							=				len(_a      )
      snake_case_    							=				3
      snake_case_    							=				[
          split_dataset_by_node(_a			,       rank=_a			,       world_size=_a      ) for rank in range(_a      )
      ]
      assert sum(len(_a      ) for ds in datasets_per_rank      ) == full_size
      assert len({tuple(x.values()      ) for ds in datasets_per_rank for x in ds}      ) == full_size
def 	snake_case_							(				):
      def gen():
            return ({"i": i} for i in range(17      ))

      snake_case_    							=				3
      snake_case_    							=				IterableDataset.from_generator(_a      )
      snake_case_    							=				len(list(_a      )      )
      snake_case_    							=				[
          split_dataset_by_node(_a			,       rank=_a			,       world_size=_a      ) for rank in range(_a      )
      ]
      assert sum(len(list(_a      )      ) for ds in datasets_per_rank      ) == full_size
      assert len({tuple(x.values()      ) for ds in datasets_per_rank for x in ds}      ) == full_size
@pytest.mark.parametrize("shards_per_node"			,       [1, 2, 3]      )
def 	snake_case_							(				_a  :				List[Any]      ):
      def gen(_a  :				Dict      ):
            for shard in shards:
                  yield from ({"i": i, "shard": shard} for i in range(17      ))

      snake_case_    							=				3
      snake_case_    							=				shards_per_node * world_size
      snake_case_    							=				{"shards": [F'''shard_{shard_idx}.txt''' for shard_idx in range(_a      )]}
      snake_case_    							=				IterableDataset.from_generator(_a			,       gen_kwargs=_a      )
      snake_case_    							=				len(list(_a      )      )
      assert full_ds.n_shards == world_size * shards_per_node
      snake_case_    							=				[
          split_dataset_by_node(_a			,       rank=_a			,       world_size=_a      ) for rank in range(_a      )
      ]
      assert [ds.n_shards for ds in datasets_per_rank] == [shards_per_node] * world_size
      assert sum(len(list(_a      )      ) for ds in datasets_per_rank      ) == full_size
      assert len({tuple(x.values()      ) for ds in datasets_per_rank for x in ds}      ) == full_size
def 	snake_case_							(				):
      def gen():
            return ({"i": i} for i in range(17      ))

      snake_case_    							=				2
      snake_case_    							=				IterableDataset.from_generator(_a      )
      snake_case_    							=				len(list(_a      )      )

      snake_case_    							=				split_dataset_by_node(_a			,       rank=0			,       world_size=_a      ).shuffle(seed=42      )
      assert len(list(_a      )      ) == 1 + full_size // world_size
      with pytest.raises(_a      ):
            split_dataset_by_node(_a			,       rank=0			,       world_size=_a      ).shuffle()

      snake_case_    							=				split_dataset_by_node(full_ds.shuffle(seed=42      )			,       rank=0			,       world_size=_a      )
      assert len(list(_a      )      ) == 1 + full_size // world_size
      with pytest.raises(_a      ):
            split_dataset_by_node(full_ds.shuffle()			,       rank=0			,       world_size=_a      )
@pytest.mark.parametrize("streaming"			,       [False, True]      )
@require_torch
@pytest.mark.skipif(os.name == "nt"			,       reason="execute_subprocess_async doesn't support windows"      )
@pytest.mark.integration
def 	snake_case_							(				_a  :				Any      ):
      snake_case_    							=				2
      snake_case_    							=				get_torch_dist_unique_port()
      snake_case_    							=				Path(_a      ).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
      snake_case_    							=				F'''
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    '''.split()
      snake_case_    							=				F'''
        --streaming={streaming}
    '''.split()
      snake_case_    							=				[sys.executable] + distributed_args + args
      execute_subprocess_async(_a			,       env=os.environ.copy()      )




@pytest.mark.parametrize(
    "nproc_per_node, num_workers"			,       [
        (2, 2),  # each node has 2 shards and each worker has 1 shards
        (3, 2),  # each node uses all the shards but skips examples, and each worker has 2 shards
    ]			,       )
@require_torch
@pytest.mark.skipif(os.name == "nt"			,       reason="execute_subprocess_async doesn't support windows"      )
@pytest.mark.integration
def 	snake_case_							(				_a  :				int			,       _a  :				List[Any]      ):
      snake_case_    							=				True
      snake_case_    							=				get_torch_dist_unique_port()
      snake_case_    							=				Path(_a      ).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
      snake_case_    							=				F'''
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    '''.split()
      snake_case_    							=				F'''
        --streaming={streaming}
        --num_workers={num_workers}
    '''.split()
      snake_case_    							=				[sys.executable] + distributed_args + args
      execute_subprocess_async(_a			,       env=os.environ.copy()      )


import os
from shutil import copyfile
from typing import TYPE_CHECKING, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
						from transformers.pipelines.conversational import Conversation

require_version("tokenizers>=0.13.3")

if is_sentencepiece_available():
						from .tokenization_llama import LlamaTokenizer
else:
						lowerCAmelCase__  	=      None

lowerCAmelCase__  	=      logging.get_logger(__name__)
lowerCAmelCase__  	=      {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}

lowerCAmelCase__	,					lowerCAmelCase__  	=      "[INST]", "[/INST]"
lowerCAmelCase__	,					lowerCAmelCase__  	=      "<<SYS>>\n", "\n<</SYS>>\n\n"

# fmt: off
lowerCAmelCase__  	=      "You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don't know the answer to a question, please don't share false information."
class 	_a  (							lowerCamelCase_					):



	"""simple docstring"""



	__SCREAMING_SNAKE_CASE              =					VOCAB_FILES_NAMES
	__SCREAMING_SNAKE_CASE              =					LlamaTokenizer
	__SCREAMING_SNAKE_CASE              =					'left'
	__SCREAMING_SNAKE_CASE              =					['input_ids', 'attention_mask']


	def __init__(   self       ,  lowerCAmelCase_=None       ,  lowerCAmelCase_=None       ,  lowerCAmelCase_=False       ,  lowerCAmelCase_="<unk>"       ,  lowerCAmelCase_="<s>"       ,  lowerCAmelCase_="</s>"       ,  lowerCAmelCase_=True       ,  lowerCAmelCase_=False       ,  **lowerCAmelCase_       ,  ):
		super().__init__(
		    vocab_file=lowerCAmelCase_       ,  tokenizer_file=lowerCAmelCase_       ,  clean_up_tokenization_spaces=lowerCAmelCase_       ,  unk_token=lowerCAmelCase_       ,  bos_token=lowerCAmelCase_       ,  eos_token=lowerCAmelCase_       ,  **lowerCAmelCase_       ,  )
		_lowercase   =add_bos_token
		_lowercase   =add_eos_token
		self.update_post_processor()

		_lowercase   =vocab_file
		_lowercase   =False if not self.vocab_file else True


	def __lowerCAmelCase      (   self       ):
		_lowercase   =self.bos_token
		_lowercase   =self.bos_token_id

		_lowercase   =self.eos_token
		_lowercase   =self.eos_token_id

		_lowercase   =F'''{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}'''
		_lowercase   =F'''{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}'''

		_lowercase   =[]
		if self.add_bos_token:
			special_tokens.append((bos, bos_token_id)       )
		if self.add_eos_token:
			special_tokens.append((eos, eos_token_id)       )
		_lowercase   =processors.TemplateProcessing(
		    single=lowerCAmelCase_       ,  pair=lowerCAmelCase_       ,  special_tokens=lowerCAmelCase_       )


	@property
	def __lowerCAmelCase      (   self       ):
		return self._add_eos_token


	@property
	def __lowerCAmelCase      (   self       ):
		return self._add_bos_token


	@add_eos_token.setter
	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_       ):
		_lowercase   =value
		self.update_post_processor()


	@add_bos_token.setter
	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_       ):
		_lowercase   =value
		self.update_post_processor()


	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_       ,  lowerCAmelCase_ = None       ):
		if not self.can_save_slow_tokenizer:
			raise ValueError(
			    "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
			    "tokenizer."       )

		if not os.path.isdir(lowerCAmelCase_       ):
			logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''       )
			return
		_lowercase   =os.path.join(
		    lowerCAmelCase_       ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]       )

		if os.path.abspath(self.vocab_file       ) != os.path.abspath(lowerCAmelCase_       ):
			copyfile(self.vocab_file       ,  lowerCAmelCase_       )

		return (out_vocab_file,)


	def __lowerCAmelCase      (   self       ,  lowerCAmelCase_       ):
		_lowercase   =list(conversation.iter_texts()       )
		if not all([is_user for is_user, msg in dialogue[::2]]       ) or not all(
		    [not is_user for is_user, msg in dialogue[1::2]]       ):
			raise ValueError(
			    "The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)"       )

		_lowercase   =[]
		if len(conversation.past_user_inputs       ) > 0:
			if not conversation.past_user_inputs[0].startswith(lowerCAmelCase_       ) or E_SYS not in conversation.past_user_inputs[0]:
				_lowercase   =(
				    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
				)
		elif not dialogue[0][1].startswith(lowerCAmelCase_       ) or E_SYS not in dialogue[0][1]:
			_lowercase   =(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

		dialog_tokens += sum(
		    [
		        [self.bos_token_id]
		        + self.encode(
		            F'''{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '''       ,  add_special_tokens=lowerCAmelCase_       )
		        + [self.eos_token_id]
		        for prompt, answer in zip(dialogue[::2]       ,  dialogue[1::2]       )
		    ]       ,  []       ,  )
		if not (dialogue[-1][0]):
			raise ValueError(F'''Last message must be from user, got {dialogue[-1]['role']}'''       )
		dialog_tokens += [self.bos_token_id] + self.encode(
		    F'''{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'''       ,  add_special_tokens=lowerCAmelCase_       )
		return dialog_tokens




