



'''simple docstring'''







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


lowercase__  :	List[Any]            =      '\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'

lowercase__  :	str            =      logging.getLogger(__name__)

@dataclass
class    lowerCamelCase_				:






   '''simple docstring'''

   A			:  Optional[str]					=						field(
       default="roberta-large-mnli"       ,     metadata={"help": "The NLI/zero-shot teacher model to be distilled."}	)
   A			:  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."
           )
       }       ,     )
   A			:  Optional[int]					=						field(
       default=32       ,     metadata={"help": "Batch size for generating teacher predictions."}	)
   A			:  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)."
           )
       }       ,     )
   A			:  Optional[float]					=						field(
       default=1.0       ,     metadata={"help": "Temperature applied to teacher softmax for distillation."}	)

@dataclass
class    lowerCamelCase_				:






   '''simple docstring'''

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

@dataclass
class    lowerCamelCase_				:






   '''simple docstring'''

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

@dataclass
class    lowerCamelCase_				(						lowerCAmelCase_	):






   '''simple docstring'''

   A			:  Optional[str]					=						field(
       default=lowerCAmelCase_       ,     metadata={"help": "The output directory where the model predictions and checkpoints will be written."}       ,     )
   A			:  int					=						field(
       default=32       ,     metadata={"help": "Batch size per GPU/TPU core/CPU for training."}	)
   A			:  int					=						field(
       default=128       ,     metadata={"help": "Batch size per GPU/TPU core/CPU for evaluation."}	)
   A			:  float					=						field(default=1.0       ,     metadata={"help": "Total number of training epochs to perform."}	)
   A			:  bool					=						field(default=lowerCAmelCase_       ,     metadata={"help": "Whether to run training of student model."}	)
   A			:  bool					=						field(
       default=lowerCAmelCase_       ,     metadata={
           "help": (
               "Whether to evaluate the agreement of the final student predictions and the teacher predictions"
               "after training."
           )
       }       ,     )
   A			:  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    lowerCamelCase_				(						lowerCAmelCase_	):






   '''simple docstring'''

   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase=False			):
       UpperCamelCase__	     =      inputs["labels"]
       UpperCamelCase__	     =      model(inputs["input_ids"]  ,    attention_mask=inputs["attention_mask"]			)
       UpperCamelCase__	     =      outputs[0]

       UpperCamelCase__	     =      -torch.sum(target_p * logits.log_softmax(dim=-1			)  ,    axis=-1			).mean()

       if return_outputs:
           return loss, outputs

       return loss





def     snake_case__			(lowerCAmelCase_						):
    UpperCamelCase__	     =      []
    with open(lowerCAmelCase_       ,	"r"						) as f:
        for line in f:
            UpperCamelCase__	     =      line.strip()
            if len(lowerCAmelCase_						) > 0:
                lines.append(lowerCAmelCase_						)
    return lines





def     snake_case__			(lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_						):
    UpperCamelCase__	     =      []
    UpperCamelCase__	     =      []
    for example in examples:
        for name in class_names:
            premises.append(lowerCAmelCase_						)
            hypotheses.append(hypothesis_template.format(lowerCAmelCase_						)						)
    return premises, hypotheses





def     snake_case__			(lowerCAmelCase_						):
    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     snake_case__			(lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	):
    UpperCamelCase__	     =      AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase_						)
    UpperCamelCase__	     =      model.config
    if not no_cuda and torch.cuda.is_available():
        UpperCamelCase__	     =      nn.DataParallel(model.cuda()						)
        batch_size *= len(model.device_ids						)
    UpperCamelCase__	     =      AutoTokenizer.from_pretrained(lowerCAmelCase_       ,	use_fast=lowerCAmelCase_						)

    UpperCamelCase__     ,	UpperCamelCase__	     =      get_premise_hypothesis_pairs(lowerCAmelCase_       ,	lowerCAmelCase_       ,	lowerCAmelCase_						)
    UpperCamelCase__	     =      []

    for i in tqdm(range(0       ,	len(lowerCAmelCase_						)       ,	lowerCAmelCase_						)						):
        UpperCamelCase__	     =      premises[i : i + batch_size]
        UpperCamelCase__	     =      hypotheses[i : i + batch_size]

        UpperCamelCase__	     =      tokenizer(
            lowerCAmelCase_       ,	lowerCAmelCase_       ,	padding=lowerCAmelCase_       ,	truncation="only_first"       ,	return_tensors="pt"       ,	)

        with torch.cuda.amp.autocast(enabled=lowerCAmelCase_						):
            with torch.no_grad():
                UpperCamelCase__	     =      model(**lowerCAmelCase_						)
        logits.append(outputs.logits.detach().cpu().float()						)

    UpperCamelCase__	     =      get_entailment_id(lowerCAmelCase_						)
    UpperCamelCase__	     =      -1 if entail_id == 0 else 0
    UpperCamelCase__	     =      torch.cat(lowerCAmelCase_       ,	dim=0						)  # N*K x 3
    UpperCamelCase__	     =      logits.reshape(len(lowerCAmelCase_						)       ,	len(lowerCAmelCase_						)       ,	-1						)[..., [contr_id, entail_id]]  # N x K x 2

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

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





def     snake_case__			():
    UpperCamelCase__	     =      HfArgumentParser(
        (DataTrainingArguments, TeacherModelArguments, StudentModelArguments, DistillTrainingArguments)       ,	description=lowerCAmelCase_       ,	)

    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__	     =      parser.parse_json_file(
            json_file=os.path.abspath(sys.argv[1]						)						)
    else:
        UpperCamelCase__     ,	UpperCamelCase__     ,	UpperCamelCase__     ,	UpperCamelCase__	     =      parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    UpperCamelCase__	     =      None
    if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
        UpperCamelCase__	     =      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__	     =      read_lines(data_args.data_file						)
    UpperCamelCase__	     =      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__	     =      get_teacher_predictions(
        teacher_args.teacher_name_or_path       ,	lowerCAmelCase_       ,	lowerCAmelCase_       ,	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__	     =      Dataset.from_dict(
        {
            "text": examples,
            "labels": teacher_soft_preds,
        }						)

    # 3. create student
    logger.info("Initializing student model"						)
    UpperCamelCase__	     =      AutoModelForSequenceClassification.from_pretrained(
        student_args.student_name_or_path       ,	num_labels=len(lowerCAmelCase_						)						)
    UpperCamelCase__	     =      AutoTokenizer.from_pretrained(student_args.student_name_or_path       ,	use_fast=data_args.use_fast_tokenizer						)
    UpperCamelCase__	     =      dict(enumerate(lowerCAmelCase_						)						)
    UpperCamelCase__	     =      {label: i for i, label in enumerate(lowerCAmelCase_						)}

    # 4. train student on teacher predictions
    UpperCamelCase__	     =      dataset.map(lowerCAmelCase_       ,	input_columns="text"						)
    dataset.set_format("torch"						)

    def compute_metrics(lowerCAmelCase_       ,	lowerCAmelCase_=False						):
        UpperCamelCase__	     =      p.predictions.argmax(-1						)
        UpperCamelCase__	     =      p.label_ids.argmax(-1						)  # "label_ids" are actually distributions
        return {"agreement": (preds == proxy_labels).mean().item()}

    UpperCamelCase__	     =      DistillationTrainer(
        model=lowerCAmelCase_       ,	tokenizer=lowerCAmelCase_       ,	args=lowerCAmelCase_       ,	train_dataset=lowerCAmelCase_       ,	compute_metrics=lowerCAmelCase_       ,	)

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

    if training_args.do_eval:
        UpperCamelCase__	     =      trainer.evaluate(eval_dataset=lowerCAmelCase_						)["eval_agreement"]
        logger.info(F'Agreement of student and teacher predictions: {agreement * 1_00:0.2f}%'						)

    trainer.save_model()


if __name__ == "__main__":
      main()









'''simple docstring'''







import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


lowercase__  :	str            =      logging.get_logger(__name__)

@dataclass
class    lowerCamelCase_				:






   '''simple docstring'''

   A			:  str
   A			:  str
   A			:  Optional[str]					=						None
   A			:  Optional[str]					=						None


   def 						_UpperCamelCase							(	self			):
       return json.dumps(dataclasses.asdict(self			)  ,    indent=2			) + "\n"

@dataclass(frozen=lowerCAmelCase_	)
class    lowerCamelCase_				:






   '''simple docstring'''

   A			:  List[int]
   A			:  Optional[List[int]]					=						None
   A			:  Optional[List[int]]					=						None
   A			:  Optional[Union[int, float]]					=						None


   def 						_UpperCamelCase							(	self			):
       return json.dumps(dataclasses.asdict(self			)			) + "\n"

class    lowerCamelCase_				:






   '''simple docstring'''

   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self			):
       raise NotImplementedError()


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase			):
       if len(self.get_labels()			) > 1:
           UpperCamelCase__	     =      self.get_labels()[int(example.label			)]
       return example







   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=None			):
       with open(__UpperCamelCase  ,    "r"  ,    encoding="utf-8-sig"			) as f:
           return list(csv.reader(__UpperCamelCase  ,    delimiter="\t"  ,    quotechar=__UpperCamelCase			)			)

class    lowerCamelCase_				(						lowerCAmelCase_	):






   '''simple docstring'''

   def __init__(	self  ,    __UpperCamelCase=None  ,    __UpperCamelCase=None  ,    __UpperCamelCase="classification"  ,    __UpperCamelCase=False			):
       UpperCamelCase__	     =      [] if labels is None else labels
       UpperCamelCase__	     =      [] if examples is None else examples
       UpperCamelCase__	     =      mode
       UpperCamelCase__	     =      verbose


   def __len__(	self			):
       return len(self.examples			)


   def __getitem__(	self  ,    __UpperCamelCase			):
       if isinstance(__UpperCamelCase  ,    __UpperCamelCase			):
           return SingleSentenceClassificationProcessor(labels=self.labels  ,    examples=self.examples[idx]			)
       return self.examples[idx]


   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=""  ,    __UpperCamelCase=0  ,    __UpperCamelCase=1  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    **__UpperCamelCase			):
       UpperCamelCase__	     =      cls(**__UpperCamelCase			)
       processor.add_examples_from_csv(
           __UpperCamelCase  ,    split_name=__UpperCamelCase  ,    column_label=__UpperCamelCase  ,    column_text=__UpperCamelCase  ,    column_id=__UpperCamelCase  ,    skip_first_row=__UpperCamelCase  ,    overwrite_labels=__UpperCamelCase  ,    overwrite_examples=__UpperCamelCase  ,    )
       return processor


   @classmethod
   def 						_UpperCamelCase							(	cls  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    **__UpperCamelCase			):
       UpperCamelCase__	     =      cls(**__UpperCamelCase			)
       processor.add_examples(__UpperCamelCase  ,    labels=__UpperCamelCase			)
       return processor


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=""  ,    __UpperCamelCase=0  ,    __UpperCamelCase=1  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False  ,    ):
       UpperCamelCase__	     =      self._read_tsv(__UpperCamelCase			)
       if skip_first_row:
           UpperCamelCase__	     =      lines[1:]
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      []
       for i, line in enumerate(__UpperCamelCase			):
           texts.append(line[column_text]			)
           labels.append(line[column_label]			)
           if column_id is not None:
               ids.append(line[column_id]			)
           else:
               UpperCamelCase__	     =      f'{split_name}-{i}' if split_name else str(__UpperCamelCase			)
               ids.append(__UpperCamelCase			)

       return self.add_examples(
           __UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase  ,    overwrite_labels=__UpperCamelCase  ,    overwrite_examples=__UpperCamelCase			)


   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=False			):
       if labels is not None and len(__UpperCamelCase			) != len(__UpperCamelCase			):
           raise ValueError(
               f'Text and labels have mismatched lengths {len(__UpperCamelCase			)} and {len(__UpperCamelCase			)}'			)
       if ids is not None and len(__UpperCamelCase			) != len(__UpperCamelCase			):
           raise ValueError(f'Text and ids have mismatched lengths {len(__UpperCamelCase			)} and {len(__UpperCamelCase			)}'			)
       if ids is None:
           UpperCamelCase__	     =      [None] * len(__UpperCamelCase			)
       if labels is None:
           UpperCamelCase__	     =      [None] * len(__UpperCamelCase			)
       UpperCamelCase__	     =      []
       UpperCamelCase__	     =      set()
       for text_or_text_and_label, label, guid in zip(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			):
           if isinstance(__UpperCamelCase  ,    (tuple, list)			) and label is None:
               UpperCamelCase__     ,	UpperCamelCase__	     =      text_or_text_and_label
           else:
               UpperCamelCase__	     =      text_or_text_and_label
           added_labels.add(__UpperCamelCase			)
           examples.append(InputExample(guid=__UpperCamelCase  ,    text_a=__UpperCamelCase  ,    text_b=__UpperCamelCase  ,    label=__UpperCamelCase			)			)

       # Update examples
       if overwrite_examples:
           UpperCamelCase__	     =      examples
       else:
           self.examples.extend(__UpperCamelCase			)

       # Update labels
       if overwrite_labels:
           UpperCamelCase__	     =      list(__UpperCamelCase			)
       else:
           UpperCamelCase__	     =      list(set(self.labels			).union(__UpperCamelCase			)			)

       return self.examples







   def 						_UpperCamelCase							(	self  ,    __UpperCamelCase  ,    __UpperCamelCase=None  ,    __UpperCamelCase=False  ,    __UpperCamelCase=0  ,    __UpperCamelCase=True  ,    __UpperCamelCase=None  ,    ):
       if max_length is None:
           UpperCamelCase__	     =      tokenizer.max_len

       UpperCamelCase__	     =      {label: i for i, label in enumerate(self.labels			)}

       UpperCamelCase__	     =      []
       for ex_index, example in enumerate(self.examples			):
           if ex_index % 1_00_00 == 0:
               logger.info(f'Tokenizing example {ex_index}'			)

           UpperCamelCase__	     =      tokenizer.encode(
               example.text_a  ,    add_special_tokens=__UpperCamelCase  ,    max_length=min(__UpperCamelCase  ,    tokenizer.max_len			)  ,    )
           all_input_ids.append(__UpperCamelCase			)

       UpperCamelCase__	     =      max(len(__UpperCamelCase			) for input_ids in all_input_ids			)

       UpperCamelCase__	     =      []
       for ex_index, (input_ids, example) in enumerate(zip(__UpperCamelCase  ,    self.examples			)			):
           if ex_index % 1_00_00 == 0:
               logger.info(f'Writing example {ex_index}/{len(self.examples			)}'			)
           # The mask has 1 for real tokens and 0 for padding tokens. Only real
           # tokens are attended to.
           UpperCamelCase__	     =      [1 if mask_padding_with_zero else 0] * len(__UpperCamelCase			)

           # Zero-pad up to the sequence length.
           UpperCamelCase__	     =      batch_length - len(__UpperCamelCase			)
           if pad_on_left:
               UpperCamelCase__	     =      ([pad_token] * padding_length) + input_ids
               UpperCamelCase__	     =      ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
           else:
               UpperCamelCase__	     =      input_ids + ([pad_token] * padding_length)
               UpperCamelCase__	     =      attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

           if len(__UpperCamelCase			) != batch_length:
               raise ValueError(f'Error with input length {len(__UpperCamelCase			)} vs {batch_length}'			)
           if len(__UpperCamelCase			) != batch_length:
               raise ValueError(f'Error with input length {len(__UpperCamelCase			)} vs {batch_length}'			)

           if self.mode == "classification":
               UpperCamelCase__	     =      label_map[example.label]
           elif self.mode == "regression":
               UpperCamelCase__	     =      float(example.label			)
           else:
               raise ValueError(self.mode			)

           if ex_index < 5 and self.verbose:
               logger.info("*** Example ***"			)
               logger.info(f'guid: {example.guid}'			)
               logger.info(f'input_ids: {" ".join([str(__UpperCamelCase			) for x in input_ids]			)}'			)
               logger.info(f'attention_mask: {" ".join([str(__UpperCamelCase			) for x in attention_mask]			)}'			)
               logger.info(f'label: {example.label} (id = {label})'			)

           features.append(InputFeatures(input_ids=__UpperCamelCase  ,    attention_mask=__UpperCamelCase  ,    label=__UpperCamelCase			)			)

       if return_tensors is None:
           return features
       elif return_tensors == "tf":
           if not is_tf_available():
               raise RuntimeError("return_tensors set to 'tf' but TensorFlow 2.0 can't be imported"			)
           import tensorflow as tf

           def gen():
               for ex in features:
                   yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

           UpperCamelCase__	     =      tf.data.Dataset.from_generator(
               __UpperCamelCase  ,    ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa)  ,    ({"input_ids": tf.TensorShape([None]			), "attention_mask": tf.TensorShape([None]			)}, tf.TensorShape([]			))  ,    )
           return dataset
       elif return_tensors == "pt":
           if not is_torch_available():
               raise RuntimeError("return_tensors set to 'pt' but PyTorch can't be imported"			)
           import torch
           from torch.utils.data import TensorDataset

           UpperCamelCase__	     =      torch.tensor([f.input_ids for f in features]  ,    dtype=torch.long			)
           UpperCamelCase__	     =      torch.tensor([f.attention_mask for f in features]  ,    dtype=torch.long			)
           if self.mode == "classification":
               UpperCamelCase__	     =      torch.tensor([f.label for f in features]  ,    dtype=torch.long			)
           elif self.mode == "regression":
               UpperCamelCase__	     =      torch.tensor([f.label for f in features]  ,    dtype=torch.float			)

           UpperCamelCase__	     =      TensorDataset(__UpperCamelCase  ,    __UpperCamelCase  ,    __UpperCamelCase			)
           return dataset
       else:
           raise ValueError("return_tensors should be one of 'tf' or 'pt'"			)




