

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

import argparse
import csv
import json
import math
import time

import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as data
from nltk.tokenize.treebank import TreebankWordDetokenizer
from pplm_classification_head import ClassificationHead
from torch import nn
from torchtext import data as torchtext_data
from torchtext import datasets
from tqdm import tqdm, trange

from transformers import GPTaLMHeadModel, GPTaTokenizer


torch.manual_seed(0)
np.random.seed(0)
__UpperCAmelCase      = 1e-1_0
__UpperCAmelCase      = """This is incredible! I love it, this is the best chicken I have ever had."""
__UpperCAmelCase      = 100



class SCREAMING_SNAKE_CASE	(  nn.Module ):
  """simple docstring"""






  def __init__(			self :    List[str]       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    List[str]="gpt2-medium"       ,							lowerCAmelCase :    int=False       ,							lowerCAmelCase :    Union[str, Any]="cpu"    )							->	int:






     """simple docstring"""







     super().__init__()
     __lowerCAmelCase  :			Dict					    =						GPTaTokenizer.from_pretrained(lowerCAmelCase    )
     __lowerCAmelCase  :			int					    =						GPTaLMHeadModel.from_pretrained(lowerCAmelCase    )
     __lowerCAmelCase  :			Tuple					    =						self.encoder.transformer.config.hidden_size
     __lowerCAmelCase  :			Tuple					    =						ClassificationHead(class_size=lowerCAmelCase       ,							embed_size=self.embed_size    )
     __lowerCAmelCase  :			str					    =						cached_mode
     __lowerCAmelCase  :			Dict					    =						device







  def        SCREAMING_SNAKE_CASE    (			self :    List[Any]    )							->	Dict:






     """simple docstring"""







     return self.classifier_head







  def        SCREAMING_SNAKE_CASE    (			self :    int    )							->	Optional[Any]:






     """simple docstring"""







     for param in self.encoder.parameters():
        __lowerCAmelCase  :			List[Any]					    =						False
     self.classifier_head.train()







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]       ,							lowerCAmelCase :    List[str]    )							->	List[str]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[Any]					    =						x.ne(0    ).unsqueeze(2    ).repeat(1       ,							1       ,							self.embed_size    ).float().to(self.device    ).detach()
     __lowerCAmelCase  :			Union[str, Any]					    =						self.encoder.transformer(lowerCAmelCase    )["""last_hidden_state"""]
     __lowerCAmelCase  :			str					    =						hidden * mask
     __lowerCAmelCase  :			List[str]					    =						torch.sum(lowerCAmelCase       ,							dim=1    ) / (torch.sum(lowerCAmelCase       ,							dim=1    ).detach() + EPSILON)
     return avg_hidden







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]       ,							lowerCAmelCase :    Union[str, Any]    )							->	Dict:






     """simple docstring"""







     if self.cached_mode:
        __lowerCAmelCase  :			str					    =						x.to(self.device    )
     else:
        __lowerCAmelCase  :			Dict					    =						self.avg_representation(x.to(self.device    )    )

     __lowerCAmelCase  :			List[str]					    =						self.classifier_head(lowerCAmelCase    )
     __lowerCAmelCase  :			List[Any]					    =						nn.functional.log_softmax(lowerCAmelCase       ,							dim=-1    )

     return probs






class SCREAMING_SNAKE_CASE	(  data.Dataset ):
  """simple docstring"""






  def __init__(			self :    str       ,							lowerCAmelCase :    Any       ,							lowerCAmelCase :    Tuple    )							->	Dict:






     """simple docstring"""







     __lowerCAmelCase  :			str					    =						X
     __lowerCAmelCase  :			int					    =						y







  def __len__(			self :    Tuple    )							->	int:






     """simple docstring"""







     return len(self.X    )







  def __getitem__(			self :    List[str]       ,							lowerCAmelCase :    Tuple    )							->	int:






     """simple docstring"""







     __lowerCAmelCase  :			List[str]					    =						{}
     __lowerCAmelCase  :			Any					    =						self.X[index]
     __lowerCAmelCase  :			Dict					    =						self.y[index]
     return data






def 	snake_case_      (__A     :						int     )			->	Optional[Any]:
   def pad_sequences(__A     :						Union[str, Any]     ):
      __lowerCAmelCase  :			Tuple					    =						[len(__A     ) for seq in sequences]

      __lowerCAmelCase  :			Dict					    =						torch.zeros(len(__A     )					,   max(__A     )     ).long()  # padding value = 0

      for i, seq in enumerate(__A     ):
         __lowerCAmelCase  :			str					    =						lengths[i]
         __lowerCAmelCase  :			Dict					    =						seq[:end]

      return padded_sequences, lengths

   __lowerCAmelCase  :			int					    =						{}
   for key in data[0].keys():
      __lowerCAmelCase  :			List[Any]					    =						[d[key] for d in data]

   __lowerCAmelCase    ,__lowerCAmelCase  :			Dict					    =						pad_sequences(item_info["""X"""]     )
   __lowerCAmelCase  :			int					    =						torch.tensor(item_info["""y"""]					,   dtype=torch.long     )

   return x_batch, y_batch





def 	snake_case_      (__A     :						List[str]     )			->	Tuple:
   __lowerCAmelCase  :			Any					    =						{}
   for key in data[0].keys():
      __lowerCAmelCase  :			Dict					    =						[d[key] for d in data]

   __lowerCAmelCase  :			List[Any]					    =						torch.cat(item_info["""X"""]					,   0     )
   __lowerCAmelCase  :			Optional[int]					    =						torch.tensor(item_info["""y"""]					,   dtype=torch.long     )

   return x_batch, y_batch





def 	snake_case_      (__A     :						List[str]					,   __A     :						str					,   __A     :						List[Any]					,   __A     :						Optional[Any]=0					,   __A     :						Dict=1_0					,   __A     :						Union[str, Any]="cpu"     )			->	Tuple:
   __lowerCAmelCase  :			List[Any]					    =						0
   discriminator.train_custom()
   for batch_idx, (input_t, target_t) in enumerate(__A     ):
      __lowerCAmelCase    ,__lowerCAmelCase  :			int					    =						input_t.to(__A     ), target_t.to(__A     )

      optimizer.zero_grad()

      __lowerCAmelCase  :			Union[str, Any]					    =						discriminator(__A     )
      __lowerCAmelCase  :			Optional[Any]					    =						nn.functional.nll_loss(__A					,   __A     )
      loss.backward(retain_graph=__A     )
      optimizer.step()

      samples_so_far += len(__A     )

      if batch_idx % log_interval == 0:
         print(
             """Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}""".format(
                 epoch + 1					,   __A					,   len(data_loader.dataset     )					,   1_0_0 * samples_so_far / len(data_loader.dataset     )					,   loss.item()					,   )     )





def 	snake_case_      (__A     :						Optional[Any]					,   __A     :						List[Any]					,   __A     :						List[str]="cpu"     )			->	Optional[int]:
   discriminator.eval()
   __lowerCAmelCase  :			int					    =						0
   __lowerCAmelCase  :			Tuple					    =						0
   with torch.no_grad():
      for input_t, target_t in data_loader:
         __lowerCAmelCase    ,__lowerCAmelCase  :			Union[str, Any]					    =						input_t.to(__A     ), target_t.to(__A     )
         __lowerCAmelCase  :			Optional[int]					    =						discriminator(__A     )
         # sum up batch loss
         test_loss += nn.functional.nll_loss(__A					,   __A					,   reduction="""sum"""     ).item()
         # get the index of the max log-probability
         __lowerCAmelCase  :			Union[str, Any]					    =						output_t.argmax(dim=1					,   keepdim=__A     )
         correct += pred_t.eq(target_t.view_as(__A     )     ).sum().item()

   test_loss /= len(data_loader.dataset     )

   print(
       """Performance on test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)""".format(
           __A					,   __A					,   len(data_loader.dataset     )					,   100.0 * correct / len(data_loader.dataset     )     )     )





def 	snake_case_      (__A     :						Optional[Any]					,   __A     :						List[Any]					,   __A     :						Any					,   __A     :						int=False					,   __A     :						int="cpu"     )			->	List[str]:
   __lowerCAmelCase  :			Dict					    =						model.tokenizer.encode(__A     )
   __lowerCAmelCase  :			Optional[Any]					    =						torch.tensor([input_t]					,   dtype=torch.long					,   device=__A     )
   if cached:
      __lowerCAmelCase  :			str					    =						model.avg_representation(__A     )

   __lowerCAmelCase  :			Optional[Any]					    =						model(__A     ).data.cpu().numpy().flatten().tolist()
   print("""Input sentence:"""					,   __A     )
   print(
       """Predictions:"""					,   """, """.join("""{}: {:.4f}""".format(__A					,   math.exp(__A     )     ) for c, log_prob in zip(__A					,   __A     )     )					,   )





def 	snake_case_      (__A     :						int					,   __A     :						List[str]					,   __A     :						Tuple					,   __A     :						List[Any]=False					,   __A     :						Tuple="cpu"     )			->	List[Any]:
   __lowerCAmelCase  :			List[Any]					    =						torch.utils.data.DataLoader(dataset=__A					,   batch_size=__A					,   collate_fn=__A     )

   __lowerCAmelCase  :			Union[str, Any]					    =						[]
   __lowerCAmelCase  :			Any					    =						[]
   for batch_idx, (x, y) in enumerate(tqdm(__A					,   ascii=__A     )     ):
      with torch.no_grad():
         __lowerCAmelCase  :			int					    =						x.to(__A     )
         __lowerCAmelCase  :			str					    =						discriminator.avg_representation(__A     ).cpu().detach()
         __lowerCAmelCase  :			str					    =						torch.unbind(avg_rep.unsqueeze(1     )     )
         xs += avg_rep_list
         ys += y.cpu().numpy().tolist()

   __lowerCAmelCase  :			Optional[Any]					    =						torch.utils.data.DataLoader(
       dataset=Dataset(__A					,   __A     )					,   batch_size=__A					,   shuffle=__A					,   collate_fn=__A     )

   return data_loader





def 	snake_case_      (__A     :						Optional[Any]					,   __A     :						int=None					,   __A     :						Optional[int]="gpt2-medium"					,   __A     :						Tuple=1_0					,   __A     :						Any=6_4					,   __A     :						Optional[Any]=1_0					,   __A     :						Dict=False					,   __A     :						Any=False					,   __A     :						List[Any]=False					,   )			->	Union[str, Any]:
   __lowerCAmelCase  :			Optional[Any]					    =						"""cuda""" if torch.cuda.is_available() and not no_cuda else """cpu"""

   print("""Preprocessing {} dataset...""".format(__A     )     )
   __lowerCAmelCase  :			Any					    =						time.time()

   if dataset == "SST":
      __lowerCAmelCase  :			Optional[Any]					    =						["""positive""", """negative""", """very positive""", """very negative""", """neutral"""]
      __lowerCAmelCase  :			str					    =						{c: i for i, c in enumerate(__A     )}

      __lowerCAmelCase  :			Tuple					    =						Discriminator(
          class_size=len(__A     )					,   pretrained_model=__A					,   cached_mode=__A					,   device=__A     ).to(__A     )

      __lowerCAmelCase  :			int					    =						torchtext_data.Field()
      __lowerCAmelCase  :			Optional[Any]					    =						torchtext_data.Field(sequential=__A     )
      __lowerCAmelCase    ,__lowerCAmelCase    ,__lowerCAmelCase  :			str					    =						datasets.SST.splits(
          __A					,   __A					,   fine_grained=__A					,   train_subtrees=__A					,   )

      __lowerCAmelCase  :			str					    =						[]
      __lowerCAmelCase  :			Dict					    =						[]
      for i in trange(len(__A     )					,   ascii=__A     ):
         __lowerCAmelCase  :			Dict					    =						TreebankWordDetokenizer().detokenize(vars(train_data[i]     )["""text"""]     )
         __lowerCAmelCase  :			str					    =						discriminator.tokenizer.encode(__A     )
         __lowerCAmelCase  :			Union[str, Any]					    =						torch.tensor([5_0_2_5_6] + seq					,   device=__A					,   dtype=torch.long     )
         x.append(__A     )
         y.append(classaidx[vars(train_data[i]     )["""label"""]]     )
      __lowerCAmelCase  :			Dict					    =						Dataset(__A					,   __A     )

      __lowerCAmelCase  :			List[Any]					    =						[]
      __lowerCAmelCase  :			Tuple					    =						[]
      for i in trange(len(__A     )					,   ascii=__A     ):
         __lowerCAmelCase  :			Union[str, Any]					    =						TreebankWordDetokenizer().detokenize(vars(test_data[i]     )["""text"""]     )
         __lowerCAmelCase  :			List[Any]					    =						discriminator.tokenizer.encode(__A     )
         __lowerCAmelCase  :			Any					    =						torch.tensor([5_0_2_5_6] + seq					,   device=__A					,   dtype=torch.long     )
         test_x.append(__A     )
         test_y.append(classaidx[vars(test_data[i]     )["""label"""]]     )
      __lowerCAmelCase  :			Any					    =						Dataset(__A					,   __A     )

      __lowerCAmelCase  :			int					    =						{
          """class_size""": len(__A     ),
          """embed_size""": discriminator.embed_size,
          """pretrained_model""": pretrained_model,
          """class_vocab""": classaidx,
          """default_class""": 2,
      }

   elif dataset == "clickbait":
      __lowerCAmelCase  :			str					    =						["""non_clickbait""", """clickbait"""]
      __lowerCAmelCase  :			List[Any]					    =						{c: i for i, c in enumerate(__A     )}

      __lowerCAmelCase  :			List[str]					    =						Discriminator(
          class_size=len(__A     )					,   pretrained_model=__A					,   cached_mode=__A					,   device=__A     ).to(__A     )

      with open("""datasets/clickbait/clickbait_train_prefix.txt"""     ) as f:
         __lowerCAmelCase  :			Union[str, Any]					    =						[]
         for i, line in enumerate(__A     ):
            try:
               data.append(eval(__A     )     )
            except Exception:
               print("""Error evaluating line {}: {}""".format(__A					,   __A     )     )
               continue
      __lowerCAmelCase  :			str					    =						[]
      __lowerCAmelCase  :			int					    =						[]
      with open("""datasets/clickbait/clickbait_train_prefix.txt"""     ) as f:
         for i, line in enumerate(tqdm(__A					,   ascii=__A     )     ):
            try:
               __lowerCAmelCase  :			List[Any]					    =						eval(__A     )
               __lowerCAmelCase  :			List[str]					    =						discriminator.tokenizer.encode(d["""text"""]     )

               if len(__A     ) < max_length_seq:
                  __lowerCAmelCase  :			str					    =						torch.tensor([5_0_2_5_6] + seq					,   device=__A					,   dtype=torch.long     )
               else:
                  print("""Line {} is longer than maximum length {}""".format(__A					,   __A     )     )
                  continue
               x.append(__A     )
               y.append(d["""label"""]     )
            except Exception:
               print("""Error evaluating / tokenizing line {}, skipping it""".format(__A     )     )
               pass

      __lowerCAmelCase  :			List[Any]					    =						Dataset(__A					,   __A     )
      __lowerCAmelCase  :			Dict					    =						int(0.9 * len(__A     )     )
      __lowerCAmelCase  :			Optional[int]					    =						len(__A     ) - train_size
      __lowerCAmelCase    ,__lowerCAmelCase  :			Optional[Any]					    =						torch.utils.data.random_split(__A					,   [train_size, test_size]     )

      __lowerCAmelCase  :			Union[str, Any]					    =						{
          """class_size""": len(__A     ),
          """embed_size""": discriminator.embed_size,
          """pretrained_model""": pretrained_model,
          """class_vocab""": classaidx,
          """default_class""": 1,
      }

   elif dataset == "toxic":
      __lowerCAmelCase  :			Dict					    =						["""non_toxic""", """toxic"""]
      __lowerCAmelCase  :			List[str]					    =						{c: i for i, c in enumerate(__A     )}

      __lowerCAmelCase  :			Dict					    =						Discriminator(
          class_size=len(__A     )					,   pretrained_model=__A					,   cached_mode=__A					,   device=__A     ).to(__A     )

      __lowerCAmelCase  :			Tuple					    =						[]
      __lowerCAmelCase  :			Optional[int]					    =						[]
      with open("""datasets/toxic/toxic_train.txt"""     ) as f:
         for i, line in enumerate(tqdm(__A					,   ascii=__A     )     ):
            try:
               __lowerCAmelCase  :			Optional[int]					    =						eval(__A     )
               __lowerCAmelCase  :			Dict					    =						discriminator.tokenizer.encode(d["""text"""]     )

               if len(__A     ) < max_length_seq:
                  __lowerCAmelCase  :			Any					    =						torch.tensor([5_0_2_5_6] + seq					,   device=__A					,   dtype=torch.long     )
               else:
                  print("""Line {} is longer than maximum length {}""".format(__A					,   __A     )     )
                  continue
               x.append(__A     )
               y.append(int(np.sum(d["""label"""]     ) > 0     )     )
            except Exception:
               print("""Error evaluating / tokenizing line {}, skipping it""".format(__A     )     )
               pass

      __lowerCAmelCase  :			Optional[Any]					    =						Dataset(__A					,   __A     )
      __lowerCAmelCase  :			Any					    =						int(0.9 * len(__A     )     )
      __lowerCAmelCase  :			Dict					    =						len(__A     ) - train_size
      __lowerCAmelCase    ,__lowerCAmelCase  :			Dict					    =						torch.utils.data.random_split(__A					,   [train_size, test_size]     )

      __lowerCAmelCase  :			Union[str, Any]					    =						{
          """class_size""": len(__A     ),
          """embed_size""": discriminator.embed_size,
          """pretrained_model""": pretrained_model,
          """class_vocab""": classaidx,
          """default_class""": 0,
      }

   else:  # if dataset == "generic":
      # This assumes the input dataset is a TSV with the following structure:
      # class \t text

      if dataset_fp is None:
         raise ValueError("""When generic dataset is selected, dataset_fp needs to be specified aswell."""     )

      __lowerCAmelCase  :			int					    =						set()
      with open(__A     ) as f:
         __lowerCAmelCase  :			int					    =						csv.reader(__A					,   delimiter="""\t"""     )
         for row in tqdm(__A					,   ascii=__A     ):
            if row:
               classes.add(row[0]     )

      __lowerCAmelCase  :			Optional[Any]					    =						sorted(__A     )
      __lowerCAmelCase  :			Union[str, Any]					    =						{c: i for i, c in enumerate(__A     )}

      __lowerCAmelCase  :			Optional[int]					    =						Discriminator(
          class_size=len(__A     )					,   pretrained_model=__A					,   cached_mode=__A					,   device=__A     ).to(__A     )

      __lowerCAmelCase  :			Tuple					    =						[]
      __lowerCAmelCase  :			Union[str, Any]					    =						[]
      with open(__A     ) as f:
         __lowerCAmelCase  :			List[Any]					    =						csv.reader(__A					,   delimiter="""\t"""     )
         for i, row in enumerate(tqdm(__A					,   ascii=__A     )     ):
            if row:
               __lowerCAmelCase  :			Optional[int]					    =						row[0]
               __lowerCAmelCase  :			Tuple					    =						row[1]

               try:
                  __lowerCAmelCase  :			Tuple					    =						discriminator.tokenizer.encode(__A     )
                  if len(__A     ) < max_length_seq:
                     __lowerCAmelCase  :			int					    =						torch.tensor([5_0_2_5_6] + seq					,   device=__A					,   dtype=torch.long     )

                  else:
                     print("""Line {} is longer than maximum length {}""".format(__A					,   __A     )     )
                     continue

                  x.append(__A     )
                  y.append(classaidx[label]     )

               except Exception:
                  print("""Error tokenizing line {}, skipping it""".format(__A     )     )
                  pass

      __lowerCAmelCase  :			str					    =						Dataset(__A					,   __A     )
      __lowerCAmelCase  :			Optional[Any]					    =						int(0.9 * len(__A     )     )
      __lowerCAmelCase  :			str					    =						len(__A     ) - train_size
      __lowerCAmelCase    ,__lowerCAmelCase  :			Union[str, Any]					    =						torch.utils.data.random_split(__A					,   [train_size, test_size]     )

      __lowerCAmelCase  :			List[str]					    =						{
          """class_size""": len(__A     ),
          """embed_size""": discriminator.embed_size,
          """pretrained_model""": pretrained_model,
          """class_vocab""": classaidx,
          """default_class""": 0,
      }

   __lowerCAmelCase  :			Optional[Any]					    =						time.time()
   print("""Preprocessed {} data points""".format(len(__A     ) + len(__A     )     )     )
   print("""Data preprocessing took: {:.3f}s""".format(end - start     )     )

   if cached:
      print("""Building representation cache..."""     )

      __lowerCAmelCase  :			int					    =						time.time()

      __lowerCAmelCase  :			List[str]					    =						get_cached_data_loader(__A					,   __A					,   __A					,   shuffle=__A					,   device=__A     )

      __lowerCAmelCase  :			Tuple					    =						get_cached_data_loader(__A					,   __A					,   __A					,   device=__A     )

      __lowerCAmelCase  :			List[Any]					    =						time.time()
      print("""Building representation cache took: {:.3f}s""".format(end - start     )     )

   else:
      __lowerCAmelCase  :			Optional[int]					    =						torch.utils.data.DataLoader(
          dataset=__A					,   batch_size=__A					,   shuffle=__A					,   collate_fn=__A     )
      __lowerCAmelCase  :			Optional[Any]					    =						torch.utils.data.DataLoader(dataset=__A					,   batch_size=__A					,   collate_fn=__A     )

   if save_model:
      with open("""{}_classifier_head_meta.json""".format(__A     )					,   """w"""     ) as meta_file:
         json.dump(__A					,   __A     )

   __lowerCAmelCase  :			Any					    =						optim.Adam(discriminator.parameters()					,   lr=0.0001     )

   for epoch in range(__A     ):
      __lowerCAmelCase  :			str					    =						time.time()
      print("""\nEpoch"""					,   epoch + 1     )

      train_epoch(
          discriminator=__A					,   data_loader=__A					,   optimizer=__A					,   epoch=__A					,   log_interval=__A					,   device=__A					,   )
      evaluate_performance(data_loader=__A					,   discriminator=__A					,   device=__A     )

      __lowerCAmelCase  :			List[Any]					    =						time.time()
      print("""Epoch took: {:.3f}s""".format(end - start     )     )

      print("""\nExample prediction"""     )
      predict(__A					,   __A					,   __A					,   cached=__A					,   device=__A     )

      if save_model:
         # torch.save(discriminator.state_dict(),
         #           "{}_discriminator_{}.pt".format(
         #               args.dataset, epoch + 1
         #               ))
         torch.save(
             discriminator.get_classifier().state_dict()					,   """{}_classifier_head_epoch_{}.pt""".format(__A					,   epoch + 1     )					,   )


if __name__ == "__main__":
   __UpperCAmelCase      = argparse.ArgumentParser(description="""Train a discriminator on top of GPT-2 representations""")
   parser.add_argument(
       """--dataset""",
       type=str,
       default="""SST""",
       choices=("""SST""", """clickbait""", """toxic""", """generic"""),
       help=(
           """dataset to train the discriminator on."""
           """In case of generic, the dataset is expected"""
           """to be a TSBV file with structure: class \\t text"""
       ),
   )
   parser.add_argument(
       """--dataset_fp""",
       type=str,
       default="""""",
       help="""File path of the dataset to use. Needed only in case of generic datadset""",
   )
   parser.add_argument(
       """--pretrained_model""", type=str, default="""gpt2-medium""", help="""Pretrained model to use as encoder"""
   )
   parser.add_argument("""--epochs""", type=int, default=10, metavar="""N""", help="""Number of training epochs""")
   parser.add_argument(
       """--batch_size""", type=int, default=64, metavar="""N""", help="""input batch size for training (default: 64)"""
   )
   parser.add_argument(
       """--log_interval""",
       type=int,
       default=10,
       metavar="""N""",
       help="""how many batches to wait before logging training status""",
   )
   parser.add_argument("""--save_model""", action="""store_true""", help="""whether to save the model""")
   parser.add_argument("""--cached""", action="""store_true""", help="""whether to cache the input representations""")
   parser.add_argument("""--no_cuda""", action="""store_true""", help="""use to turn off cuda""")
   __UpperCAmelCase      = parser.parse_args()

   train_discriminator(**(vars(args)))





from math import sqrt





def 	snake_case_      (__A     :						int     )			->	list[int]:
   __lowerCAmelCase  :			List[str]					    =						[1]
   for i in range(2					,   int(sqrt(__A     )     ) + 1					,   1     ):
      if number % i == 0:
         values.append(__A     )
         if int(number // i     ) != i:
            values.append(int(number // i     )     )
   return sorted(__A     )





def 	snake_case_      (__A     :						int     )			->	bool:
   return sum(factors(__A     )     ) > n





def 	snake_case_      (__A     :						int     )			->	bool:
   __lowerCAmelCase  :			Any					    =						factors(__A     )
   __lowerCAmelCase  :			Union[str, Any]					    =						len(__A     )
   __lowerCAmelCase  :			str					    =						[[0 for i in range(number + 1     )] for j in range(r + 1     )]
   for i in range(r + 1     ):
      __lowerCAmelCase  :			Tuple					    =						True

   for i in range(1					,   number + 1     ):
      __lowerCAmelCase  :			List[str]					    =						False

   for i in range(1					,   r + 1     ):
      for j in range(1					,   number + 1     ):
         if j < values[i - 1]:
            __lowerCAmelCase  :			Dict					    =						subset[i - 1][j]
         else:
            __lowerCAmelCase  :			Dict					    =						subset[i - 1][j] or subset[i - 1][j - values[i - 1]]

   return subset[r][number] != 0





def 	snake_case_      (__A     :						int     )			->	bool:
   return abundant(__A     ) and not semi_perfect(__A     )


if __name__ == "__main__":
   import doctest

   doctest.testmod(verbose=True)
   for number in (69, 70, 71):
      print(F'{number} is {"" if weird(number) else "not "}weird.')


