


import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
lowerCAmelCase__  :Dict             =							logging.getLogger(__name__)

def 	lowerCAmelCase__			(      a__:		List[Any] ,  a__:		Any	)  ->		List[Any]:


							'''simple docstring'''





							_UpperCAmelCase					=      np.argmax(a__ ,  axis=1	)
							return np.sum(outputs == labels	)

def 	lowerCAmelCase__			(      a__:		Union[str, Any]	)  ->		Dict:


							'''simple docstring'''





							with open(a__ ,  encoding='utf_8'	) as f:
														_UpperCAmelCase					=      csv.reader(a__	)
														_UpperCAmelCase					=      []
														next(a__	)  # skip the first line
														for line in tqdm(a__	):
																					output.append((' '.join(line[1:5]	), line[5], line[6], int(line[-1]	) - 1)	)
							return output

def 	lowerCAmelCase__			(      a__:		Optional[Any] ,  a__:		Any ,  a__:		List[Any] ,  a__:		Any ,  a__:		Union[str, Any] ,  a__:		Optional[int]	)  ->		Optional[int]:


							'''simple docstring'''





							_UpperCAmelCase					=      []
							for dataset in encoded_datasets:
														_UpperCAmelCase					=      len(a__	)
														_UpperCAmelCase					=      np.zeros((n_batch, 2, input_len) ,  dtype=np.intaa	)
														_UpperCAmelCase					=      np.zeros((n_batch, 2) ,  dtype=np.intaa	)
														_UpperCAmelCase					=      np.full((n_batch, 2, input_len) ,  fill_value=-1_0_0 ,  dtype=np.intaa	)
														_UpperCAmelCase					=      np.zeros((n_batch,) ,  dtype=np.intaa	)
														for (
														    i,
														    (story, conta, conta, mc_label),
														) in enumerate(a__	):
																					_UpperCAmelCase					=      [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
																					_UpperCAmelCase					=      [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
																					_UpperCAmelCase					=      with_conta
																					_UpperCAmelCase					=      with_conta
																					_UpperCAmelCase					=      len(a__	) - 1
																					_UpperCAmelCase					=      len(a__	) - 1
																					_UpperCAmelCase					=      with_conta
																					_UpperCAmelCase					=      with_conta
																					_UpperCAmelCase					=      mc_label
														_UpperCAmelCase					=      (input_ids, mc_token_ids, lm_labels, mc_labels)
														tensor_datasets.append(tuple(torch.tensor(a__	) for t in all_inputs	)	)
							return tensor_datasets

def 	lowerCAmelCase__			(      )  ->		Dict:


							'''simple docstring'''





							_UpperCAmelCase					=      argparse.ArgumentParser()
							parser.add_argument('--model_name' ,  type=a__ ,  default='openai-gpt' ,  help='pretrained model name'	)
							parser.add_argument('--do_train' ,  action='store_true' ,  help='Whether to run training.'	)
							parser.add_argument('--do_eval' ,  action='store_true' ,  help='Whether to run eval on the dev set.'	)
							parser.add_argument(
							    '--output_dir' ,  default=a__ ,  type=a__ ,  required=a__ ,  help='The output directory where the model predictions and checkpoints will be written.' ,  )
							parser.add_argument('--train_dataset' ,  type=a__ ,  default=''	)
							parser.add_argument('--eval_dataset' ,  type=a__ ,  default=''	)
							parser.add_argument('--seed' ,  type=a__ ,  default=4_2	)
							parser.add_argument('--num_train_epochs' ,  type=a__ ,  default=3	)
							parser.add_argument('--train_batch_size' ,  type=a__ ,  default=8	)
							parser.add_argument('--eval_batch_size' ,  type=a__ ,  default=1_6	)
							parser.add_argument('--adam_epsilon' ,  default=1e-8 ,  type=a__ ,  help='Epsilon for Adam optimizer.'	)
							parser.add_argument('--max_grad_norm' ,  type=a__ ,  default=1	)
							parser.add_argument(
							    '--max_steps' ,  default=-1 ,  type=a__ ,  help=(
							        'If > 0: set total number of training                         steps to perform. Override num_train_epochs.'
							    ) ,  )
							parser.add_argument(
							    '--gradient_accumulation_steps' ,  type=a__ ,  default=1 ,  help='Number of updates steps to accumulate before                        performing a backward/update pass.' ,  )
							parser.add_argument('--learning_rate' ,  type=a__ ,  default=6.25e-5	)
							parser.add_argument('--warmup_steps' ,  default=0 ,  type=a__ ,  help='Linear warmup over warmup_steps.'	)
							parser.add_argument('--lr_schedule' ,  type=a__ ,  default='warmup_linear'	)
							parser.add_argument('--weight_decay' ,  type=a__ ,  default=0.01	)
							parser.add_argument('--lm_coef' ,  type=a__ ,  default=0.9	)
							parser.add_argument('--n_valid' ,  type=a__ ,  default=3_7_4	)

							parser.add_argument('--server_ip' ,  type=a__ ,  default='' ,  help='Can be used for distant debugging.'	)
							parser.add_argument('--server_port' ,  type=a__ ,  default='' ,  help='Can be used for distant debugging.'	)
							_UpperCAmelCase					=      parser.parse_args()
							print(a__	)

							if args.server_ip and args.server_port:
														# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
														import ptvsd

														print('Waiting for debugger attach'	)
														ptvsd.enable_attach(address=(args.server_ip, args.server_port) ,  redirect_output=a__	)
														ptvsd.wait_for_attach()

							random.seed(args.seed	)
							np.random.seed(args.seed	)
							torch.manual_seed(args.seed	)
							torch.cuda.manual_seed_all(args.seed	)

							_UpperCAmelCase					=      torch.device('cuda' if torch.cuda.is_available() else 'cpu'	)
							_UpperCAmelCase					=      torch.cuda.device_count()
							logger.info('device: {}, n_gpu {}'.format(a__ ,  a__	)	)

							if not args.do_train and not args.do_eval:
														raise ValueError('At least one of `do_train` or `do_eval` must be True.'	)

							if not os.path.exists(args.output_dir	):
														os.makedirs(args.output_dir	)

							# Load tokenizer and model
							# This loading functions also add new tokens and embeddings called `special tokens`
							# These new embeddings will be fine-tuned on the RocStories dataset
							_UpperCAmelCase					=      ['_start_', '_delimiter_', '_classify_']
							_UpperCAmelCase					=      OpenAIGPTTokenizer.from_pretrained(args.model_name	)
							tokenizer.add_tokens(a__	)
							_UpperCAmelCase					=      tokenizer.convert_tokens_to_ids(a__	)
							_UpperCAmelCase					=      OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name	)
							model.resize_token_embeddings(len(a__	)	)
							model.to(a__	)

							# Load and encode the datasets
							def tokenize_and_encode(a__:		Optional[Any]	):
														if isinstance(a__ ,  a__	):
																					return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(a__	)	)
														elif isinstance(a__ ,  a__	):
																					return obj
														return [tokenize_and_encode(a__	) for o in obj]

							logger.info('Encoding dataset...'	)
							_UpperCAmelCase					=      load_rocstories_dataset(args.train_dataset	)
							_UpperCAmelCase					=      load_rocstories_dataset(args.eval_dataset	)
							_UpperCAmelCase					=      (train_dataset, eval_dataset)
							_UpperCAmelCase					=      tokenize_and_encode(a__	)

							# Compute the max input length for the Transformer
							_UpperCAmelCase					=      model.config.n_positions // 2 - 2
							_UpperCAmelCase					=      max(
							    len(story[:max_length]	) + max(len(conta[:max_length]	) ,  len(conta[:max_length]	)	) + 3
							    for dataset in encoded_datasets
							    for story, conta, conta, _ in dataset	)
							_UpperCAmelCase					=      min(a__ ,  model.config.n_positions	)  # Max size of input for the pre-trained model

							# Prepare inputs tensors and dataloaders
							_UpperCAmelCase					=      pre_process_datasets(a__ ,  a__ ,  a__ ,  *a__	)
							_UpperCAmelCase		,	_UpperCAmelCase					=      tensor_datasets[0], tensor_datasets[1]

							_UpperCAmelCase					=      TensorDataset(*a__	)
							_UpperCAmelCase					=      RandomSampler(a__	)
							_UpperCAmelCase					=      DataLoader(a__ ,  sampler=a__ ,  batch_size=args.train_batch_size	)

							_UpperCAmelCase					=      TensorDataset(*a__	)
							_UpperCAmelCase					=      SequentialSampler(a__	)
							_UpperCAmelCase					=      DataLoader(a__ ,  sampler=a__ ,  batch_size=args.eval_batch_size	)

							# Prepare optimizer
							if args.do_train:
														if args.max_steps > 0:
																					_UpperCAmelCase					=      args.max_steps
																					_UpperCAmelCase					=      args.max_steps // (len(a__	) // args.gradient_accumulation_steps) + 1
														else:
																					_UpperCAmelCase					=      len(a__	) // args.gradient_accumulation_steps * args.num_train_epochs

														_UpperCAmelCase					=      list(model.named_parameters()	)
														_UpperCAmelCase					=      ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
														_UpperCAmelCase					=      [
														    {
														        'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay	)],
														        'weight_decay': args.weight_decay,
														    },
														    {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay	)], 'weight_decay': 0.0},
														]
														_UpperCAmelCase					=      AdamW(a__ ,  lr=args.learning_rate ,  eps=args.adam_epsilon	)
														_UpperCAmelCase					=      get_linear_schedule_with_warmup(
														    a__ ,  num_warmup_steps=args.warmup_steps ,  num_training_steps=a__	)

							if args.do_train:
														_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase					=      0, 0, None
														model.train()
														for _ in trange(int(args.num_train_epochs	) ,  desc='Epoch'	):
																					_UpperCAmelCase					=      0
																					_UpperCAmelCase					=      0
																					_UpperCAmelCase					=      tqdm(a__ ,  desc='Training'	)
																					for step, batch in enumerate(a__	):
																												_UpperCAmelCase					=      tuple(t.to(a__	) for t in batch	)
																												_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase					=      batch
																												_UpperCAmelCase					=      model(a__ ,  mc_token_ids=a__ ,  lm_labels=a__ ,  mc_labels=a__	)
																												_UpperCAmelCase					=      args.lm_coef * losses[0] + losses[1]
																												loss.backward()
																												optimizer.step()
																												scheduler.step()
																												optimizer.zero_grad()
																												tr_loss += loss.item()
																												_UpperCAmelCase					=      (
																												    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
																												)
																												nb_tr_steps += 1
																												_UpperCAmelCase					=      'Training loss: {:.2e} lr: {:.2e}'.format(a__ ,  scheduler.get_lr()[0]	)

    # Save a trained model
							if args.do_train:
														# Save a trained model, configuration and tokenizer
														_UpperCAmelCase					=      model.module if hasattr(a__ ,  'module'	) else model  # Only save the model itself

														# If we save using the predefined names, we can load using `from_pretrained`
														_UpperCAmelCase					=      os.path.join(args.output_dir ,  a__	)
														_UpperCAmelCase					=      os.path.join(args.output_dir ,  a__	)

														torch.save(model_to_save.state_dict() ,  a__	)
														model_to_save.config.to_json_file(a__	)
														tokenizer.save_vocabulary(args.output_dir	)

														# Load a trained model and vocabulary that you have fine-tuned
														_UpperCAmelCase					=      OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir	)
														_UpperCAmelCase					=      OpenAIGPTTokenizer.from_pretrained(args.output_dir	)
														model.to(a__	)

							if args.do_eval:
														model.eval()
														_UpperCAmelCase		,	_UpperCAmelCase					=      0, 0
														_UpperCAmelCase		,	_UpperCAmelCase					=      0, 0
														for batch in tqdm(a__ ,  desc='Evaluating'	):
																					_UpperCAmelCase					=      tuple(t.to(a__	) for t in batch	)
																					_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase					=      batch
																					with torch.no_grad():
																												_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase		,	_UpperCAmelCase					=      model(
																												    a__ ,  mc_token_ids=a__ ,  lm_labels=a__ ,  mc_labels=a__	)

																					_UpperCAmelCase					=      mc_logits.detach().cpu().numpy()
																					_UpperCAmelCase					=      mc_labels.to('cpu'	).numpy()
																					_UpperCAmelCase					=      accuracy(a__ ,  a__	)

																					eval_loss += mc_loss.mean().item()
																					eval_accuracy += tmp_eval_accuracy

																					nb_eval_examples += input_ids.size(0	)
																					nb_eval_steps += 1

														_UpperCAmelCase					=      eval_loss / nb_eval_steps
														_UpperCAmelCase					=      eval_accuracy / nb_eval_examples
														_UpperCAmelCase					=      tr_loss / nb_tr_steps if args.do_train else None
														_UpperCAmelCase					=      {'eval_loss': eval_loss, 'eval_accuracy': eval_accuracy, 'train_loss': train_loss}

														_UpperCAmelCase					=      os.path.join(args.output_dir ,  'eval_results.txt'	)
														with open(a__ ,  'w'	) as writer:
																					logger.info('***** Eval results *****'	)
																					for key in sorted(result.keys()	):
																												logger.info('  %s = %s' ,  a__ ,  str(result[key]	)	)
																												writer.write('%s = %s\n' % (key, str(result[key]	))	)


if __name__ == "__main__":
		main()




import argparse
import re

import requests
import torch

# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode

from transformers import (
    BertTokenizer,
    BlipConfig,
    BlipForConditionalGeneration,
    BlipForImageTextRetrieval,
    BlipForQuestionAnswering,
)

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


							'''simple docstring'''





							_UpperCAmelCase					=      'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg'
							_UpperCAmelCase					=      Image.open(requests.get(a__      ,  stream=a__	).raw	).convert('RGB'	)

							_UpperCAmelCase					=      transforms.Compose(
							    [
							        transforms.Resize((image_size, image_size)      ,  interpolation=InterpolationMode.BICUBIC	),
							        transforms.ToTensor(),
							        transforms.Normalize((0.48_145_466, 0.4_578_275, 0.40_821_073)      ,  (0.26_862_954, 0.26_130_258, 0.27_577_711)	),
							    ]	)
							_UpperCAmelCase					=      transform(a__	).unsqueeze(0	).to(a__	)
							return image

def 	lowerCAmelCase__			(      a__:		Optional[int]	)  ->		int:


							'''simple docstring'''





							if "visual_encoder" in key:
														_UpperCAmelCase					=      re.sub('visual_encoder*'      ,  'vision_model.encoder'      ,  a__	)
							if "blocks" in key:
														_UpperCAmelCase					=      re.sub(R'blocks'      ,  'layers'      ,  a__	)
							if "attn" in key:
														_UpperCAmelCase					=      re.sub(R'attn'      ,  'self_attn'      ,  a__	)
							if "norm1" in key:
														_UpperCAmelCase					=      re.sub(R'norm1'      ,  'layer_norm1'      ,  a__	)
							if "norm2" in key:
														_UpperCAmelCase					=      re.sub(R'norm2'      ,  'layer_norm2'      ,  a__	)
							if "encoder.norm" in key:
														_UpperCAmelCase					=      re.sub(R'encoder.norm'      ,  'post_layernorm'      ,  a__	)
							if "encoder.patch_embed.proj" in key:
														_UpperCAmelCase					=      re.sub(R'encoder.patch_embed.proj'      ,  'embeddings.patch_embedding'      ,  a__	)

							if "encoder.pos_embed" in key:
														_UpperCAmelCase					=      re.sub(R'encoder.pos_embed'      ,  'embeddings.position_embedding'      ,  a__	)
							if "encoder.cls_token" in key:
														_UpperCAmelCase					=      re.sub(R'encoder.cls_token'      ,  'embeddings.class_embedding'      ,  a__	)

							if "self_attn" in key:
														_UpperCAmelCase					=      re.sub(R'self_attn.proj'      ,  'self_attn.projection'      ,  a__	)

							return key

@torch.no_grad()
def 	lowerCAmelCase__			(      a__:		Optional[Any]      ,  a__:		List[str]=None	)  ->		Optional[Any]:


							'''simple docstring'''





							if config_path is not None:
														_UpperCAmelCase					=      BlipConfig.from_pretrained(a__	)
							else:
														_UpperCAmelCase					=      BlipConfig(projection_dim=5_1_2      ,  text_config={}      ,  vision_config={}	)

							_UpperCAmelCase					=      BlipForConditionalGeneration(a__	).eval()

							_UpperCAmelCase					=      'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth'

							_UpperCAmelCase					=      blip_decoder(pretrained=a__      ,  image_size=3_8_4      ,  vit='base'	)
							_UpperCAmelCase					=      pt_model.eval()

							_UpperCAmelCase					=      pt_model.state_dict()
							for key in modified_state_dict.copy():
														_UpperCAmelCase					=      modified_state_dict.pop(a__	)
														_UpperCAmelCase					=      rename_key(a__	)
														_UpperCAmelCase					=      value

							hf_model.load_state_dict(a__	)

							_UpperCAmelCase					=      3_8_4
							_UpperCAmelCase					=      load_demo_image(image_size=a__      ,  device='cpu'	)
							_UpperCAmelCase					=      BertTokenizer.from_pretrained('bert-base-uncased'	)
							_UpperCAmelCase					=      tokenizer(['a picture of']	).input_ids

							_UpperCAmelCase					=      hf_model.generate(a__      ,  a__	)

							assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 3_8_6_1, 1_9_9_7, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2]

							_UpperCAmelCase					=      hf_model.generate(a__	)

							assert out[0].tolist() == [3_0_5_2_2, 1_0_3_7, 2_4_5_0, 3_5_6_4, 2_0_0_6, 1_9_9_6, 3_5_0_9, 2_0_0_7, 2_0_1_4, 3_8_9_9, 1_0_2]

							if pytorch_dump_folder_path is not None:
														hf_model.save_pretrained(a__	)

							# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
							_UpperCAmelCase					=      (
							    'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'
							)

							_UpperCAmelCase					=      blip_vqa(pretrained=a__      ,  image_size=a__      ,  vit='base'	)
							vqa_model.eval()

							_UpperCAmelCase					=      vqa_model.state_dict()
							for key in modified_state_dict.copy():
														_UpperCAmelCase					=      modified_state_dict.pop(a__	)
														_UpperCAmelCase					=      rename_key(a__	)
														_UpperCAmelCase					=      value

							_UpperCAmelCase					=      BlipForQuestionAnswering(a__	)

							hf_vqa_model.load_state_dict(a__	)

							_UpperCAmelCase					=      ['How many dogs are in this image?']
							_UpperCAmelCase					=      tokenizer(a__      ,  return_tensors='pt'	).input_ids

							_UpperCAmelCase					=      hf_vqa_model.generate(a__      ,  a__	)
							print(tokenizer.decode(answer[0]	)	)

							assert tokenizer.decode(answer[0]	) == "[UNK] 1 [SEP]"
							if pytorch_dump_folder_path is not None:
														hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '_vqa'	)

							_UpperCAmelCase					=      'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'

							_UpperCAmelCase					=      blip_itm(pretrained=a__      ,  image_size=a__      ,  vit='base'	)
							itm_model.eval()

							_UpperCAmelCase					=      itm_model.state_dict()
							for key in modified_state_dict.copy():
														_UpperCAmelCase					=      modified_state_dict.pop(a__	)
														_UpperCAmelCase					=      rename_key(a__	)
														_UpperCAmelCase					=      value

							_UpperCAmelCase					=      BlipForImageTextRetrieval(a__	)

							_UpperCAmelCase					=      ['A picture of a woman with a dog sitting in a beach']
							_UpperCAmelCase					=      tokenizer(
							    a__      ,  return_tensors='pt'      ,  padding='max_length'      ,  truncation=a__      ,  max_length=3_5      ,  ).input_ids

							hf_itm_model.load_state_dict(a__	)
							hf_itm_model.eval()

							_UpperCAmelCase					=      hf_itm_model(a__      ,  a__      ,  use_itm_head=a__	)
							_UpperCAmelCase					=      hf_itm_model(a__      ,  a__      ,  use_itm_head=a__	)

							assert out[0].item() == 0.2_110_687_494_277_954
							assert torch.nn.functional.softmax(out_itm[0]      ,  dim=1	)[:, 1].item() == 0.45_698_845_386_505_127

							if pytorch_dump_folder_path is not None:
														hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm'	)


if __name__ == "__main__":
		lowerCAmelCase__  :int             =							argparse.ArgumentParser()
		parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
		parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
		lowerCAmelCase__  :List[Any]             =							parser.parse_args()

		convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
