


"""simple docstring"""



# 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)
lowercase_							 =       1E-1_0
lowercase_							 =       'This is incredible! I love it, this is the best chicken I have ever had.'
lowercase_							 =       1_00







class       __a	(   nn.Module       ):







				def __init__(   self			,  UpperCAmelCase			,  UpperCAmelCase="gpt2-medium"			,  UpperCAmelCase=False			,  UpperCAmelCase="cpu"      ):

					'''simple docstring'''






					super().__init__()
					lowerCAmelCase_			       = GPTaTokenizer.from_pretrained(UpperCAmelCase      )
					lowerCAmelCase_			       = GPTaLMHeadModel.from_pretrained(UpperCAmelCase      )
					lowerCAmelCase_			       = self.encoder.transformer.config.hidden_size
					lowerCAmelCase_			       = ClassificationHead(class_size=UpperCAmelCase			,  embed_size=self.embed_size      )
					lowerCAmelCase_			       = cached_mode
					lowerCAmelCase_			       = device







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					return self.classifier_head







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					for param in self.encoder.parameters():
						lowerCAmelCase_			       = False
					self.classifier_head.train()







				def     lowerCamelCase_    (   self			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = x.ne(0      ).unsqueeze(2      ).repeat(1			,  1			,  self.embed_size      ).float().to(self.device      ).detach()
					lowerCAmelCase_			       = self.encoder.transformer(UpperCAmelCase      )['''last_hidden_state''']
					lowerCAmelCase_			       = hidden * mask
					lowerCAmelCase_			       = torch.sum(UpperCAmelCase			,  dim=1      ) / (torch.sum(UpperCAmelCase			,  dim=1      ).detach() + EPSILON)
					return avg_hidden







				def     lowerCamelCase_    (   self			,  UpperCAmelCase      ):

					'''simple docstring'''






					if self.cached_mode:
						lowerCAmelCase_			       = x.to(self.device      )
					else:
						lowerCAmelCase_			       = self.avg_representation(x.to(self.device      )      )

					lowerCAmelCase_			       = self.classifier_head(UpperCAmelCase      )
					lowerCAmelCase_			       = nn.functional.log_softmax(UpperCAmelCase			,  dim=-1      )

					return probs







class       __a	(   data.Dataset       ):







				def __init__(   self			,  UpperCAmelCase			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = X
					lowerCAmelCase_			       = y







				def __len__(   self      ):

					'''simple docstring'''






					return len(self.X      )







				def __getitem__(   self			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = {}
					lowerCAmelCase_			       = self.X[index]
					lowerCAmelCase_			       = self.y[index]
					return data




def     UpperCAmelCase    (					_lowercase   :      Optional[Any]  )	->   Optional[int]:


	"""simple docstring"""




	def pad_sequences(_lowercase   :      Dict  ):
		lowerCAmelCase_			       = [len(_lowercase  ) for seq in sequences]

		lowerCAmelCase_			       = torch.zeros(len(_lowercase  ) ,      max(_lowercase  )  ).long()  # padding value = 0

		for i, seq in enumerate(_lowercase  ):
			lowerCAmelCase_			       = lengths[i]
			lowerCAmelCase_			       = seq[:end]

		return padded_sequences, lengths

	lowerCAmelCase_			       = {}
	for key in data[0].keys():
		lowerCAmelCase_			       = [d[key] for d in data]

	lowerCAmelCase_       ,  lowerCAmelCase_			       = pad_sequences(item_info['''X''']  )
	lowerCAmelCase_			       = torch.tensor(item_info['''y'''] ,      dtype=torch.long  )

	return x_batch, y_batch
def     UpperCAmelCase    (					_lowercase   :      int  )	->   int:


	"""simple docstring"""




	lowerCAmelCase_			       = {}
	for key in data[0].keys():
		lowerCAmelCase_			       = [d[key] for d in data]

	lowerCAmelCase_			       = torch.cat(item_info['''X'''] ,      0  )
	lowerCAmelCase_			       = torch.tensor(item_info['''y'''] ,      dtype=torch.long  )

	return x_batch, y_batch
def     UpperCAmelCase    (					_lowercase   :      Any ,      _lowercase   :      Dict ,      _lowercase   :      Union[str, Any] ,      _lowercase   :      Union[str, Any]=0 ,      _lowercase   :      Union[str, Any]=1_0 ,      _lowercase   :      Optional[int]="cpu"  )	->   Union[str, Any]:


	"""simple docstring"""




	lowerCAmelCase_			       = 0
	discriminator.train_custom()
	for batch_idx, (input_t, target_t) in enumerate(_lowercase  ):
		lowerCAmelCase_       ,  lowerCAmelCase_			       = input_t.to(_lowercase  ), target_t.to(_lowercase  )

		optimizer.zero_grad()

		lowerCAmelCase_			       = discriminator(_lowercase  )
		lowerCAmelCase_			       = nn.functional.nll_loss(_lowercase ,      _lowercase  )
		loss.backward(retain_graph=_lowercase  )
		optimizer.step()

		samples_so_far += len(_lowercase  )

		if batch_idx % log_interval == 0:
			print(
			    '''Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'''.format(
			        epoch + 1 ,      _lowercase ,      len(data_loader.dataset  ) ,      1_0_0 * samples_so_far / len(data_loader.dataset  ) ,      loss.item() ,      )  )
def     UpperCAmelCase    (					_lowercase   :      Optional[Any] ,      _lowercase   :      Optional[Any] ,      _lowercase   :      Optional[int]="cpu"  )	->   int:


	"""simple docstring"""




	discriminator.eval()
	lowerCAmelCase_			       = 0
	lowerCAmelCase_			       = 0
	with torch.no_grad():
		for input_t, target_t in data_loader:
			lowerCAmelCase_       ,  lowerCAmelCase_			       = input_t.to(_lowercase  ), target_t.to(_lowercase  )
			lowerCAmelCase_			       = discriminator(_lowercase  )
			# sum up batch loss
			test_loss += nn.functional.nll_loss(_lowercase ,      _lowercase ,      reduction='''sum'''  ).item()
			# get the index of the max log-probability
			lowerCAmelCase_			       = output_t.argmax(dim=1 ,      keepdim=_lowercase  )
			correct += pred_t.eq(target_t.view_as(_lowercase  )  ).sum().item()

	test_loss /= len(data_loader.dataset  )

	print(
	    '''Performance on test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)'''.format(
	        _lowercase ,      _lowercase ,      len(data_loader.dataset  ) ,      1_0_0.0 * correct / len(data_loader.dataset  )  )  )
def     UpperCAmelCase    (					_lowercase   :      Dict ,      _lowercase   :      Tuple ,      _lowercase   :      Any ,      _lowercase   :      List[Any]=False ,      _lowercase   :      Union[str, Any]="cpu"  )	->   Dict:


	"""simple docstring"""




	lowerCAmelCase_			       = model.tokenizer.encode(_lowercase  )
	lowerCAmelCase_			       = torch.tensor([input_t] ,      dtype=torch.long ,      device=_lowercase  )
	if cached:
		lowerCAmelCase_			       = model.avg_representation(_lowercase  )

	lowerCAmelCase_			       = model(_lowercase  ).data.cpu().numpy().flatten().tolist()
	print('''Input sentence:''' ,      _lowercase  )
	print(
	    '''Predictions:''' ,      ''', '''.join('''{}: {:.4f}'''.format(_lowercase ,      math.exp(_lowercase  )  ) for c, log_prob in zip(_lowercase ,      _lowercase  )  ) ,      )
def     UpperCAmelCase    (					_lowercase   :      Optional[Any] ,      _lowercase   :      str ,      _lowercase   :      Union[str, Any] ,      _lowercase   :      str=False ,      _lowercase   :      List[str]="cpu"  )	->   Union[str, Any]:


	"""simple docstring"""




	lowerCAmelCase_			       = torch.utils.data.DataLoader(dataset=_lowercase ,      batch_size=_lowercase ,      collate_fn=_lowercase  )

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

	lowerCAmelCase_			       = torch.utils.data.DataLoader(
	    dataset=Dataset(_lowercase ,      _lowercase  ) ,      batch_size=_lowercase ,      shuffle=_lowercase ,      collate_fn=_lowercase  )

	return data_loader
def     UpperCAmelCase    (					_lowercase   :      int ,      _lowercase   :      Union[str, Any]=None ,      _lowercase   :      Tuple="gpt2-medium" ,      _lowercase   :      List[str]=1_0 ,      _lowercase   :      str=6_4 ,      _lowercase   :      str=1_0 ,      _lowercase   :      Union[str, Any]=False ,      _lowercase   :      Union[str, Any]=False ,      _lowercase   :      Optional[int]=False ,      )	->   List[str]:


	"""simple docstring"""




	lowerCAmelCase_			       = '''cuda''' if torch.cuda.is_available() and not no_cuda else '''cpu'''

	print('''Preprocessing {} dataset...'''.format(_lowercase  )  )
	lowerCAmelCase_			       = time.time()

	if dataset == "SST":
		lowerCAmelCase_			       = ['''positive''', '''negative''', '''very positive''', '''very negative''', '''neutral''']
		lowerCAmelCase_			       = {c: i for i, c in enumerate(_lowercase  )}

		lowerCAmelCase_			       = Discriminator(
		    class_size=len(_lowercase  ) ,      pretrained_model=_lowercase ,      cached_mode=_lowercase ,      device=_lowercase  ).to(_lowercase  )

		lowerCAmelCase_			       = torchtext_data.Field()
		lowerCAmelCase_			       = torchtext_data.Field(sequential=_lowercase  )
		lowerCAmelCase_       ,  lowerCAmelCase_       ,  lowerCAmelCase_			       = datasets.SST.splits(
		    _lowercase ,      _lowercase ,      fine_grained=_lowercase ,      train_subtrees=_lowercase ,      )

		lowerCAmelCase_			       = []
		lowerCAmelCase_			       = []
		for i in trange(len(_lowercase  ) ,      ascii=_lowercase  ):
			lowerCAmelCase_			       = TreebankWordDetokenizer().detokenize(vars(train_data[i]  )['''text''']  )
			lowerCAmelCase_			       = discriminator.tokenizer.encode(_lowercase  )
			lowerCAmelCase_			       = torch.tensor([5_0_2_5_6] + seq ,      device=_lowercase ,      dtype=torch.long  )
			x.append(_lowercase  )
			y.append(classaidx[vars(train_data[i]  )['''label''']]  )
		lowerCAmelCase_			       = Dataset(_lowercase ,      _lowercase  )

		lowerCAmelCase_			       = []
		lowerCAmelCase_			       = []
		for i in trange(len(_lowercase  ) ,      ascii=_lowercase  ):
			lowerCAmelCase_			       = TreebankWordDetokenizer().detokenize(vars(test_data[i]  )['''text''']  )
			lowerCAmelCase_			       = discriminator.tokenizer.encode(_lowercase  )
			lowerCAmelCase_			       = torch.tensor([5_0_2_5_6] + seq ,      device=_lowercase ,      dtype=torch.long  )
			test_x.append(_lowercase  )
			test_y.append(classaidx[vars(test_data[i]  )['''label''']]  )
		lowerCAmelCase_			       = Dataset(_lowercase ,      _lowercase  )

		lowerCAmelCase_			       = {
		    '''class_size''': len(_lowercase  ),
		    '''embed_size''': discriminator.embed_size,
		    '''pretrained_model''': pretrained_model,
		    '''class_vocab''': classaidx,
		    '''default_class''': 2,
		}

	elif dataset == "clickbait":
		lowerCAmelCase_			       = ['''non_clickbait''', '''clickbait''']
		lowerCAmelCase_			       = {c: i for i, c in enumerate(_lowercase  )}

		lowerCAmelCase_			       = Discriminator(
		    class_size=len(_lowercase  ) ,      pretrained_model=_lowercase ,      cached_mode=_lowercase ,      device=_lowercase  ).to(_lowercase  )

		with open('''datasets/clickbait/clickbait_train_prefix.txt'''  ) as f:
			lowerCAmelCase_			       = []
			for i, line in enumerate(_lowercase  ):
				try:
					data.append(eval(_lowercase  )  )
				except Exception:
					print('''Error evaluating line {}: {}'''.format(_lowercase ,      _lowercase  )  )
					continue
		lowerCAmelCase_			       = []
		lowerCAmelCase_			       = []
		with open('''datasets/clickbait/clickbait_train_prefix.txt'''  ) as f:
			for i, line in enumerate(tqdm(_lowercase ,      ascii=_lowercase  )  ):
				try:
					lowerCAmelCase_			       = eval(_lowercase  )
					lowerCAmelCase_			       = discriminator.tokenizer.encode(d['''text''']  )

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

		lowerCAmelCase_			       = Dataset(_lowercase ,      _lowercase  )
		lowerCAmelCase_			       = int(0.9 * len(_lowercase  )  )
		lowerCAmelCase_			       = len(_lowercase  ) - train_size
		lowerCAmelCase_       ,  lowerCAmelCase_			       = torch.utils.data.random_split(_lowercase ,      [train_size, test_size]  )

		lowerCAmelCase_			       = {
		    '''class_size''': len(_lowercase  ),
		    '''embed_size''': discriminator.embed_size,
		    '''pretrained_model''': pretrained_model,
		    '''class_vocab''': classaidx,
		    '''default_class''': 1,
		}

	elif dataset == "toxic":
		lowerCAmelCase_			       = ['''non_toxic''', '''toxic''']
		lowerCAmelCase_			       = {c: i for i, c in enumerate(_lowercase  )}

		lowerCAmelCase_			       = Discriminator(
		    class_size=len(_lowercase  ) ,      pretrained_model=_lowercase ,      cached_mode=_lowercase ,      device=_lowercase  ).to(_lowercase  )

		lowerCAmelCase_			       = []
		lowerCAmelCase_			       = []
		with open('''datasets/toxic/toxic_train.txt'''  ) as f:
			for i, line in enumerate(tqdm(_lowercase ,      ascii=_lowercase  )  ):
				try:
					lowerCAmelCase_			       = eval(_lowercase  )
					lowerCAmelCase_			       = discriminator.tokenizer.encode(d['''text''']  )

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

		lowerCAmelCase_			       = Dataset(_lowercase ,      _lowercase  )
		lowerCAmelCase_			       = int(0.9 * len(_lowercase  )  )
		lowerCAmelCase_			       = len(_lowercase  ) - train_size
		lowerCAmelCase_       ,  lowerCAmelCase_			       = torch.utils.data.random_split(_lowercase ,      [train_size, test_size]  )

		lowerCAmelCase_			       = {
		    '''class_size''': len(_lowercase  ),
		    '''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_			       = set()
		with open(_lowercase  ) as f:
			lowerCAmelCase_			       = csv.reader(_lowercase ,      delimiter='''\t'''  )
			for row in tqdm(_lowercase ,      ascii=_lowercase  ):
				if row:
					classes.add(row[0]  )

		lowerCAmelCase_			       = sorted(_lowercase  )
		lowerCAmelCase_			       = {c: i for i, c in enumerate(_lowercase  )}

		lowerCAmelCase_			       = Discriminator(
		    class_size=len(_lowercase  ) ,      pretrained_model=_lowercase ,      cached_mode=_lowercase ,      device=_lowercase  ).to(_lowercase  )

		lowerCAmelCase_			       = []
		lowerCAmelCase_			       = []
		with open(_lowercase  ) as f:
			lowerCAmelCase_			       = csv.reader(_lowercase ,      delimiter='''\t'''  )
			for i, row in enumerate(tqdm(_lowercase ,      ascii=_lowercase  )  ):
				if row:
					lowerCAmelCase_			       = row[0]
					lowerCAmelCase_			       = row[1]

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

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

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

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

		lowerCAmelCase_			       = Dataset(_lowercase ,      _lowercase  )
		lowerCAmelCase_			       = int(0.9 * len(_lowercase  )  )
		lowerCAmelCase_			       = len(_lowercase  ) - train_size
		lowerCAmelCase_       ,  lowerCAmelCase_			       = torch.utils.data.random_split(_lowercase ,      [train_size, test_size]  )

		lowerCAmelCase_			       = {
		    '''class_size''': len(_lowercase  ),
		    '''embed_size''': discriminator.embed_size,
		    '''pretrained_model''': pretrained_model,
		    '''class_vocab''': classaidx,
		    '''default_class''': 0,
		}

	lowerCAmelCase_			       = time.time()
	print('''Preprocessed {} data points'''.format(len(_lowercase  ) + len(_lowercase  )  )  )
	print('''Data preprocessing took: {:.3f}s'''.format(end - start  )  )

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

		lowerCAmelCase_			       = time.time()

		lowerCAmelCase_			       = get_cached_data_loader(_lowercase ,      _lowercase ,      _lowercase ,      shuffle=_lowercase ,      device=_lowercase  )

		lowerCAmelCase_			       = get_cached_data_loader(_lowercase ,      _lowercase ,      _lowercase ,      device=_lowercase  )

		lowerCAmelCase_			       = time.time()
		print('''Building representation cache took: {:.3f}s'''.format(end - start  )  )

	else:
		lowerCAmelCase_			       = torch.utils.data.DataLoader(
		    dataset=_lowercase ,      batch_size=_lowercase ,      shuffle=_lowercase ,      collate_fn=_lowercase  )
		lowerCAmelCase_			       = torch.utils.data.DataLoader(dataset=_lowercase ,      batch_size=_lowercase ,      collate_fn=_lowercase  )

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

	lowerCAmelCase_			       = optim.Adam(discriminator.parameters() ,      lr=0.0_0_0_1  )

	for epoch in range(_lowercase  ):
		lowerCAmelCase_			       = time.time()
		print('''\nEpoch''' ,      epoch + 1  )

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

		lowerCAmelCase_			       = time.time()
		print('''Epoch took: {:.3f}s'''.format(end - start  )  )

		print('''\nExample prediction'''  )
		predict(_lowercase ,      _lowercase ,      _lowercase ,      cached=_lowercase ,      device=_lowercase  )

		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(_lowercase ,      epoch + 1  ) ,      )


if __name__ == "__main__":
		lowercase_							 =       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')
		lowercase_							 =       parser.parse_args()

		train_discriminator(**(vars(args)))



"""simple docstring"""



from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available







@dataclass
class       __a	(   __snake_case       ):
				lowerCamelCase    :					int 					={
				    'sld_warmup_steps': 15,
				    'sld_guidance_scale': 20,
				    'sld_threshold': 0.0,
				    'sld_momentum_scale': 0.0,
				    'sld_mom_beta': 0.0,
				}
				lowerCamelCase    :					Optional[Any] 					={
				    'sld_warmup_steps': 10,
				    'sld_guidance_scale': 1000,
				    'sld_threshold': 0.01,
				    'sld_momentum_scale': 0.3,
				    'sld_mom_beta': 0.4,
				}
				lowerCamelCase    :					List[str] 					={
				    'sld_warmup_steps': 7,
				    'sld_guidance_scale': 2000,
				    'sld_threshold': 0.025,
				    'sld_momentum_scale': 0.5,
				    'sld_mom_beta': 0.7,
				}
				lowerCamelCase    :					Any 					={
				    'sld_warmup_steps': 0,
				    'sld_guidance_scale': 5000,
				    'sld_threshold': 1.0,
				    'sld_momentum_scale': 0.5,
				    'sld_mom_beta': 0.7,
				}







@dataclass
class       __a	(   __snake_case       ):
				lowerCamelCase    :					Union[List[PIL.Image.Image], np.ndarray]
				lowerCamelCase    :					Optional[List[bool]]
				lowerCamelCase    :					Optional[Union[List[PIL.Image.Image], np.ndarray]]
				lowerCamelCase    :					Optional[str]


if is_transformers_available() and is_torch_available():
		from .pipeline_stable_diffusion_safe import StableDiffusionPipelineSafe
		from .safety_checker import SafeStableDiffusionSafetyChecker