






import logging
import os
import sys
from dataclasses import dataclass, field
from typing import List, Optional

import torch
from datasets import Dataset
from torch import nn
from tqdm.auto import tqdm

from transformers import (
    AutoModelForSequenceClassification,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
    utils,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


SCREAMING_SNAKE_CASE								=  '\nDistills an NLI-based zero-shot classifier to a smaller, more efficient model with a fixed set of candidate class\nnames. Useful for speeding up zero-shot classification in cases where labeled training data is not available, but\nwhen only a single fixed set of classes is needed. Takes a teacher NLI model, student classifier model, unlabeled\ndataset, and set of K possible class names. Yields a single classifier with K outputs corresponding to the provided\nclass names.\n'

SCREAMING_SNAKE_CASE								=  logging.getLogger(__name__)
@dataclass
class 							A_      :






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     Optional[str]	=   field(
     default="roberta-large-mnli"	,				metadata={"help": "The NLI/zero-shot teacher model to be distilled."}     )
 _SCREAMING_SNAKE_CASE							:     Optional[str]	=   field(
     default="This example is {}."	,				metadata={
         "help": (
             "Template used to turn class names into mock hypotheses for teacher NLI model. Must include {{}}"
             "where class name is inserted."
         )
     }	,				)
 _SCREAMING_SNAKE_CASE							:     Optional[int]	=   field(
     default=3_2	,				metadata={"help": "Batch size for generating teacher predictions."}     )
 _SCREAMING_SNAKE_CASE							:     Optional[bool]	=   field(
     default=__lowerCamelCase	,				metadata={
         "help": (
             "Allow multiple classes to be true rather than forcing them to sum to 1 (sometimes called"
             "multi-class multi-label classification)."
         )
     }	,				)
 _SCREAMING_SNAKE_CASE							:     Optional[float]	=   field(
     default=1.0	,				metadata={"help": "Temperature applied to teacher softmax for distillation."}     )



@dataclass
class 							A_      :






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     Optional[str]	=   field(
     default="distilbert-base-uncased"	,				metadata={"help": "The NLI/zero-shot teacher model to be distilled."}     )



@dataclass
class 							A_      :






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     str	=   field(metadata={"help": "Text file with one unlabeled instance per line."}     )
 _SCREAMING_SNAKE_CASE							:     str	=   field(metadata={"help": "Text file with one class name per line."}     )
 _SCREAMING_SNAKE_CASE							:     bool	=   field(
     default=__lowerCamelCase	,				metadata={"help": "Whether to use one of the fast tokenizer (backed by the Rust tokenizers library) or not."}	,				)



@dataclass
class 							A_      (  __lowerCamelCase     ):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:     Optional[str]	=   field(
     default=__lowerCamelCase	,				metadata={"help": "The output directory where the model predictions and checkpoints will be written."}	,				)
 _SCREAMING_SNAKE_CASE							:     int	=   field(
     default=3_2	,				metadata={"help": "Batch size per GPU/TPU core/CPU for training."}     )
 _SCREAMING_SNAKE_CASE							:     int	=   field(
     default=1_2_8	,				metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}     )
 _SCREAMING_SNAKE_CASE							:     float	=   field(default=1.0	,				metadata={"help": "Total number of training epochs to perform."}     )
 _SCREAMING_SNAKE_CASE							:     bool	=   field(default=__lowerCamelCase	,				metadata={"help": "Whether to run training of student model."}     )
 _SCREAMING_SNAKE_CASE							:     bool	=   field(
     default=__lowerCamelCase	,				metadata={
         "help": (
             "Whether to evaluate the agreement of the final student predictions and the teacher predictions"
             "after training."
         )
     }	,				)
 _SCREAMING_SNAKE_CASE							:     Optional[int]	=   field(
     default=0	,				metadata={
         "help": (
             "Limit the total amount of checkpoints."
             "Deletes the older checkpoints in the output_dir. Default is 0 (no checkpoints)."
         )
     }	,				)



class 							A_      (  __lowerCamelCase     ):






 '''simple docstring'''




 def 	snake_case__			(		self							,					_A							,					_A							,					_A=False)	->						List[Any]:

     """simple docstring"""



     _UpperCAmelCase			: Tuple     					=			inputs['''labels''']
     _UpperCAmelCase			: Dict     					=			model(inputs['''input_ids''']							,					attention_mask=inputs['''attention_mask'''])
     _UpperCAmelCase			: Optional[int]     					=			outputs[0]

     _UpperCAmelCase			: Optional[int]     					=			-torch.sum(target_p * logits.log_softmax(dim=-1)							,					axis=-1).mean()

     if return_outputs:
         return loss, outputs

     return loss



def        _lowerCamelCase		(  __A      :							Optional[int]	) ->   int:
    _UpperCAmelCase			: Optional[Any]     					=			[]
    with open(__UpperCamelCase						,						'''r'''	) as f:
        for line in f:
            _UpperCAmelCase			: Tuple     					=			line.strip()
            if len(__UpperCamelCase	) > 0:
                lines.append(__UpperCamelCase	)
    return lines

def        _lowerCamelCase		(  __A      :							Any						,						__A      :							Tuple						,						__A      :							Union[str, Any]	) ->   Dict:
    _UpperCAmelCase			: int     					=			[]
    _UpperCAmelCase			: int     					=			[]
    for example in examples:
        for name in class_names:
            premises.append(__UpperCamelCase	)
            hypotheses.append(hypothesis_template.format(__UpperCamelCase	)	)
    return premises, hypotheses

def        _lowerCamelCase		(  __A      :							Optional[Any]	) ->   Optional[Any]:
    for label, ind in config.labelaid.items():
        if label.lower().startswith('''entail'''	):
            return ind
    logger.warning('''Could not identify entailment dimension from teacher config label2id. Setting to -1.'''	)
    return -1

def        _lowerCamelCase		(  __A      :							Any						,						__A      :							Optional[int]						,						__A      :							str						,						__A      :							Union[str, Any]						,						__A      :							List[str]						,						__A      :							int						,						__A      :							List[str]						,						__A      :							Any						,						__A      :							List[str]						,						__A      :							Union[str, Any]						,						) ->   Optional[int]:
    _UpperCAmelCase			: int     					=			AutoModelForSequenceClassification.from_pretrained(__UpperCamelCase	)
    _UpperCAmelCase			: Union[str, Any]     					=			model.config
    if not no_cuda and torch.cuda.is_available():
        _UpperCAmelCase			: List[Any]     					=			nn.DataParallel(model.cuda()	)
        batch_size *= len(model.device_ids	)
    _UpperCAmelCase			: Tuple     					=			AutoTokenizer.from_pretrained(__UpperCamelCase						,						use_fast=__UpperCamelCase	)

    _UpperCAmelCase					,	_UpperCAmelCase			: Dict     					=			get_premise_hypothesis_pairs(__UpperCamelCase						,						__UpperCamelCase						,						__UpperCamelCase	)
    _UpperCAmelCase			: List[Any]     					=			[]

    for i in tqdm(range(0						,						len(__UpperCamelCase	)						,						__UpperCamelCase	)	):
        _UpperCAmelCase			: List[str]     					=			premises[i : i + batch_size]
        _UpperCAmelCase			: int     					=			hypotheses[i : i + batch_size]

        _UpperCAmelCase			: Dict     					=			tokenizer(
            __UpperCamelCase						,						__UpperCamelCase						,						padding=__UpperCamelCase						,						truncation='''only_first'''						,						return_tensors='''pt'''						,						)

        with torch.cuda.amp.autocast(enabled=__UpperCamelCase	):
            with torch.no_grad():
                _UpperCAmelCase			: List[Any]     					=			model(**__UpperCamelCase	)
        logits.append(outputs.logits.detach().cpu().float()	)

    _UpperCAmelCase			: List[str]     					=			get_entailment_id(__UpperCamelCase	)
    _UpperCAmelCase			: List[str]     					=			-1 if entail_id == 0 else 0
    _UpperCAmelCase			: Dict     					=			torch.cat(__UpperCamelCase						,						dim=0	)  # N*K x 3
    _UpperCAmelCase			: Any     					=			logits.reshape(len(__UpperCamelCase	)						,						len(__UpperCamelCase	)						,						-1	)[..., [contr_id, entail_id]]  # N x K x 2

    if multi_label:
        # softmax over (contr, entail) logits for each class independently
        _UpperCAmelCase			: Tuple     					=			(nli_logits / temperature).softmax(-1	)
    else:
        # softmax over entail logits across classes s.t. class probabilities sum to 1.
        _UpperCAmelCase			: List[Any]     					=			(nli_logits / temperature).softmax(1	)

    return nli_prob[..., 1]  # N x K

def        _lowerCamelCase		(  ) ->   int:
    _UpperCAmelCase			: List[Any]     					=			HfArgumentParser(
        (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)						,						description=__UpperCamelCase						,						)

    if len(sys.argv	) == 2 and sys.argv[1].endswith('''.json'''	):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        _UpperCAmelCase					,	_UpperCAmelCase					,	_UpperCAmelCase					,	_UpperCAmelCase			: Optional[Any]     					=			parser.parse_json_file(
            json_file=os.path.abspath(sys.argv[1]	)	)
    else:
        _UpperCAmelCase					,	_UpperCAmelCase					,	_UpperCAmelCase					,	_UpperCAmelCase			: List[Any]     					=			parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    _UpperCAmelCase			: Dict     					=			None
    if os.path.isdir(training_args.output_dir	) and training_args.do_train and not training_args.overwrite_output_dir:
        _UpperCAmelCase			: Any     					=			get_last_checkpoint(training_args.output_dir	)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir	)	) > 0:
            raise ValueError(
                f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                '''Use --overwrite_output_dir to overcome.'''	)
        elif last_checkpoint is not None:
            logger.info(
                f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''	)

    # Setup logging
    logging.basicConfig(
        format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''						,						datefmt='''%m/%d/%Y %H:%M:%S'''						,						handlers=[logging.StreamHandler(sys.stdout	)]						,						)
    logger.setLevel(logging.INFO if is_main_process(training_args.local_rank	) else logging.WARN	)

    # Log on each process the small summary:
    logger.warning(
        f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
        + f'''distributed training: {bool(training_args.local_rank != -1	)}, 16-bits training: {training_args.fpaa}'''	)
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank	):
        utils.logging.set_verbosity_info()
        utils.logging.enable_default_handler()
        utils.logging.enable_explicit_format()

    if training_args.local_rank != -1:
        raise ValueError('''Distributed training is not currently supported.'''	)
    if training_args.tpu_num_cores is not None:
        raise ValueError('''TPU acceleration is not currently supported.'''	)

    logger.info(f'''Training/evaluation parameters {training_args}'''	)

    # Set seed before initializing model.
    set_seed(training_args.seed	)

    # 1. read in data
    _UpperCAmelCase			: List[Any]     					=			read_lines(data_args.data_file	)
    _UpperCAmelCase			: str     					=			read_lines(data_args.class_names_file	)

    # 2. get teacher predictions and load into dataset
    logger.info('''Generating predictions from zero-shot teacher model'''	)
    _UpperCAmelCase			: Optional[int]     					=			get_teacher_predictions(
        teacher_args.teacher_name_or_path						,						__UpperCamelCase						,						__UpperCamelCase						,						teacher_args.hypothesis_template						,						teacher_args.teacher_batch_size						,						teacher_args.temperature						,						teacher_args.multi_label						,						data_args.use_fast_tokenizer						,						training_args.no_cuda						,						training_args.fpaa						,						)
    _UpperCAmelCase			: Tuple     					=			Dataset.from_dict(
        {
            '''text''': examples,
            '''labels''': teacher_soft_preds,
        }	)

    # 3. create student
    logger.info('''Initializing student model'''	)
    _UpperCAmelCase			: List[str]     					=			AutoModelForSequenceClassification.from_pretrained(
        student_args.student_name_or_path						,						num_labels=len(__UpperCamelCase	)	)
    _UpperCAmelCase			: List[str]     					=			AutoTokenizer.from_pretrained(student_args.student_name_or_path						,						use_fast=data_args.use_fast_tokenizer	)
    _UpperCAmelCase			: List[Any]     					=			dict(enumerate(__UpperCamelCase	)	)
    _UpperCAmelCase			: Optional[int]     					=			{label: i for i, label in enumerate(__UpperCamelCase	)}

    # 4. train student on teacher predictions
    _UpperCAmelCase			: str     					=			dataset.map(__UpperCamelCase						,						input_columns='''text'''	)
    dataset.set_format('''torch'''	)

    def compute_metrics(__A      :							Any						,						__A      :							Dict=False	):
        _UpperCAmelCase			: int     					=			p.predictions.argmax(-1	)
        _UpperCAmelCase			: List[Any]     					=			p.label_ids.argmax(-1	)  # "label_ids" are actually distributions
        return {"agreement": (preds == proxy_labels).mean().item()}

    _UpperCAmelCase			: int     					=			DistillationTrainer(
        model=__UpperCamelCase						,						tokenizer=__UpperCamelCase						,						args=__UpperCamelCase						,						train_dataset=__UpperCamelCase						,						compute_metrics=__UpperCamelCase						,						)

    if training_args.do_train:
        logger.info('''Training student model on teacher predictions'''	)
        trainer.train()

    if training_args.do_eval:
        _UpperCAmelCase			: Union[str, Any]     					=			trainer.evaluate(eval_dataset=__UpperCamelCase	)['''eval_agreement''']
        logger.info(f'''Agreement of student and teacher predictions: {agreement * 100:0.2f}%'''	)

    trainer.save_model()


if __name__ == "__main__":
  main()












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							,					_A)	->						List[Any]:

     """simple docstring"""



     _UpperCAmelCase			: List[Any]     					=			foo


 def __call__(		self)	->						List[Any]:

     """simple docstring"""



     return self.foo



class 							A_      (  datasets.Dataset     ):






 '''simple docstring'''




 @fingerprint_transform(inplace=_A)
 def 	snake_case__			(		self							,					_A							,					*_A							,					**_A)	->						str:

     """simple docstring"""



     return DatasetChild(self.data							,					fingerprint=_A)


 @fingerprint_transform(inplace=_A)
 def 	snake_case__			(		self							,					_A							,					*_A							,					**_A)	->						Optional[Any]:

     """simple docstring"""



     return DatasetChild(self.data							,					fingerprint=_A)



class 							A_      :






 '''simple docstring'''




 def __init__(		self							,					_A)	->						List[str]:

     """simple docstring"""



     _UpperCAmelCase			: Union[str, Any]     					=			callable


 def __call__(		self							,					*_A							,					**_A)	->						Optional[int]:

     """simple docstring"""



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


 def __getstate__(		self)	->						Optional[Any]:

     """simple docstring"""



     raise pickle.PicklingError()



class 							A_      (  __lowercase     ):






 '''simple docstring'''




 @require_transformers
 @pytest.mark.integration
 def 	snake_case__			(		self)	->						Optional[Any]:

     """simple docstring"""



     from transformers import AutoTokenizer

     def encode(_A):
         return tokenizer(_A)

     # TODO: add hash consistency tests across sessions
     _UpperCAmelCase			: Tuple     					=			AutoTokenizer.from_pretrained('''bert-base-uncased''')
     _UpperCAmelCase			: int     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Optional[int]     					=			mda(datasets.utils.py_utils.dumps(lambda _A: tokenizer(_A))).hexdigest()
     _UpperCAmelCase			: Dict     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Union[str, Any]     					=			AutoTokenizer.from_pretrained('''bert-base-cased''')
     _UpperCAmelCase			: int     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: str     					=			mda(datasets.utils.py_utils.dumps(lambda _A: tokenizer(_A))).hexdigest()
     _UpperCAmelCase			: Any     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Union[str, Any]     					=			AutoTokenizer.from_pretrained('''bert-base-uncased''')
     _UpperCAmelCase			: Optional[int]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(lambda _A: tokenizer(_A))).hexdigest()
     _UpperCAmelCase			: Optional[int]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 @require_transformers
 @pytest.mark.integration
 def 	snake_case__			(		self)	->						Any:

     """simple docstring"""



     from transformers import AutoTokenizer

     _UpperCAmelCase			: Union[str, Any]     					=			AutoTokenizer.from_pretrained('''gpt2''')
     _UpperCAmelCase			: Union[str, Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     tokenizer('''Hello world !''')  # call once to change the tokenizer's cache
     _UpperCAmelCase			: Optional[int]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)


 @require_regex
 def 	snake_case__			(		self)	->						Dict:

     """simple docstring"""



     import regex

     _UpperCAmelCase			: Optional[int]     					=			regex.Regex('''foo''')
     _UpperCAmelCase			: Union[str, Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: int     					=			regex.Regex('''bar''')
     _UpperCAmelCase			: int     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Optional[Any]     					=			regex.Regex('''foo''')
     _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)



class 							A_      (  __lowercase     ):






 '''simple docstring'''




 def 	snake_case__			(		self)	->						Optional[Any]:

     """simple docstring"""



     def func():
         return foo

     _UpperCAmelCase			: List[str]     					=			[0]
     _UpperCAmelCase			: Dict     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: List[str]     					=			[1]
     _UpperCAmelCase			: Any     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Any     					=			[0]
     _UpperCAmelCase			: List[Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						List[Any]:

     """simple docstring"""



     def func():
         pass

     _UpperCAmelCase			: Union[str, Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()

     def func():
         pass

     _UpperCAmelCase			: Dict     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase			: str     					=			mda(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest()
     _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(Foo([1]))).hexdigest()
     _UpperCAmelCase			: Dict     					=			mda(datasets.utils.py_utils.dumps(Foo([0]))).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						int:

     """simple docstring"""



     _UpperCAmelCase			: Any     					=			mda(datasets.utils.py_utils.dumps(Foo([0]).__call__)).hexdigest()
     _UpperCAmelCase			: int     					=			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(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						int:

     """simple docstring"""



     _UpperCAmelCase			: List[str]     					=			(
         '''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(*_A):
         if hasattr(args[-3]							,					'''encode'''):
             _UpperCAmelCase			: Tuple     					=			list(_A)
             _UpperCAmelCase			: Optional[int]     					=			args[-3].encode()  # co_lnotab
             _UpperCAmelCase			: List[str]     					=			args[-10].encode()  # co_code
         if hasattr(_A							,					'''co_posonlyargcount'''):
             if len(_A) == 16:
                 return CodeType(*_A)
             elif len(_A) == 15:
                 return CodeType(args[0]							,					0							,					*args[1:])
             return CodeType(args[0]							,					0							,					0							,					*args[1:])
         elif hasattr(_A							,					'''co_kwonlyargcount'''):
             if len(_A) == 16:
                 return CodeType(args[0]							,					*args[2:])
             elif len(_A) == 15:
                 return CodeType(*_A)
             return CodeType(args[0]							,					0							,					*args[1:])
         if len(_A) == 16:
             return CodeType(args[0]							,					*args[3:])
         elif len(_A) == 15:
             return CodeType(args[0]							,					*args[2:])
         return CodeType(*_A)

     def create_ipython_func(_A							,					_A):
         def func():
             return returned_obj

         _UpperCAmelCase			: List[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			: int     					=			_create_code_pyaa(
                 *[getattr(_A							,					_A) if k != '''co_filename''' else co_filename for k in code_args_pyaa])
         else:
             _UpperCAmelCase			: List[str]     					=			code.replace(co_filename=_A)
         return FunctionType(_A							,					func.__globals__							,					func.__name__							,					func.__defaults__							,					func.__closure__)

     _UpperCAmelCase					,	_UpperCAmelCase			: List[Any]     					=			'''<ipython-input-2-e0383a102aae>''', [0]
     _UpperCAmelCase			: Tuple     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     _UpperCAmelCase					,	_UpperCAmelCase			: List[Any]     					=			'''<ipython-input-2-e0383a102aae>''', [1]
     _UpperCAmelCase			: Tuple     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     _UpperCAmelCase					,	_UpperCAmelCase			: List[Any]     					=			'''<ipython-input-5-713f6613acf3>''', [0]
     _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)

     _UpperCAmelCase					,	_UpperCAmelCase			: Union[str, Any]     					=			os.path.join(gettempdir()							,					'''ipykernel_12345'''							,					'''321456789.py'''), [0]
     _UpperCAmelCase			: Union[str, Any]     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     _UpperCAmelCase					,	_UpperCAmelCase			: str     					=			os.path.join(gettempdir()							,					'''ipykernel_12345'''							,					'''321456789.py'''), [1]
     _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     _UpperCAmelCase					,	_UpperCAmelCase			: Union[str, Any]     					=			os.path.join(gettempdir()							,					'''ipykernel_12345'''							,					'''654123987.py'''), [0]
     _UpperCAmelCase			: Any     					=			mda(datasets.utils.py_utils.dumps(create_ipython_func(_A							,					_A))).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase					,	_UpperCAmelCase			: List[str]     					=			[0], [1]

     def func():
         return foo, bar

     _UpperCAmelCase			: List[str]     					=			'''__main__'''

     def globalvars_mocka_side_effect(_A							,					*_A							,					**_A):
         return {"foo": foo, "bar": bar}

     def globalvars_mocka_side_effect(_A							,					*_A							,					**_A):
         return {"bar": bar, "foo": foo}

     with patch('''dill.detect.globalvars'''							,					side_effect=_A) as globalvars_mocka:
         _UpperCAmelCase			: Optional[Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
         self.assertGreater(globalvars_mocka.call_count							,					0)
     with patch('''dill.detect.globalvars'''							,					side_effect=_A) as globalvars_mocka:
         _UpperCAmelCase			: List[str]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
         self.assertGreater(globalvars_mocka.call_count							,					0)
     self.assertEqual(_A							,					_A)



class 							A_      (  __lowercase     ):






 '''simple docstring'''




 def 	snake_case__			(		self)	->						List[str]:

     """simple docstring"""



     _UpperCAmelCase			: Optional[int]     					=			Hasher.hash('''hello''')
     _UpperCAmelCase			: Union[str, Any]     					=			Hasher.hash('''hello''')
     _UpperCAmelCase			: Tuple     					=			Hasher.hash('''there''')
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						List[Any]:

     """simple docstring"""



     _UpperCAmelCase			: Union[str, Any]     					=			Hasher.hash(Foo('''hello'''))
     _UpperCAmelCase			: Optional[int]     					=			Hasher.hash(Foo('''hello'''))
     _UpperCAmelCase			: Any     					=			Hasher.hash(Foo('''there'''))
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						Optional[int]:

     """simple docstring"""



     _UpperCAmelCase			: List[Any]     					=			Hasher()
     for x in ["hello", Foo('''hello''')]:
         hasher.update(_A)
     _UpperCAmelCase			: Optional[Any]     					=			hasher.hexdigest()
     _UpperCAmelCase			: Optional[Any]     					=			Hasher()
     for x in ["hello", Foo('''hello''')]:
         hasher.update(_A)
     _UpperCAmelCase			: Optional[int]     					=			hasher.hexdigest()
     _UpperCAmelCase			: Optional[int]     					=			Hasher()
     for x in ["there", Foo('''there''')]:
         hasher.update(_A)
     _UpperCAmelCase			: Optional[int]     					=			hasher.hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 def 	snake_case__			(		self)	->						Optional[Any]:

     """simple docstring"""



     with self.assertRaises(pickle.PicklingError):
         Hasher.hash(UnpicklableCallable(Foo('''hello''')))


 def 	snake_case__			(		self)	->						int:

     """simple docstring"""



     _UpperCAmelCase			: List[str]     					=			'''abc'''
     _UpperCAmelCase			: List[Any]     					=			[string, string]  # two strings have the same ids
     _UpperCAmelCase			: int     					=			[string, string]
     _UpperCAmelCase			: List[str]     					=			json.loads(f'''["{string}", "{string}"]''')  # two strings have different ids
     self.assertIs(obja[0]							,					_A)
     self.assertIs(obja[0]							,					obja[1])
     self.assertIs(obja[0]							,					_A)
     self.assertIs(obja[0]							,					obja[1])
     self.assertIsNot(obja[0]							,					_A)
     self.assertIsNot(obja[0]							,					obja[1])
     _UpperCAmelCase			: List[Any]     					=			Hasher.hash(_A)
     _UpperCAmelCase			: int     					=			Hasher.hash(_A)
     _UpperCAmelCase			: List[str]     					=			Hasher.hash(_A)
     self.assertEqual(_A							,					_A)
     self.assertEqual(_A							,					_A)


 @require_tiktoken
 def 	snake_case__			(		self)	->						Any:

     """simple docstring"""



     import tiktoken

     _UpperCAmelCase			: List[str]     					=			tiktoken.get_encoding('''gpt2''')
     _UpperCAmelCase			: Dict     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: List[str]     					=			tiktoken.get_encoding('''r50k_base''')
     _UpperCAmelCase			: Optional[Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: List[str]     					=			tiktoken.get_encoding('''gpt2''')
     _UpperCAmelCase			: Tuple     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)


 @require_torch
 def 	snake_case__			(		self)	->						Optional[int]:

     """simple docstring"""



     import torch

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


 @require_spacy
 @require_spacy_model('''en_core_web_sm''')
 @require_spacy_model('''fr_core_news_sm''')
 @pytest.mark.integration
 def 	snake_case__			(		self)	->						Tuple:

     """simple docstring"""



     import spacy

     _UpperCAmelCase			: Optional[int]     					=			spacy.load('''en_core_web_sm''')
     _UpperCAmelCase			: Union[str, Any]     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: Dict     					=			spacy.load('''fr_core_news_sm''')
     _UpperCAmelCase			: str     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     _UpperCAmelCase			: List[str]     					=			spacy.load('''en_core_web_sm''')
     _UpperCAmelCase			: Tuple     					=			mda(datasets.utils.py_utils.dumps(_A)).hexdigest()
     self.assertEqual(_A							,					_A)
     self.assertNotEqual(_A							,					_A)



@pytest.mark.integration
def        _lowerCamelCase		(  __A      :							Path	) ->   int:
    _UpperCAmelCase			: Union[str, Any]     					=			tmp_path / '''dir1'''
    _UpperCAmelCase			: int     					=			tmp_path / '''dir2'''
    dira.mkdir()
    dira.mkdir()
    _UpperCAmelCase			: List[str]     					=			'''script.py'''
    _UpperCAmelCase			: str     					=			dedent(
        '''
    from datasets.fingerprint import Hasher
    def foo():
        pass
    print(Hasher.hash(foo))
    '''	)
    _UpperCAmelCase			: Optional[Any]     					=			dira / script_filename
    _UpperCAmelCase			: List[Any]     					=			dira / script_filename
    with script_patha.open('''w'''	) as f:
        f.write(__A	)
    with script_patha.open('''w'''	) as f:
        f.write(__A	)
    _UpperCAmelCase			: Union[str, Any]     					=			subprocess.check_output(['''python''', str(__A	)]	)
    _UpperCAmelCase			: str     					=			subprocess.check_output(['''python''', str(__A	)]	)
    assert fingerprinta == fingerprinta

def        _lowerCamelCase		(  ) ->   Optional[int]:
    _UpperCAmelCase			: Union[str, Any]     					=			{'''a''': [0, 1, 2]}
    _UpperCAmelCase			: Union[str, Any]     					=			DatasetChild(InMemoryTable.from_pydict(__A	)	)
    _UpperCAmelCase			: Optional[Any]     					=			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		(  ) ->   str:
    _UpperCAmelCase			: str     					=			{'''a''': [0, 1, 2]}
    class 							A_      (  datasets.Dataset     ):






     '''simple docstring'''




     @fingerprint_transform(inplace=_A)
     def 	snake_case__			(		self							,					_A)	->						Optional[int]:

         """simple docstring"""



         return DummyDatasetChild(self.data							,					fingerprint=_A)



    _UpperCAmelCase			: Tuple     					=			DummyDatasetChild(InMemoryTable.from_pydict(__A	)	).func()
    class 							A_      (  datasets.Dataset     ):






     '''simple docstring'''




     @fingerprint_transform(inplace=_A							,					version='''1.0.0''')
     def 	snake_case__			(		self							,					_A)	->						List[str]:

         """simple docstring"""



         return DummyDatasetChild(self.data							,					fingerprint=_A)



    _UpperCAmelCase			: str     					=			DummyDatasetChild(InMemoryTable.from_pydict(__A	)	).func()
    class 							A_      (  datasets.Dataset     ):






     '''simple docstring'''




     @fingerprint_transform(inplace=_A							,					version='''2.0.0''')
     def 	snake_case__			(		self							,					_A)	->						List[str]:

         """simple docstring"""



         return DummyDatasetChild(self.data							,					fingerprint=_A)



    _UpperCAmelCase			: str     					=			DummyDatasetChild(InMemoryTable.from_pydict(__A	)	).func()

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


def        _lowerCamelCase		(  ) ->   List[str]:
    # AttributeError: module 'dill._dill' has no attribute 'stack'
    _UpperCAmelCase			: Dict     					=			Hasher()
    hasher.update(lambda __A	: x	)




