


# 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)
lowerCAmelCase__						:int         =							1e-10
lowerCAmelCase__						:str         =							'''This is incredible! I love it, this is the best chicken I have ever had.'''
lowerCAmelCase__						:Any         =							1_0_0

class 	__a   (       nn.Module    ):
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE    ,					_SCREAMING_SNAKE_CASE="gpt2-medium"    ,					_SCREAMING_SNAKE_CASE=False    ,					_SCREAMING_SNAKE_CASE="cpu"		)				-> Any:




									"""simple docstring"""





									super().__init__()
									_UpperCAmelCase					=    GPTaTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    GPTaLMHeadModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    self.encoder.transformer.config.hidden_size
									_UpperCAmelCase					=    ClassificationHead(class_size=_SCREAMING_SNAKE_CASE    ,					embed_size=self.embed_size		)
									_UpperCAmelCase					=    cached_mode
									_UpperCAmelCase					=    device
		def 			UpperCAmelCase__       (    self		)				-> str:




									"""simple docstring"""





									return self.classifier_head
		def 			UpperCAmelCase__       (    self		)				-> List[Any]:




									"""simple docstring"""





									for param in self.encoder.parameters():
																_UpperCAmelCase					=    False
									self.classifier_head.train()
		def 			UpperCAmelCase__       (    self    ,					_SCREAMING_SNAKE_CASE		)				-> Union[str, Any]:




									"""simple docstring"""





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






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




									"""simple docstring"""





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

									_UpperCAmelCase					=    self.classifier_head(_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    nn.functional.log_softmax(_SCREAMING_SNAKE_CASE    ,					dim=-1		)

									return probs



class 	__a   (       data.Dataset    ):
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE    ,					_SCREAMING_SNAKE_CASE		)				-> Optional[Any]:




									"""simple docstring"""





									_UpperCAmelCase					=    X
									_UpperCAmelCase					=    y
		def __len__(    self		)				-> Optional[Any]:




									"""simple docstring"""





									return len(self.X		)






		def __getitem__(    self    ,					_SCREAMING_SNAKE_CASE		)				-> List[Any]:




									"""simple docstring"""





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



def  lowerCAmelCase__				(    a__:	Any )						->	int:


							'''simple docstring'''





							def pad_sequences(a__:	Optional[int] ):
														_UpperCAmelCase					=    [len(a__ ) for seq in sequences]

														_UpperCAmelCase					=    torch.zeros(len(a__ )    ,						max(a__ ) ).long()  # padding value = 0

														for i, seq in enumerate(a__ ):
																					_UpperCAmelCase					=    lengths[i]
																					_UpperCAmelCase					=    seq[:end]

														return padded_sequences, lengths

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

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

							return x_batch, y_batch

def  lowerCAmelCase__				(    a__:	List[str] )						->	int:


							'''simple docstring'''





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

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

							return x_batch, y_batch

def  lowerCAmelCase__				(    a__:	int    ,						a__:	Tuple    ,						a__:	List[Any]    ,						a__:	Optional[Any]=0    ,						a__:	Tuple=1_0    ,						a__:	Tuple="cpu" )						->	Tuple:


							'''simple docstring'''





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

														optimizer.zero_grad()

														_UpperCAmelCase					=    discriminator(a__ )
														_UpperCAmelCase					=    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  lowerCAmelCase__				(    a__:	List[Any]    ,						a__:	List[str]    ,						a__:	str="cpu" )						->	List[str]:


							'''simple docstring'''





							discriminator.eval()
							_UpperCAmelCase					=    0
							_UpperCAmelCase					=    0
							with torch.no_grad():
														for input_t, target_t in data_loader:
																					_UpperCAmelCase	, _UpperCAmelCase					=    input_t.to(a__ ), target_t.to(a__ )
																					_UpperCAmelCase					=    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
																					_UpperCAmelCase					=    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  lowerCAmelCase__				(    a__:	Dict    ,						a__:	Tuple    ,						a__:	Union[str, Any]    ,						a__:	Union[str, Any]=False    ,						a__:	Tuple="cpu" )						->	Optional[int]:


							'''simple docstring'''





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

							_UpperCAmelCase					=    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  lowerCAmelCase__				(    a__:	Tuple    ,						a__:	Union[str, Any]    ,						a__:	List[str]    ,						a__:	List[str]=False    ,						a__:	Optional[int]="cpu" )						->	int:


							'''simple docstring'''





							_UpperCAmelCase					=    torch.utils.data.DataLoader(dataset=a__    ,						batch_size=a__    ,						collate_fn=a__ )

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

							_UpperCAmelCase					=    torch.utils.data.DataLoader(
							    dataset=Dataset(a__    ,						a__ )    ,						batch_size=a__    ,						shuffle=a__    ,						collate_fn=a__ )

							return data_loader

def  lowerCAmelCase__				(    a__:	Dict    ,						a__:	Optional[int]=None    ,						a__:	Any="gpt2-medium"    ,						a__:	Optional[int]=1_0    ,						a__:	Union[str, Any]=6_4    ,						a__:	Any=1_0    ,						a__:	Any=False    ,						a__:	Dict=False    ,						a__:	int=False    ,						)						->	Dict:


							'''simple docstring'''





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

							print('Preprocessing {} dataset...'.format(a__ ) )
							_UpperCAmelCase					=    time.time()

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

														_UpperCAmelCase					=    Discriminator(
														    class_size=len(a__ )    ,						pretrained_model=a__    ,						cached_mode=a__    ,						device=a__ ).to(a__ )

														_UpperCAmelCase					=    torchtext_data.Field()
														_UpperCAmelCase					=    torchtext_data.Field(sequential=a__ )
														_UpperCAmelCase	, _UpperCAmelCase	, _UpperCAmelCase					=    datasets.SST.splits(
														    a__    ,						a__    ,						fine_grained=a__    ,						train_subtrees=a__    ,						)

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

														_UpperCAmelCase					=    []
														_UpperCAmelCase					=    []
														for i in trange(len(a__ )    ,						ascii=a__ ):
																					_UpperCAmelCase					=    TreebankWordDetokenizer().detokenize(vars(test_data[i] )['text'] )
																					_UpperCAmelCase					=    discriminator.tokenizer.encode(a__ )
																					_UpperCAmelCase					=    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']] )
														_UpperCAmelCase					=    Dataset(a__    ,						a__ )

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

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

														_UpperCAmelCase					=    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:
																					_UpperCAmelCase					=    []
																					for i, line in enumerate(a__ ):
																												try:
																																			data.append(eval(a__ ) )
																												except Exception:
																																			print('Error evaluating line {}: {}'.format(a__    ,						a__ ) )
																																			continue
														_UpperCAmelCase					=    []
														_UpperCAmelCase					=    []
														with open('datasets/clickbait/clickbait_train_prefix.txt' ) as f:
																					for i, line in enumerate(tqdm(a__    ,						ascii=a__ ) ):
																												try:
																																			_UpperCAmelCase					=    eval(a__ )
																																			_UpperCAmelCase					=    discriminator.tokenizer.encode(d['text'] )

																																			if len(a__ ) < max_length_seq:
																																										_UpperCAmelCase					=    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

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

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

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

														_UpperCAmelCase					=    Discriminator(
														    class_size=len(a__ )    ,						pretrained_model=a__    ,						cached_mode=a__    ,						device=a__ ).to(a__ )

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

																																			if len(a__ ) < max_length_seq:
																																										_UpperCAmelCase					=    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

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

														_UpperCAmelCase					=    {
														    '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.' )

														_UpperCAmelCase					=    set()
														with open(a__ ) as f:
																					_UpperCAmelCase					=    csv.reader(a__    ,						delimiter='\t' )
																					for row in tqdm(a__    ,						ascii=a__ ):
																												if row:
																																			classes.add(row[0] )

														_UpperCAmelCase					=    sorted(a__ )
														_UpperCAmelCase					=    {c: i for i, c in enumerate(a__ )}

														_UpperCAmelCase					=    Discriminator(
														    class_size=len(a__ )    ,						pretrained_model=a__    ,						cached_mode=a__    ,						device=a__ ).to(a__ )

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

																																			try:
																																										_UpperCAmelCase					=    discriminator.tokenizer.encode(a__ )
																																										if len(a__ ) < max_length_seq:
																																																	_UpperCAmelCase					=    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

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

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

							_UpperCAmelCase					=    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...' )

														_UpperCAmelCase					=    time.time()

														_UpperCAmelCase					=    get_cached_data_loader(a__    ,						a__    ,						a__    ,						shuffle=a__    ,						device=a__ )

														_UpperCAmelCase					=    get_cached_data_loader(a__    ,						a__    ,						a__    ,						device=a__ )

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

							else:
														_UpperCAmelCase					=    torch.utils.data.DataLoader(
														    dataset=a__    ,						batch_size=a__    ,						shuffle=a__    ,						collate_fn=a__ )
														_UpperCAmelCase					=    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__ )

							_UpperCAmelCase					=    optim.Adam(discriminator.parameters()    ,						lr=0.0_001 )

							for epoch in range(a__ ):
														_UpperCAmelCase					=    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__ )

														_UpperCAmelCase					=    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__":
		lowerCAmelCase__						:Union[str, Any]         =							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=1_0, metavar='''N''', help='''Number of training epochs''')
		parser.add_argument(
		    '''--batch_size''', type=int, default=6_4, metavar='''N''', help='''input batch size for training (default: 64)'''
		)
		parser.add_argument(
		    '''--log_interval''',
		    type=int,
		    default=1_0,
		    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''')
		lowerCAmelCase__						:Dict         =							parser.parse_args()

		train_discriminator(**(vars(args)))




import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCAmelCase__						:int         =							logging.get_logger(__name__)

lowerCAmelCase__						:Optional[int]         =							{
    '''facebook/sam-vit-huge''': '''https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json''',
    '''facebook/sam-vit-large''': '''https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json''',
    '''facebook/sam-vit-base''': '''https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json''',
}

class 	__a   (       UpperCAmelCase    ):
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE=256    ,					_SCREAMING_SNAKE_CASE=1024    ,					_SCREAMING_SNAKE_CASE=16    ,					_SCREAMING_SNAKE_CASE=16    ,					_SCREAMING_SNAKE_CASE=4    ,					_SCREAMING_SNAKE_CASE="gelu"    ,					_SCREAMING_SNAKE_CASE=1e-6    ,					**_SCREAMING_SNAKE_CASE    ,					)				-> Tuple:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    hidden_size
									_UpperCAmelCase					=    image_size
									_UpperCAmelCase					=    patch_size
									_UpperCAmelCase					=    image_size // patch_size
									_UpperCAmelCase					=    mask_input_channels
									_UpperCAmelCase					=    num_point_embeddings
									_UpperCAmelCase					=    hidden_act
									_UpperCAmelCase					=    layer_norm_eps



class 	__a   (       UpperCAmelCase    ):
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE=256    ,					_SCREAMING_SNAKE_CASE="relu"    ,					_SCREAMING_SNAKE_CASE=2048    ,					_SCREAMING_SNAKE_CASE=2    ,					_SCREAMING_SNAKE_CASE=8    ,					_SCREAMING_SNAKE_CASE=2    ,					_SCREAMING_SNAKE_CASE=3    ,					_SCREAMING_SNAKE_CASE=3    ,					_SCREAMING_SNAKE_CASE=256    ,					_SCREAMING_SNAKE_CASE=1e-6    ,					**_SCREAMING_SNAKE_CASE    ,					)				-> List[Any]:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    hidden_size
									_UpperCAmelCase					=    hidden_act
									_UpperCAmelCase					=    mlp_dim
									_UpperCAmelCase					=    num_hidden_layers
									_UpperCAmelCase					=    num_attention_heads
									_UpperCAmelCase					=    attention_downsample_rate
									_UpperCAmelCase					=    num_multimask_outputs
									_UpperCAmelCase					=    iou_head_depth
									_UpperCAmelCase					=    iou_head_hidden_dim
									_UpperCAmelCase					=    layer_norm_eps



class 	__a   (       UpperCAmelCase    ):
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE=768    ,					_SCREAMING_SNAKE_CASE=256    ,					_SCREAMING_SNAKE_CASE=12    ,					_SCREAMING_SNAKE_CASE=12    ,					_SCREAMING_SNAKE_CASE=3    ,					_SCREAMING_SNAKE_CASE=1024    ,					_SCREAMING_SNAKE_CASE=16    ,					_SCREAMING_SNAKE_CASE="gelu"    ,					_SCREAMING_SNAKE_CASE=1e-0_6    ,					_SCREAMING_SNAKE_CASE=0.0    ,					_SCREAMING_SNAKE_CASE=1e-1_0    ,					_SCREAMING_SNAKE_CASE=True    ,					_SCREAMING_SNAKE_CASE=4.0    ,					_SCREAMING_SNAKE_CASE=True    ,					_SCREAMING_SNAKE_CASE=True    ,					_SCREAMING_SNAKE_CASE=14    ,					_SCREAMING_SNAKE_CASE=[2, 5, 8, 11]    ,					_SCREAMING_SNAKE_CASE=128    ,					_SCREAMING_SNAKE_CASE=None    ,					**_SCREAMING_SNAKE_CASE    ,					)				-> List[str]:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE		)

									_UpperCAmelCase					=    hidden_size
									_UpperCAmelCase					=    output_channels
									_UpperCAmelCase					=    num_hidden_layers
									_UpperCAmelCase					=    num_attention_heads
									_UpperCAmelCase					=    num_channels
									_UpperCAmelCase					=    image_size
									_UpperCAmelCase					=    patch_size
									_UpperCAmelCase					=    hidden_act
									_UpperCAmelCase					=    layer_norm_eps
									_UpperCAmelCase					=    attention_dropout
									_UpperCAmelCase					=    initializer_range
									_UpperCAmelCase					=    qkv_bias
									_UpperCAmelCase					=    mlp_ratio
									_UpperCAmelCase					=    use_abs_pos
									_UpperCAmelCase					=    use_rel_pos
									_UpperCAmelCase					=    window_size
									_UpperCAmelCase					=    global_attn_indexes
									_UpperCAmelCase					=    num_pos_feats
									_UpperCAmelCase					=    int(hidden_size * mlp_ratio		) if mlp_dim is None else mlp_dim



class 	__a   (       UpperCAmelCase    ):
		_a			:						Any    			=			'sam'
		_a			:						Any    			=			True
		def __init__(    self    ,					_SCREAMING_SNAKE_CASE=None    ,					_SCREAMING_SNAKE_CASE=None    ,					_SCREAMING_SNAKE_CASE=None    ,					_SCREAMING_SNAKE_CASE=0.02    ,					**_SCREAMING_SNAKE_CASE    ,					)				-> Tuple:




									"""simple docstring"""





									super().__init__(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    vision_config if vision_config is not None else {}
									_UpperCAmelCase					=    prompt_encoder_config if prompt_encoder_config is not None else {}
									_UpperCAmelCase					=    mask_decoder_config if mask_decoder_config is not None else {}

									if isinstance(_SCREAMING_SNAKE_CASE    ,					_SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase					=    vision_config.to_dict()
									if isinstance(_SCREAMING_SNAKE_CASE    ,					_SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase					=    prompt_encoder_config.to_dict()
									if isinstance(_SCREAMING_SNAKE_CASE    ,					_SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase					=    mask_decoder_config.to_dict()

									_UpperCAmelCase					=    SamVisionConfig(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    SamPromptEncoderConfig(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    SamMaskDecoderConfig(**_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase					=    initializer_range






		def 			UpperCAmelCase__       (    self		)				-> str:




									"""simple docstring"""





									_UpperCAmelCase					=    copy.deepcopy(self.__dict__		)
									_UpperCAmelCase					=    self.vision_config.to_dict()
									_UpperCAmelCase					=    self.prompt_encoder_config.to_dict()
									_UpperCAmelCase					=    self.mask_decoder_config.to_dict()
									_UpperCAmelCase					=    self.__class__.model_type
									return output
