

'''simple docstring'''




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType






class   _SCREAMING_SNAKE_CASE   (   __a     ):



 def __init__(   self		:   Union[str, Any]			,				a__		:   Any      ):
      __magic_name__						       =    data



 def __iter__(   self		:   List[str]      ):
      for element in self.data:
           yield element




def 						UpperCamelCase	(			a=True			)				->     Union[str, Any]:






     '''simple docstring'''
     __magic_name__						       =    Accelerator(even_batches=a			)
     assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
     return accelerator




def 						UpperCamelCase	(			a		,						a		,						a		,						a = False			)				->     int:






     '''simple docstring'''
     if iterable:
          __magic_name__						       =    DummyIterableDataset(torch.as_tensor(range(a			)			)			)
     else:
          __magic_name__						       =    TensorDataset(torch.as_tensor(range(a			)			)			)

     __magic_name__						       =    DataLoader(a		,						batch_size=a			)
     __magic_name__						       =    accelerator.prepare(a			)

     return dl




def 						UpperCamelCase	(			a		,						a		,						a		,						a		,						a		,						)				->     Union[str, Any]:






     '''simple docstring'''
     __magic_name__						       =    create_dataloader(accelerator=a		,						dataset_size=a		,						batch_size=a			)

     __magic_name__						       =    [len(batch[0]			) for batch in dl]

     if accelerator.process_index == 0:
          assert batch_sizes == process_0_expected_batch_sizes
     elif accelerator.process_index == 1:
          assert batch_sizes == process_1_expected_batch_sizes




def 						UpperCamelCase	(			)				->     Optional[Any]:






     '''simple docstring'''
     __magic_name__						       =    create_accelerator()

     # without padding, we would expect a different number of batches
     verify_dataloader_batch_sizes(
         a		,						dataset_size=3		,						batch_size=1		,						process_0_expected_batch_sizes=[1, 1]		,						process_1_expected_batch_sizes=[1, 1]		,						)

     # without padding, we would expect the same number of batches, but different sizes
     verify_dataloader_batch_sizes(
         a		,						dataset_size=7		,						batch_size=2		,						process_0_expected_batch_sizes=[2, 2]		,						process_1_expected_batch_sizes=[2, 2]		,						)




def 						UpperCamelCase	(			)				->     Optional[int]:






     '''simple docstring'''
     __magic_name__						       =    create_accelerator(even_batches=a			)

     verify_dataloader_batch_sizes(
         a		,						dataset_size=3		,						batch_size=1		,						process_0_expected_batch_sizes=[1, 1]		,						process_1_expected_batch_sizes=[1]		,						)

     verify_dataloader_batch_sizes(
         a		,						dataset_size=7		,						batch_size=2		,						process_0_expected_batch_sizes=[2, 2]		,						process_1_expected_batch_sizes=[2, 1]		,						)




def 						UpperCamelCase	(			)				->     str:






     '''simple docstring'''
     __magic_name__						       =    create_accelerator(even_batches=a			)

     __magic_name__						       =    torch.nn.Linear(1		,						1			)
     __magic_name__						       =    accelerator.prepare(a			)

     __magic_name__						       =    create_dataloader(a		,						dataset_size=3		,						batch_size=1			)

     __magic_name__						       =    []
     with accelerator.join_uneven_inputs([ddp_model]			):
          for batch_idx, batch in enumerate(a			):
               __magic_name__						       =    ddp_model(batch[0].float()			)
               __magic_name__						       =    output.sum()
               loss.backward()
               batch_idxs.append(a			)

     accelerator.wait_for_everyone()

     if accelerator.process_index == 0:
          assert batch_idxs == [0, 1]
     elif accelerator.process_index == 1:
          assert batch_idxs == [0]




def 						UpperCamelCase	(			a			)				->     List[Any]:






     '''simple docstring'''
     with warnings.catch_warnings(record=a			) as w:
          with accelerator.join_uneven_inputs([Mock()]			):
               pass

          assert issubclass(w[-1].category		,						a			)
          assert "only supported for multi-GPU" in str(w[-1].message			)




def 						UpperCamelCase	(			)				->     int:






     '''simple docstring'''
     __magic_name__						       =    True
     __magic_name__						       =    False
     __magic_name__						       =    create_accelerator(even_batches=a			)
     __magic_name__						       =    torch.nn.Linear(1		,						1			)
     __magic_name__						       =    accelerator.prepare(a			)
     __magic_name__						       =    create_dataloader(a		,						dataset_size=3		,						batch_size=1			)
     __magic_name__						       =    create_dataloader(a		,						dataset_size=3		,						batch_size=1			)

     with accelerator.join_uneven_inputs([ddp_model]		,						even_batches=a			):
          __magic_name__						       =    train_dl.batch_sampler.even_batches
          __magic_name__						       =    valid_dl.batch_sampler.even_batches

     assert train_dl_overridden_value == overridden_even_batches
     assert valid_dl_overridden_value == overridden_even_batches
     assert train_dl.batch_sampler.even_batches == default_even_batches
     assert valid_dl.batch_sampler.even_batches == default_even_batches




def 						UpperCamelCase	(			)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    True
     __magic_name__						       =    False
     __magic_name__						       =    create_accelerator(even_batches=a			)
     __magic_name__						       =    torch.nn.Linear(1		,						1			)
     __magic_name__						       =    accelerator.prepare(a			)
     create_dataloader(a		,						dataset_size=3		,						batch_size=1		,						iterable=a			)
     __magic_name__						       =    create_dataloader(a		,						dataset_size=3		,						batch_size=1			)

     with warnings.catch_warnings():
          warnings.filterwarnings('''ignore'''			)
          try:
               with accelerator.join_uneven_inputs([ddp_model]		,						even_batches=a			):
                    __magic_name__						       =    batch_dl.batch_sampler.even_batches
          except AttributeError:
               # ensure attribute error is not raised when processing iterable dl
               raise AssertionError

     assert batch_dl_overridden_value == overridden_even_batches
     assert batch_dl.batch_sampler.even_batches == default_even_batches




def 						UpperCamelCase	(			)				->     Optional[Any]:






     '''simple docstring'''
     __magic_name__						       =    create_accelerator()
     __magic_name__						       =    torch.nn.Linear(1		,						1			)
     __magic_name__						       =    accelerator.prepare(a			)
     create_dataloader(a		,						dataset_size=3		,						batch_size=1		,						iterable=a			)

     with warnings.catch_warnings(record=a			) as w:
          with accelerator.join_uneven_inputs([ddp_model]		,						even_batches=a			):
               pass

          assert issubclass(w[-1].category		,						a			)
          assert "only supported for map-style datasets" in str(w[-1].message			)




def 						UpperCamelCase	(			)				->     List[str]:






     '''simple docstring'''
     __magic_name__						       =    create_accelerator()

     accelerator.print('''Test that even_batches variable ensures uniform batches across processes'''			)
     test_default_ensures_even_batch_sizes()

     accelerator.print('''Run tests with even_batches disabled'''			)
     test_can_disable_even_batches()

     accelerator.print('''Test joining uneven inputs'''			)
     test_can_join_uneven_inputs()

     accelerator.print('''Test overriding even_batches when joining uneven inputs'''			)
     test_join_can_override_even_batches()

     accelerator.print('''Test overriding even_batches for mixed dataloader types'''			)
     test_join_can_override_for_mixed_type_dataloaders()

     accelerator.print('''Test overriding even_batches raises a warning for iterable dataloaders'''			)
     test_join_raises_warning_for_iterable_when_overriding_even_batches()

     accelerator.print('''Test join with non DDP distributed raises warning'''			)
     __magic_name__						       =    accelerator.state.distributed_type
     __magic_name__						       =    DistributedType.FSDP
     test_join_raises_warning_for_non_ddp_distributed(a			)
     __magic_name__						       =    original_state


if __name__ == "__main__":
      main()









'''simple docstring'''




import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type

from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm


_lowerCAmelCase         =						re.compile("[^A-Za-z_0-9]")
# parameters used in DuplicationIndex
_lowerCAmelCase         =						10
_lowerCAmelCase         =						256




def 						UpperCamelCase	(			a			)				->     Optional[MinHash]:






     '''simple docstring'''
     if len(a			) < MIN_NUM_TOKENS:
          return None
     __magic_name__						       =    MinHash(num_perm=a			)
     for token in set(a			):
          min_hash.update(token.encode()			)
     return min_hash




def 						UpperCamelCase	(			a			)				->     Set[str]:






     '''simple docstring'''
     return {t for t in NON_ALPHA.split(a			) if len(t.strip()			) > 0}






class   _SCREAMING_SNAKE_CASE   :



 def __init__(   self		:   Any			,				*,
     a__		:   float = 0.85			,				):
      __magic_name__						       =    duplication_jaccard_threshold
      __magic_name__						       =    NUM_PERM
      __magic_name__						       =    MinHashLSH(threshold=self._duplication_jaccard_threshold			,				num_perm=self._num_perm      )

      __magic_name__						       =    defaultdict(a__      )



 def 			snake_case__  (   self		:   int			,				a__		:   Tuple			,				a__		:   MinHash      ):
      __magic_name__						       =    self._index.query(a__      )
      if code_key in self._index.keys:
           print(F'''Duplicate key {code_key}'''      )
           return

      self._index.insert(a__			,				a__      )
      if len(a__      ) > 0:
           for base_duplicate in close_duplicates:
                if base_duplicate in self._duplicate_clusters:
                     self._duplicate_clusters[base_duplicate].add(a__      )
                     break
           else:
                self._duplicate_clusters[close_duplicates[0]].add(a__      )



 def 			snake_case__  (   self		:   Optional[int]      ):
      __magic_name__						       =    []
      for base, duplicates in self._duplicate_clusters.items():
           __magic_name__						       =    [base] + list(a__      )
           # reformat the cluster to be a list of dict
           __magic_name__						       =    [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster]
           duplicate_clusters.append(a__      )
      return duplicate_clusters



 def 			snake_case__  (   self		:   int			,				a__		:   Tuple      ):
      __magic_name__						       =    self.get_duplicate_clusters()
      with open(a__			,				'''w'''      ) as f:
           json.dump(a__			,				a__      )




def 						UpperCamelCase	(			a			)				->     List[Any]:






     '''simple docstring'''
     __magic_name__       ,  __magic_name__						       =    element
     __magic_name__						       =    get_min_hash([t for t in NON_ALPHA.split(data['''content''']			) if len(t.strip()			) > 0]			)
     if min_hash is not None:
          return (index, data["repo_name"], data["path"]), min_hash




def 						UpperCamelCase	(			a			)				->     List[Any]:






     '''simple docstring'''
     with mp.Pool() as pool:
          for data in pool.imap_unordered(
              _compute_min_hash		,						ThreadedIterator(a		,						max_queue_size=1_0000			)		,						chunksize=100		,						):
               if data is not None:
                    yield data




def 						UpperCamelCase	(			a		,						a			)				->     Tuple:






     '''simple docstring'''
     __magic_name__						       =    DuplicationIndex(duplication_jaccard_threshold=a			)

     for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(a			)			)		,						max_queue_size=100			)			):
          di.add(a		,						a			)

     # Returns a List[Cluster] where Cluster is List[str] with the filenames.
     return di.get_duplicate_clusters()




def 						UpperCamelCase	(			a		,						a			)				->     float:






     '''simple docstring'''
     __magic_name__						       =    get_tokens(a			)
     __magic_name__						       =    get_tokens(a			)
     return len(tokensa & tokensa			) / len(tokensa | tokensa			)


_lowerCAmelCase         =						None




def 						UpperCamelCase	(			a		,						a			)				->     Dict:






     '''simple docstring'''
     __magic_name__						       =    []
     for elementa in cluster:
          __magic_name__						       =    _shared_dataset[elementa['''base_index''']]['''content''']
          for elementa in extremes:
               __magic_name__						       =    _shared_dataset[elementa['''base_index''']]['''content''']
               if jaccard_similarity(a		,						a			) >= jaccard_threshold:
                    elementa["copies"] += 1
                    break
          else:
               __magic_name__						       =    1
               extremes.append(a			)
     return extremes




def 						UpperCamelCase	(			a		,						a		,						a			)				->     Optional[Any]:






     '''simple docstring'''
     global _shared_dataset
     __magic_name__						       =    dataset
     __magic_name__						       =    []
     __magic_name__						       =    partial(_find_cluster_extremes_shared		,						jaccard_threshold=a			)
     with mp.Pool() as pool:
          for extremes in tqdm(
              pool.imap_unordered(
                  a		,						a		,						)		,						total=len(a			)		,						):
               extremes_list.append(a			)
     return extremes_list




def 						UpperCamelCase	(			a		,						a = 0.85			)				->     Tuple[Type[Dataset], List[List[Dict]]]:






     '''simple docstring'''
     __magic_name__						       =    make_duplicate_clusters(a		,						a			)
     __magic_name__						       =    {x['''base_index'''] for cluster in duplicate_clusters for x in cluster}
     __magic_name__						       =    {}
     __magic_name__						       =    find_extremes(a		,						a		,						a			)
     for extremes in extremes_clusters:
          for element in extremes:
               __magic_name__						       =    element
     __magic_name__						       =    duplicate_indices - set(extreme_dict.keys()			)
     __magic_name__						       =    dataset.filter(lambda a		,						a			: idx not in remove_indices		,						with_indices=a			)

     # update duplicate_clusters
     for cluster in duplicate_clusters:
          for element in cluster:
               __magic_name__						       =    element['''base_index'''] in extreme_dict
               if element["is_extreme"]:
                    __magic_name__						       =    extreme_dict[element['''base_index''']]['''copies''']

     print(F'''Original dataset size: {len(a			)}'''			)
     print(F'''Number of duplicate clusters: {len(a			)}'''			)
     print(F'''Files in duplicate cluster: {len(a			)}'''			)
     print(F'''Unique files in duplicate cluster: {len(a			)}'''			)
     print(F'''Filtered dataset size: {len(a			)}'''			)

     return ds_filter, duplicate_clusters






