


import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding



class       UpperCAmelCase_		(							__snake_case):
       '''simple docstring'''
       __UpperCamelCase					:   Optional[int]							=    ["image_processor", "tokenizer"]
       __UpperCamelCase					:   List[Any]							=    "VideoMAEImageProcessor"
       __UpperCamelCase					:   List[str]							=    ("CLIPTokenizer", "CLIPTokenizerFast")






       def __init__(   self       ,    __SCREAMING_SNAKE_CASE=None       ,    __SCREAMING_SNAKE_CASE=None       ,    **__SCREAMING_SNAKE_CASE  ):




              """simple docstring"""




              UpperCamelCase			:		Any      		=						None
              if "feature_extractor" in kwargs:
                     warnings.warn(
                         '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
                         ''' instead.'''       ,    lowercase_       ,    )
                     UpperCamelCase			:		Union[str, Any]      		=						kwargs.pop('''feature_extractor'''  )

              UpperCamelCase			:		Optional[int]      		=						image_processor if image_processor is not None else feature_extractor
              if image_processor is None:
                     raise ValueError('''You need to specify an `image_processor`.'''  )
              if tokenizer is None:
                     raise ValueError('''You need to specify a `tokenizer`.'''  )

              super().__init__(lowercase_       ,    lowercase_  )
              UpperCamelCase			:		str      		=						self.image_processor






       def __call__(   self       ,    __SCREAMING_SNAKE_CASE=None       ,    __SCREAMING_SNAKE_CASE=None       ,    __SCREAMING_SNAKE_CASE=None       ,    **__SCREAMING_SNAKE_CASE  ):




              """simple docstring"""




              if text is None and videos is None:
                     raise ValueError('''You have to specify either text or videos. Both cannot be none.'''  )

              if text is not None:
                     UpperCamelCase			:		List[str]      		=						self.tokenizer(lowercase_       ,    return_tensors=lowercase_       ,    **lowercase_  )

              if videos is not None:
                     UpperCamelCase			:		int      		=						self.image_processor(lowercase_       ,    return_tensors=lowercase_       ,    **lowercase_  )

              if text is not None and videos is not None:
                     UpperCamelCase			:		List[Any]      		=						image_features.pixel_values
                     return encoding
              elif text is not None:
                     return encoding
              else:
                     return BatchEncoding(data=dict(**lowercase_  )       ,    tensor_type=lowercase_  )






       def        _lowercase      (   self       ,    *__SCREAMING_SNAKE_CASE       ,    **__SCREAMING_SNAKE_CASE  ):




              """simple docstring"""




              return self.tokenizer.batch_decode(*lowercase_       ,    **lowercase_  )






       def        _lowercase      (   self       ,    *__SCREAMING_SNAKE_CASE       ,    **__SCREAMING_SNAKE_CASE  ):




              """simple docstring"""




              return self.tokenizer.decode(*lowercase_       ,    **lowercase_  )






       @property
       def        _lowercase      (   self  ):




              """simple docstring"""




              return ["input_ids", "attention_mask", "position_ids", "pixel_values"]






       @property
       def        _lowercase      (   self  ):




              """simple docstring"""




              warnings.warn(
                  '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''       ,    lowercase_       ,    )
              return self.image_processor_class






       @property
       def        _lowercase      (   self  ):




              """simple docstring"""




              warnings.warn(
                  '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''       ,    lowercase_       ,    )
              return self.image_processor


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						()       ->       int:

						'''simple docstring'''



						_snake_case						:     List[Any]				=    Dataset.from_dict({"i": range(17						)}						)
						_snake_case						:     Tuple				=    len(__lowercase						)
						_snake_case						:     Any				=    3
						_snake_case						:     List[str]				=    [
						    split_dataset_by_node(__lowercase					,			rank=__lowercase					,			world_size=__lowercase						) for rank in range(__lowercase						)
						]
						assert sum(len(__lowercase						) 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						()       ->       List[Any]:

						'''simple docstring'''



						def gen():
												return ({"i": i} for i in range(17						))

						_snake_case						:     List[Any]				=    3
						_snake_case						:     Dict				=    IterableDataset.from_generator(__lowercase						)
						_snake_case						:     List[Any]				=    len(list(__lowercase						)						)
						_snake_case						:     str				=    [
						    split_dataset_by_node(__lowercase					,			rank=__lowercase					,			world_size=__lowercase						) for rank in range(__lowercase						)
						]
						assert sum(len(list(__lowercase						)						) 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						(__lowercase						)       ->       List[Any]:

						'''simple docstring'''



						def gen(__lowercase						):
												for shard in shards:
																		yield from ({"i": i, "shard": shard} for i in range(17						))

						_snake_case						:     str				=    3
						_snake_case						:     List[str]				=    shards_per_node * world_size
						_snake_case						:     List[Any]				=    {"shards": [F"""shard_{shard_idx}.txt""" for shard_idx in range(__lowercase						)]}
						_snake_case						:     Optional[int]				=    IterableDataset.from_generator(__lowercase					,			gen_kwargs=__lowercase						)
						_snake_case						:     Tuple				=    len(list(__lowercase						)						)
						assert full_ds.n_shards == world_size * shards_per_node
						_snake_case						:     List[Any]				=    [
						    split_dataset_by_node(__lowercase					,			rank=__lowercase					,			world_size=__lowercase						) for rank in range(__lowercase						)
						]
						assert [ds.n_shards for ds in datasets_per_rank] == [shards_per_node] * world_size
						assert sum(len(list(__lowercase						)						) 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						()       ->       Dict:

						'''simple docstring'''



						def gen():
												return ({"i": i} for i in range(17						))

						_snake_case						:     Dict				=    2
						_snake_case						:     str				=    IterableDataset.from_generator(__lowercase						)
						_snake_case						:     Dict				=    len(list(__lowercase						)						)

						_snake_case						:     Optional[int]				=    split_dataset_by_node(__lowercase					,			rank=0					,			world_size=__lowercase						).shuffle(seed=42						)
						assert len(list(__lowercase						)						) == 1 + full_size // world_size
						with pytest.raises(__lowercase						):
												split_dataset_by_node(__lowercase					,			rank=0					,			world_size=__lowercase						).shuffle()

						_snake_case						:     Optional[int]				=    split_dataset_by_node(full_ds.shuffle(seed=42						)					,			rank=0					,			world_size=__lowercase						)
						assert len(list(__lowercase						)						) == 1 + full_size // world_size
						with pytest.raises(__lowercase						):
												split_dataset_by_node(full_ds.shuffle()					,			rank=0					,			world_size=__lowercase						)
@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						(__lowercase						)       ->       Any:

						'''simple docstring'''



						_snake_case						:     Union[str, Any]				=    2
						_snake_case						:     Optional[Any]				=    get_torch_dist_unique_port()
						_snake_case						:     Optional[int]				=    Path(__lowercase						).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
						_snake_case						:     Any				=    F"""
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    """.split()
						_snake_case						:     str				=    F"""
        --streaming={streaming}
    """.split()
						_snake_case						:     Optional[Any]				=    [sys.executable] + distributed_args + args
						execute_subprocess_async(__lowercase					,			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						(__lowercase					,			__lowercase						)       ->       Optional[Any]:

						'''simple docstring'''



						_snake_case						:     Dict				=    True
						_snake_case						:     Optional[int]				=    get_torch_dist_unique_port()
						_snake_case						:     List[str]				=    Path(__lowercase						).resolve().parent / "distributed_scripts" / "launch_torch_distributed.py"
						_snake_case						:     List[str]				=    F"""
        -m torch.distributed.launch
        --nproc_per_node={nproc_per_node}
        --master_port={master_port}
        {test_script}
    """.split()
						_snake_case						:     Tuple				=    F"""
        --streaming={streaming}
        --num_workers={num_workers}
    """.split()
						_snake_case						:     Any				=    [sys.executable] + distributed_args + args
						execute_subprocess_async(__lowercase					,			env=os.environ.copy()						)