






"""simple docstring"""




import json
import os
import pickle
import subprocess
from hashlib import mda
from pathlib import Path
from tempfile import gettempdir
from textwrap import dedent
from types import CodeType, FunctionType
from unittest import TestCase
from unittest.mock import patch

import pytest
from multiprocess import Pool
from packaging import version

import datasets
from datasets.fingerprint import Hasher, fingerprint_transform
from datasets.table import InMemoryTable

from .utils import (
    require_regex,
    require_spacy,
    require_spacy_model,
    require_tiktoken,
    require_torch,
    require_transformers,
)
class    a   :



      """simple docstring"""


      def __init__(				self :      Union[str, Any]		,				__lowercase :      str )							->				List[str]:
        __UpperCAmelCase							:     List[str]									=  foo




      def __call__(				self :      List[str] )							->				int:
        return self.foo


class    a   (			datasets.Dataset       ):



      """simple docstring"""


      @fingerprint_transform(inplace=lowercase__ )
      def      UpperCAmelCase				(				self :      List[str]		,				__lowercase :      str		,				*__lowercase :      int		,				**__lowercase :      List[Any] )							->				Tuple:
        return DatasetChild(self.data		,				fingerprint=lowercase__ )




      @fingerprint_transform(inplace=lowercase__ )
      def      UpperCAmelCase				(				self :      Any		,				__lowercase :      Dict		,				*__lowercase :      List[str]		,				**__lowercase :      List[str] )							->				List[Any]:
        return DatasetChild(self.data		,				fingerprint=lowercase__ )


class    a   :



      """simple docstring"""


      def __init__(				self :      Union[str, Any]		,				__lowercase :      Optional[int] )							->				str:
        __UpperCAmelCase							:     List[str]									=  callable
      def __call__(				self :      Optional[int]		,				*__lowercase :      int		,				**__lowercase :      Optional[int] )							->				List[str]:







        if self.callable is not None:
          return self.callable(*lowercase__		,				**lowercase__ )




      def __getstate__(				self :      Optional[Any] )							->				Optional[Any]:
        raise pickle.PicklingError()


class    a   (			lowercase__       ):



      """simple docstring"""


      @require_transformers
      @pytest.mark.integration
      def      UpperCAmelCase				(				self :      List[str] )							->				str:
        from transformers import AutoTokenizer

        def encode(__lowercase :      Optional[int] ):
          return tokenizer(lowercase__ )

        # TODO: add hash consistency tests across sessions
        __UpperCAmelCase							:     str									=  AutoTokenizer.from_pretrained("""bert-base-uncased""" )
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Union[str, Any]									=  mda(datasets.utils.py_utils.dumps(lambda __lowercase : tokenizer(lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase							:     str									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  AutoTokenizer.from_pretrained("""bert-base-cased""" )
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[Any]									=  mda(datasets.utils.py_utils.dumps(lambda __lowercase : tokenizer(lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase							:     Any									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  AutoTokenizer.from_pretrained("""bert-base-uncased""" )
        __UpperCAmelCase							:     Dict									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(lambda __lowercase : tokenizer(lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      @require_transformers
      @pytest.mark.integration
      def      UpperCAmelCase				(				self :      List[str] )							->				Any:
        from transformers import AutoTokenizer

        __UpperCAmelCase							:     Any									=  AutoTokenizer.from_pretrained("""gpt2""" )
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        tokenizer("""Hello world !""" )  # call once to change the tokenizer's cache
        __UpperCAmelCase							:     str									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )




      @require_regex
      def      UpperCAmelCase				(				self :      Optional[Any] )							->				Tuple:
        import regex

        __UpperCAmelCase							:     Any									=  regex.Regex("""foo""" )
        __UpperCAmelCase							:     Any									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Dict									=  regex.Regex("""bar""" )
        __UpperCAmelCase							:     List[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  regex.Regex("""foo""" )
        __UpperCAmelCase							:     Optional[int]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )


class    a   (			lowercase__       ):



      """simple docstring"""


      def      UpperCAmelCase				(				self :      List[str] )							->				Any:







        def func():
          return foo

        __UpperCAmelCase							:     Union[str, Any]									=  [0]
        __UpperCAmelCase							:     str									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     str									=  [1]
        __UpperCAmelCase							:     Optional[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     List[Any]									=  [0]
        __UpperCAmelCase							:     Any									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      Optional[Any] )							->				Union[str, Any]:







        def func():
          pass

        __UpperCAmelCase							:     int									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()

        def func():
          pass

        __UpperCAmelCase							:     Dict									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      str )							->				List[Any]:
        __UpperCAmelCase							:     Dict									=  mda(datasets.utils.py_utils.dumps(Foo([0] ) ) ).hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  mda(datasets.utils.py_utils.dumps(Foo([1] ) ) ).hexdigest()
        __UpperCAmelCase							:     Optional[Any]									=  mda(datasets.utils.py_utils.dumps(Foo([0] ) ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      Tuple )							->				Optional[int]:
        __UpperCAmelCase							:     Union[str, Any]									=  mda(datasets.utils.py_utils.dumps(Foo([0] ).__call__ ) ).hexdigest()
        __UpperCAmelCase							:     Tuple									=  mda(datasets.utils.py_utils.dumps(Foo([1] ).__call__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[Any]									=  mda(datasets.utils.py_utils.dumps(Foo([0] ).__call__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      Any )							->				int:
        __UpperCAmelCase							:     int									=  (
            """co_argcount""",
            """co_kwonlyargcount""",
            """co_nlocals""",
            """co_stacksize""",
            """co_flags""",
            """co_code""",
            """co_consts""",
            """co_names""",
            """co_varnames""",
            """co_filename""",
            """co_name""",
            """co_firstlineno""",
            """co_lnotab""",
            """co_freevars""",
            """co_cellvars""",
        )

        def _create_code_pyaa(*__lowercase :      Tuple ):
          if hasattr(args[-3]		,				"""encode""" ):
            __UpperCAmelCase							:     Union[str, Any]									=  list(lowercase__ )
            __UpperCAmelCase							:     List[str]									=  args[-3].encode()  # co_lnotab
            __UpperCAmelCase							:     str									=  args[-10].encode()  # co_code
          if hasattr(lowercase__		,				"""co_posonlyargcount""" ):
            if len(lowercase__ ) == 16:
              return CodeType(*lowercase__ )
            elif len(lowercase__ ) == 15:
              return CodeType(args[0]		,				0		,				*args[1:] )
            return CodeType(args[0]		,				0		,				0		,				*args[1:] )
          elif hasattr(lowercase__		,				"""co_kwonlyargcount""" ):
            if len(lowercase__ ) == 16:
              return CodeType(args[0]		,				*args[2:] )
            elif len(lowercase__ ) == 15:
              return CodeType(*lowercase__ )
            return CodeType(args[0]		,				0		,				*args[1:] )
          if len(lowercase__ ) == 16:
            return CodeType(args[0]		,				*args[3:] )
          elif len(lowercase__ ) == 15:
            return CodeType(args[0]		,				*args[2:] )
          return CodeType(*lowercase__ )

        def create_ipython_func(__lowercase :      List[Any]		,				__lowercase :      Union[str, Any] ):
          def func():
            return returned_obj

          __UpperCAmelCase							:     Optional[Any]									=  func.__code__
          # Use _create_code from dill in order to make it work for different python versions
          if datasets.config.PY_VERSION < version.parse("""3.8""" ):
            __UpperCAmelCase							:     Dict									=  _create_code_pyaa(
                *[getattr(lowercase__		,				lowercase__ ) if k != """co_filename""" else co_filename for k in code_args_pyaa] )
          else:
            __UpperCAmelCase							:     Any									=  code.replace(co_filename=lowercase__ )
          return FunctionType(lowercase__		,				func.__globals__		,				func.__name__		,				func.__defaults__		,				func.__closure__ )

        __UpperCAmelCase				,			__UpperCAmelCase							:     Any									=  """<ipython-input-2-e0383a102aae>""", [0]
        __UpperCAmelCase							:     Optional[int]									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase				,			__UpperCAmelCase							:     List[Any]									=  """<ipython-input-2-e0383a102aae>""", [1]
        __UpperCAmelCase							:     List[Any]									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase				,			__UpperCAmelCase							:     Union[str, Any]									=  """<ipython-input-5-713f6613acf3>""", [0]
        __UpperCAmelCase							:     Dict									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )

        __UpperCAmelCase				,			__UpperCAmelCase							:     Optional[Any]									=  os.path.join(gettempdir()		,				"""ipykernel_12345"""		,				"""321456789.py""" ), [0]
        __UpperCAmelCase							:     Dict									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase				,			__UpperCAmelCase							:     List[Any]									=  os.path.join(gettempdir()		,				"""ipykernel_12345"""		,				"""321456789.py""" ), [1]
        __UpperCAmelCase							:     List[str]									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        __UpperCAmelCase				,			__UpperCAmelCase							:     int									=  os.path.join(gettempdir()		,				"""ipykernel_12345"""		,				"""654123987.py""" ), [0]
        __UpperCAmelCase							:     str									=  mda(datasets.utils.py_utils.dumps(create_ipython_func(lowercase__		,				lowercase__ ) ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )




      def      UpperCAmelCase				(				self :      Optional[Any] )							->				Optional[int]:
        __UpperCAmelCase				,			__UpperCAmelCase							:     int									=  [0], [1]

        def func():
          return foo, bar

        __UpperCAmelCase							:     Optional[Any]									=  """__main__"""

        def globalvars_mocka_side_effect(__lowercase :      List[str]		,				*__lowercase :      Any		,				**__lowercase :      Optional[Any] ):
          return {"foo": foo, "bar": bar}

        def globalvars_mocka_side_effect(__lowercase :      Optional[Any]		,				*__lowercase :      List[str]		,				**__lowercase :      str ):
          return {"bar": bar, "foo": foo}

        with patch("""dill.detect.globalvars"""		,				side_effect=lowercase__ ) as globalvars_mocka:
          __UpperCAmelCase							:     Any									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
          self.assertGreater(globalvars_mocka.call_count		,				0 )
        with patch("""dill.detect.globalvars"""		,				side_effect=lowercase__ ) as globalvars_mocka:
          __UpperCAmelCase							:     int									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
          self.assertGreater(globalvars_mocka.call_count		,				0 )
        self.assertEqual(lowercase__		,				lowercase__ )


class    a   (			lowercase__       ):



      """simple docstring"""


      def      UpperCAmelCase				(				self :      Any )							->				Optional[int]:
        __UpperCAmelCase							:     Dict									=  Hasher.hash("""hello""" )
        __UpperCAmelCase							:     Any									=  Hasher.hash("""hello""" )
        __UpperCAmelCase							:     Any									=  Hasher.hash("""there""" )
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      Union[str, Any] )							->				Optional[int]:
        __UpperCAmelCase							:     Any									=  Hasher.hash(Foo("""hello""" ) )
        __UpperCAmelCase							:     List[Any]									=  Hasher.hash(Foo("""hello""" ) )
        __UpperCAmelCase							:     Optional[int]									=  Hasher.hash(Foo("""there""" ) )
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      List[str] )							->				Any:
        __UpperCAmelCase							:     Optional[int]									=  Hasher()
        for x in ["hello", Foo("""hello""" )]:
          hasher.update(lowercase__ )
        __UpperCAmelCase							:     int									=  hasher.hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  Hasher()
        for x in ["hello", Foo("""hello""" )]:
          hasher.update(lowercase__ )
        __UpperCAmelCase							:     int									=  hasher.hexdigest()
        __UpperCAmelCase							:     str									=  Hasher()
        for x in ["there", Foo("""there""" )]:
          hasher.update(lowercase__ )
        __UpperCAmelCase							:     Union[str, Any]									=  hasher.hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      def      UpperCAmelCase				(				self :      int )							->				int:







        with self.assertRaises(pickle.PicklingError ):
          Hasher.hash(UnpicklableCallable(Foo("""hello""" ) ) )
      def      UpperCAmelCase				(				self :      List[str] )							->				Optional[int]:
        __UpperCAmelCase							:     Tuple									=  """abc"""
        __UpperCAmelCase							:     List[str]									=  [string, string]  # two strings have the same ids
        __UpperCAmelCase							:     int									=  [string, string]
        __UpperCAmelCase							:     Tuple									=  json.loads(f"""[\"{string}\", \"{string}\"]""" )  # two strings have different ids
        self.assertIs(obja[0]		,				lowercase__ )
        self.assertIs(obja[0]		,				obja[1] )
        self.assertIs(obja[0]		,				lowercase__ )
        self.assertIs(obja[0]		,				obja[1] )
        self.assertIsNot(obja[0]		,				lowercase__ )
        self.assertIsNot(obja[0]		,				obja[1] )
        __UpperCAmelCase							:     int									=  Hasher.hash(lowercase__ )
        __UpperCAmelCase							:     Union[str, Any]									=  Hasher.hash(lowercase__ )
        __UpperCAmelCase							:     str									=  Hasher.hash(lowercase__ )
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertEqual(lowercase__		,				lowercase__ )
      @require_tiktoken
      def      UpperCAmelCase				(				self :      Tuple )							->				List[Any]:
        import tiktoken

        __UpperCAmelCase							:     str									=  tiktoken.get_encoding("""gpt2""" )
        __UpperCAmelCase							:     Optional[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Optional[int]									=  tiktoken.get_encoding("""r50k_base""" )
        __UpperCAmelCase							:     int									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     Dict									=  tiktoken.get_encoding("""gpt2""" )
        __UpperCAmelCase							:     Union[str, Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )
      @require_torch
      def      UpperCAmelCase				(				self :      Tuple )							->				str:
        import torch

        __UpperCAmelCase							:     Dict									=  torch.tensor([1.0] )
        __UpperCAmelCase							:     List[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     List[Any]									=  torch.tensor([2.0] )
        __UpperCAmelCase							:     int									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     str									=  torch.tensor([1.0] )
        __UpperCAmelCase							:     List[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )




      @require_spacy
      @require_spacy_model("""en_core_web_sm""" )
      @require_spacy_model("""fr_core_news_sm""" )
      @pytest.mark.integration
      def      UpperCAmelCase				(				self :      str )							->				Optional[Any]:
        import spacy

        __UpperCAmelCase							:     Optional[int]									=  spacy.load("""en_core_web_sm""" )
        __UpperCAmelCase							:     Any									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     List[str]									=  spacy.load("""fr_core_news_sm""" )
        __UpperCAmelCase							:     int									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        __UpperCAmelCase							:     List[Any]									=  spacy.load("""en_core_web_sm""" )
        __UpperCAmelCase							:     List[Any]									=  mda(datasets.utils.py_utils.dumps(lowercase__ ) ).hexdigest()
        self.assertEqual(lowercase__		,				lowercase__ )
        self.assertNotEqual(lowercase__		,				lowercase__ )






@pytest.mark.integration
def     lowerCamelCase__				(   __lowerCamelCase      :					str		):
  __UpperCAmelCase							:     Optional[Any]									=  tmp_path / """dir1"""
  __UpperCAmelCase							:     List[Any]									=  tmp_path / """dir2"""
  dira.mkdir()
  dira.mkdir()
  __UpperCAmelCase							:     str									=  """script.py"""
  __UpperCAmelCase							:     Dict									=  dedent(
      """\n    from datasets.fingerprint import Hasher\n    def foo():\n        pass\n    print(Hasher.hash(foo))\n    """		)
  __UpperCAmelCase							:     int									=  dira / script_filename
  __UpperCAmelCase							:     int									=  dira / script_filename
  with script_patha.open("""w"""		) as f:
    f.write(SCREAMING_SNAKE_CASE_		)
  with script_patha.open("""w"""		) as f:
    f.write(SCREAMING_SNAKE_CASE_		)
  __UpperCAmelCase							:     List[Any]									=  subprocess.check_output(["""python""", str(SCREAMING_SNAKE_CASE_		)]		)
  __UpperCAmelCase							:     str									=  subprocess.check_output(["""python""", str(SCREAMING_SNAKE_CASE_		)]		)
  assert fingerprinta == fingerprinta






def     lowerCamelCase__				(   ):
  __UpperCAmelCase							:     Any									=  {"""a""": [0, 1, 2]}
  __UpperCAmelCase							:     Dict									=  DatasetChild(InMemoryTable.from_pydict(SCREAMING_SNAKE_CASE_		)		)
  __UpperCAmelCase							:     str									=  dataset.funca()._fingerprint
  assert expected_fingerprint == dataset.funca()._fingerprint
  assert expected_fingerprint != dataset.funca()._fingerprint

  with Pool(2		) as p:
    assert expected_fingerprint == p.apply_async(dataset.funca		).get()._fingerprint
    assert expected_fingerprint != p.apply_async(dataset.funca		).get()._fingerprint






def     lowerCamelCase__				(   ):
  __UpperCAmelCase							:     Union[str, Any]									=  {"""a""": [0, 1, 2]}
  class    a   (			datasets.Dataset       ):



        """simple docstring"""


        @fingerprint_transform(inplace=lowercase__ )
        def      UpperCAmelCase				(				self :      List[Any]		,				__lowercase :      Optional[int] )							->				Any:
          return DummyDatasetChild(self.data		,				fingerprint=lowercase__ )


  __UpperCAmelCase							:     Optional[Any]									=  DummyDatasetChild(InMemoryTable.from_pydict(SCREAMING_SNAKE_CASE_		)		).func()
  class    a   (			datasets.Dataset       ):



        """simple docstring"""


        @fingerprint_transform(inplace=lowercase__		,				version="""1.0.0""" )
        def      UpperCAmelCase				(				self :      Union[str, Any]		,				__lowercase :      Optional[int] )							->				int:
          return DummyDatasetChild(self.data		,				fingerprint=lowercase__ )


  __UpperCAmelCase							:     str									=  DummyDatasetChild(InMemoryTable.from_pydict(SCREAMING_SNAKE_CASE_		)		).func()
  class    a   (			datasets.Dataset       ):



        """simple docstring"""


        @fingerprint_transform(inplace=lowercase__		,				version="""2.0.0""" )
        def      UpperCAmelCase				(				self :      Optional[Any]		,				__lowercase :      List[Any] )							->				Dict:
          return DummyDatasetChild(self.data		,				fingerprint=lowercase__ )


  __UpperCAmelCase							:     Union[str, Any]									=  DummyDatasetChild(InMemoryTable.from_pydict(SCREAMING_SNAKE_CASE_		)		).func()

  assert len({fingeprint_no_version, fingeprint_a, fingeprint_a}		) == 3







def     lowerCamelCase__				(   ):
  # AttributeError: module 'dill._dill' has no attribute 'stack'
  __UpperCAmelCase							:     List[str]									=  Hasher()
  hasher.update(lambda __lowerCamelCase		: x		)










import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


a		:	str      					=			logging.getLogger(__name__)

require_version("pytorch_lightning>=1.0.4")

a		:	Any      					=			{
    "base": AutoModel,
    "sequence-classification": AutoModelForSequenceClassification,
    "question-answering": AutoModelForQuestionAnswering,
    "pretraining": AutoModelForPreTraining,
    "token-classification": AutoModelForTokenClassification,
    "language-modeling": AutoModelWithLMHead,
    "summarization": AutoModelForSeqaSeqLM,
    "translation": AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
a		:	List[str]      					=			{
    "linear": get_linear_schedule_with_warmup,
    "cosine": get_cosine_schedule_with_warmup,
    "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup,
    "polynomial": get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
a		:	int      					=			sorted(arg_to_scheduler.keys())
a		:	Dict      					=			"{" + ", ".join(arg_to_scheduler_choices) + "}"
class    a   (			pl.LightningModule       ):



      """simple docstring"""


      def __init__(				self :      Union[str, Any]		,				__lowercase :      argparse.Namespace		,				__lowercase :      int=None		,				__lowercase :      Any="base"		,				__lowercase :      str=None		,				__lowercase :      Dict=None		,				__lowercase :      Optional[Any]=None		,				**__lowercase :      Optional[Any]		,				)							->				List[str]:
        super().__init__()
        # TODO: move to self.save_hyperparameters()
        # self.save_hyperparameters()
        # can also expand arguments into trainer signature for easier reading

        self.save_hyperparameters(__lowercase )
        __UpperCAmelCase							:     Any									=  0
        __UpperCAmelCase							:     List[Any]									=  Path(self.hparams.output_dir )
        __UpperCAmelCase							:     int									=  self.hparams.cache_dir if self.hparams.cache_dir else None
        if config is None:
          __UpperCAmelCase							:     str									=  AutoConfig.from_pretrained(
              self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path		,				**({"""num_labels""": num_labels} if num_labels is not None else {})		,				cache_dir=__lowercase		,				**__lowercase		,				)
        else:
          __UpperCAmelCase							:     PretrainedConfig									=  config

        __UpperCAmelCase							:     Optional[int]									=  ("""encoder_layerdrop""", """decoder_layerdrop""", """dropout""", """attention_dropout""")
        for p in extra_model_params:
          if getattr(self.hparams		,				__lowercase		,				__lowercase ):
            assert hasattr(self.config		,				__lowercase ), f"""model config doesn't have a `{p}` attribute"""
            setattr(self.config		,				__lowercase		,				getattr(self.hparams		,				__lowercase ) )

        if tokenizer is None:
          __UpperCAmelCase							:     Tuple									=  AutoTokenizer.from_pretrained(
              self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path		,				cache_dir=__lowercase		,				)
        else:
          __UpperCAmelCase							:     PreTrainedTokenizer									=  tokenizer
        __UpperCAmelCase							:     Dict									=  MODEL_MODES[mode]
        if model is None:
          __UpperCAmelCase							:     Dict									=  self.model_type.from_pretrained(
              self.hparams.model_name_or_path		,				from_tf=bool(""".ckpt""" in self.hparams.model_name_or_path )		,				config=self.config		,				cache_dir=__lowercase		,				)
        else:
          __UpperCAmelCase							:     Any									=  model
      def      UpperCAmelCase				(				self :      Optional[Any]		,				*__lowercase :      Optional[Any]		,				**__lowercase :      Optional[Any] )							->				List[Any]:
        __UpperCAmelCase							:     List[Any]									=  self.model_type.from_pretrained(*__lowercase		,				**__lowercase )
      def      UpperCAmelCase				(				self :      Union[str, Any] )							->				Dict:
        __UpperCAmelCase							:     Union[str, Any]									=  arg_to_scheduler[self.hparams.lr_scheduler]
        __UpperCAmelCase							:     Optional[int]									=  get_schedule_func(
            self.opt		,				num_warmup_steps=self.hparams.warmup_steps		,				num_training_steps=self.total_steps() )
        __UpperCAmelCase							:     int									=  {"""scheduler""": scheduler, """interval""": """step""", """frequency""": 1}
        return scheduler
      def      UpperCAmelCase				(				self :      Optional[int] )							->				int:
        __UpperCAmelCase							:     List[str]									=  self.model
        __UpperCAmelCase							:     List[str]									=  ["""bias""", """LayerNorm.weight"""]
        __UpperCAmelCase							:     List[str]									=  [
            {
                """params""": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay )],
                """weight_decay""": self.hparams.weight_decay,
            },
            {
                """params""": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay )],
                """weight_decay""": 0.0,
            },
        ]
        if self.hparams.adafactor:
          __UpperCAmelCase							:     List[Any]									=  Adafactor(
              __lowercase		,				lr=self.hparams.learning_rate		,				scale_parameter=__lowercase		,				relative_step=__lowercase )

        else:
          __UpperCAmelCase							:     Optional[int]									=  AdamW(
              __lowercase		,				lr=self.hparams.learning_rate		,				eps=self.hparams.adam_epsilon )
        __UpperCAmelCase							:     Dict									=  optimizer

        __UpperCAmelCase							:     Dict									=  self.get_lr_scheduler()

        return [optimizer], [scheduler]
      def      UpperCAmelCase				(				self :      Any		,				__lowercase :      List[Any]		,				__lowercase :      Tuple )							->				List[Any]:
        return self.validation_step(__lowercase		,				__lowercase )
      def      UpperCAmelCase				(				self :      Union[str, Any]		,				__lowercase :      Optional[int] )							->				Optional[int]:
        return self.validation_end(__lowercase )
      def      UpperCAmelCase				(				self :      Union[str, Any] )							->				int:
        __UpperCAmelCase							:     Optional[Any]									=  max(1		,				self.hparams.gpus )  # TODO: consider num_tpu_cores
        __UpperCAmelCase							:     int									=  self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
        return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs
      def      UpperCAmelCase				(				self :      Any		,				__lowercase :      Tuple )							->				Dict:
        if stage == "test":
          __UpperCAmelCase							:     str									=  len(self.test_dataloader().dataset )
        else:
          __UpperCAmelCase							:     Any									=  self.get_dataloader("""train"""		,				self.hparams.train_batch_size		,				shuffle=__lowercase )
          __UpperCAmelCase							:     List[Any]									=  len(self.train_dataloader().dataset )
      def      UpperCAmelCase				(				self :      List[str]		,				__lowercase :      str		,				__lowercase :      int		,				__lowercase :      bool = False )							->				Optional[int]:
        raise NotImplementedError("""You must implement this for your task""" )
      def      UpperCAmelCase				(				self :      Optional[Any] )							->				Dict:
        return self.train_loader
      def      UpperCAmelCase				(				self :      Optional[Any] )							->				Tuple:
        return self.get_dataloader("""dev"""		,				self.hparams.eval_batch_size		,				shuffle=__lowercase )
      def      UpperCAmelCase				(				self :      Dict )							->				List[Any]:
        return self.get_dataloader("""test"""		,				self.hparams.eval_batch_size		,				shuffle=__lowercase )
      def      UpperCAmelCase				(				self :      Optional[int]		,				__lowercase :      Optional[int] )							->				List[Any]:
        return os.path.join(
            self.hparams.data_dir		,				"""cached_{}_{}_{}""".format(
                __lowercase		,				list(filter(__lowercase		,				self.hparams.model_name_or_path.split("""/""" ) ) ).pop()		,				str(self.hparams.max_seq_length )		,				)		,				)
      @pl.utilities.rank_zero_only
      def      UpperCAmelCase				(				self :      Optional[Any]		,				__lowercase :      Dict[str, Any] )							->				None:
        __UpperCAmelCase							:     List[str]									=  self.output_dir.joinpath("""best_tfmr""" )
        __UpperCAmelCase							:     str									=  self.step_count
        self.model.save_pretrained(__lowercase )
        self.tokenizer.save_pretrained(__lowercase )




      @staticmethod
      def      UpperCAmelCase				(				__lowercase :      List[str]		,				__lowercase :      Optional[int] )							->				Optional[int]:
        parser.add_argument(
            """--model_name_or_path"""		,				default=__lowercase		,				type=__lowercase		,				required=__lowercase		,				help="""Path to pretrained model or model identifier from huggingface.co/models"""		,				)
        parser.add_argument(
            """--config_name"""		,				default=""""""		,				type=__lowercase		,				help="""Pretrained config name or path if not the same as model_name""" )
        parser.add_argument(
            """--tokenizer_name"""		,				default=__lowercase		,				type=__lowercase		,				help="""Pretrained tokenizer name or path if not the same as model_name"""		,				)
        parser.add_argument(
            """--cache_dir"""		,				default=""""""		,				type=__lowercase		,				help="""Where do you want to store the pre-trained models downloaded from huggingface.co"""		,				)
        parser.add_argument(
            """--encoder_layerdrop"""		,				type=__lowercase		,				help="""Encoder layer dropout probability (Optional). Goes into model.config"""		,				)
        parser.add_argument(
            """--decoder_layerdrop"""		,				type=__lowercase		,				help="""Decoder layer dropout probability (Optional). Goes into model.config"""		,				)
        parser.add_argument(
            """--dropout"""		,				type=__lowercase		,				help="""Dropout probability (Optional). Goes into model.config"""		,				)
        parser.add_argument(
            """--attention_dropout"""		,				type=__lowercase		,				help="""Attention dropout probability (Optional). Goes into model.config"""		,				)
        parser.add_argument("""--learning_rate"""		,				default=5e-5		,				type=__lowercase		,				help="""The initial learning rate for Adam.""" )
        parser.add_argument(
            """--lr_scheduler"""		,				default="""linear"""		,				choices=__lowercase		,				metavar=__lowercase		,				type=__lowercase		,				help="""Learning rate scheduler"""		,				)
        parser.add_argument("""--weight_decay"""		,				default=0.0		,				type=__lowercase		,				help="""Weight decay if we apply some.""" )
        parser.add_argument("""--adam_epsilon"""		,				default=1e-8		,				type=__lowercase		,				help="""Epsilon for Adam optimizer.""" )
        parser.add_argument("""--warmup_steps"""		,				default=0		,				type=__lowercase		,				help="""Linear warmup over warmup_steps.""" )
        parser.add_argument("""--num_workers"""		,				default=4		,				type=__lowercase		,				help="""kwarg passed to DataLoader""" )
        parser.add_argument("""--num_train_epochs"""		,				dest="""max_epochs"""		,				default=3		,				type=__lowercase )
        parser.add_argument("""--train_batch_size"""		,				default=32		,				type=__lowercase )
        parser.add_argument("""--eval_batch_size"""		,				default=32		,				type=__lowercase )
        parser.add_argument("""--adafactor"""		,				action="""store_true""" )


class    a   (			pl.Callback       ):



      """simple docstring"""


      def      UpperCAmelCase				(				self :      int		,				__lowercase :      Tuple		,				__lowercase :      str )							->				Optional[Any]:
        if (
            trainer.is_global_zero and trainer.global_rank == 0
        ):  # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.
          pl_module.model.rag.retriever.init_retrieval()  # better to use hook functions.


class    a   (			pl.Callback       ):



      """simple docstring"""


      def      UpperCAmelCase				(				self :      List[Any]		,				__lowercase :      int		,				__lowercase :      Union[str, Any] )							->				Optional[int]:
        __UpperCAmelCase							:     Union[str, Any]									=  trainer.lr_schedulers[0]["""scheduler"""]
        __UpperCAmelCase							:     Optional[Any]									=  {f"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr() )}
        pl_module.logger.log_metrics(__lowercase )
      def      UpperCAmelCase				(				self :      Any		,				__lowercase :      pl.Trainer		,				__lowercase :      pl.LightningModule )							->				Dict:
        rank_zero_info("""***** Validation results *****""" )
        __UpperCAmelCase							:     int									=  trainer.callback_metrics
        # Log results
        for key in sorted(__lowercase ):
          if key not in ["log", "progress_bar"]:
            rank_zero_info("""{} = {}\n""".format(__lowercase		,				str(metrics[key] ) ) )




      def      UpperCAmelCase				(				self :      Any		,				__lowercase :      pl.Trainer		,				__lowercase :      pl.LightningModule )							->				Any:
        rank_zero_info("""***** Test results *****""" )
        __UpperCAmelCase							:     List[str]									=  trainer.callback_metrics
        # Log and save results to file
        __UpperCAmelCase							:     Dict									=  os.path.join(pl_module.hparams.output_dir		,				"""test_results.txt""" )
        with open(__lowercase		,				"""w""" ) as writer:
          for key in sorted(__lowercase ):
            if key not in ["log", "progress_bar"]:
              rank_zero_info("""{} = {}\n""".format(__lowercase		,				str(metrics[key] ) ) )
              writer.write("""{} = {}\n""".format(__lowercase		,				str(metrics[key] ) ) )






def     lowerCamelCase__				(   __lowerCamelCase      :					Optional[Any]  ,		__lowerCamelCase      :					List[Any]		):
  #  To allow all pl args uncomment the following line
  #  parser = pl.Trainer.add_argparse_args(parser)
  parser.add_argument(
      """--output_dir"""  ,		default=__lowerCamelCase  ,		type=__lowerCamelCase  ,		required=__lowerCamelCase  ,		help="""The output directory where the model predictions and checkpoints will be written."""  ,		)
  parser.add_argument(
      """--fp16"""  ,		action="""store_true"""  ,		help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"""  ,		)

  parser.add_argument(
      """--fp16_opt_level"""  ,		type=__lowerCamelCase  ,		default="""O2"""  ,		help=(
          """For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."""
          """See details at https://nvidia.github.io/apex/amp.html"""
      )  ,		)
  parser.add_argument("""--n_tpu_cores"""  ,		dest="""tpu_cores"""  ,		type=__lowerCamelCase		)
  parser.add_argument("""--max_grad_norm"""  ,		dest="""gradient_clip_val"""  ,		default=1.0  ,		type=__lowerCamelCase  ,		help="""Max gradient norm"""		)
  parser.add_argument("""--do_train"""  ,		action="""store_true"""  ,		help="""Whether to run training."""		)
  parser.add_argument("""--do_predict"""  ,		action="""store_true"""  ,		help="""Whether to run predictions on the test set."""		)
  parser.add_argument(
      """--gradient_accumulation_steps"""  ,		dest="""accumulate_grad_batches"""  ,		type=__lowerCamelCase  ,		default=1  ,		help="""Number of updates steps to accumulate before performing a backward/update pass."""  ,		)
  parser.add_argument("""--seed"""  ,		type=__lowerCamelCase  ,		default=42  ,		help="""random seed for initialization"""		)
  parser.add_argument(
      """--data_dir"""  ,		default=__lowerCamelCase  ,		type=__lowerCamelCase  ,		required=__lowerCamelCase  ,		help="""The input data dir. Should contain the training files for the CoNLL-2003 NER task."""  ,		)







def     lowerCamelCase__				(   __lowerCamelCase      :					BaseTransformer  ,		__lowerCamelCase      :					argparse.Namespace  ,		__lowerCamelCase      :					Any=None  ,		__lowerCamelCase      :					Optional[Any]=True  ,		__lowerCamelCase      :					Tuple=None  ,		__lowerCamelCase      :					Optional[int]=[]  ,		__lowerCamelCase      :					int=None  ,		__lowerCamelCase      :					List[str]=None  ,		**__lowerCamelCase      :					List[Any]  ,		):
  pl.seed_everything(args.seed		)

  # init model
  __UpperCAmelCase							:     Optional[Any]									=  Path(model.hparams.output_dir		)
  odir.mkdir(exist_ok=__lowerCamelCase		)

  # add custom checkpoints
  if checkpoint_callback is None:
    __UpperCAmelCase							:     Tuple									=  pl.callbacks.ModelCheckpoint(
        filepath=args.output_dir  ,		prefix="""checkpoint"""  ,		monitor="""val_loss"""  ,		mode="""min"""  ,		save_top_k=1		)
  if early_stopping_callback:
    extra_callbacks.append(__lowerCamelCase		)
  if logging_callback is None:
    __UpperCAmelCase							:     int									=  LoggingCallback()

  __UpperCAmelCase							:     int									=  {}

  # TODO: remove with PyTorch 1.6 since pl uses native amp
  if args.fpaa:
    __UpperCAmelCase							:     Dict									=  16
    # train_params["amp_level"] = args.fp16_opt_level

  if args.gpus > 1:
    __UpperCAmelCase							:     List[str]									=  """auto"""  # "ddp"
    __UpperCAmelCase							:     Union[str, Any]									=  """ddp"""

  __UpperCAmelCase							:     Optional[int]									=  args.accumulate_grad_batches
  __UpperCAmelCase							:     Dict									=  None  # extra_train_kwargs.get("profiler", None) #get unwanted logs
  __UpperCAmelCase							:     Optional[int]									=  """auto"""

  __UpperCAmelCase							:     Optional[Any]									=  pl.Trainer.from_argparse_args(
      __lowerCamelCase  ,		weights_summary=__lowerCamelCase  ,		callbacks=[logging_callback] + extra_callbacks + [checkpoint_callback] + [InitCallback()]  ,		logger=__lowerCamelCase  ,		**__lowerCamelCase  ,		)

  if args.do_train:
    trainer.fit(__lowerCamelCase		)

  return trainer


