

"""simple docstring"""




import argparse

import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download

from transformers import (
    CLIPTokenizer,
    CLIPTokenizerFast,
    VideoMAEImageProcessor,
    XCLIPConfig,
    XCLIPModel,
    XCLIPProcessor,
    XCLIPTextConfig,
    XCLIPVisionConfig,
)

def 	A       (     snake_case__		,				snake_case__    ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__								=      XCLIPTextConfig()

			# derive patch size from model name
			SCREAMING_SNAKE_CASE__								=      model_name.find("""patch"""    )
			SCREAMING_SNAKE_CASE__								=      int(model_name[start_idx + len("""patch"""    ) : start_idx + len("""patch"""    ) + 2]    )
			SCREAMING_SNAKE_CASE__								=      XCLIPVisionConfig(patch_size=_snake_case		,				num_frames=_snake_case    )

			if "large" in model_name:
						SCREAMING_SNAKE_CASE__								=      7_68
						SCREAMING_SNAKE_CASE__								=      30_72
						SCREAMING_SNAKE_CASE__								=      12

						SCREAMING_SNAKE_CASE__								=      10_24
						SCREAMING_SNAKE_CASE__								=      40_96
						SCREAMING_SNAKE_CASE__								=      16
						SCREAMING_SNAKE_CASE__								=      24
						SCREAMING_SNAKE_CASE__								=      7_68
						SCREAMING_SNAKE_CASE__								=      30_72

			if model_name == "xclip-large-patch14-16-frames":
						SCREAMING_SNAKE_CASE__								=      3_36

			SCREAMING_SNAKE_CASE__								=      XCLIPConfig.from_text_vision_configs(_snake_case		,				_snake_case    )

			if "large" in model_name:
						SCREAMING_SNAKE_CASE__								=      7_68

			return config

def 	A       (     snake_case__    ):




			'''simple docstring'''


			if name == "token_embedding.weight":
						SCREAMING_SNAKE_CASE__								=      name.replace("""token_embedding.weight"""		,				"""text_model.embeddings.token_embedding.weight"""    )
			if name == "positional_embedding":
						SCREAMING_SNAKE_CASE__								=      name.replace("""positional_embedding"""		,				"""text_model.embeddings.position_embedding.weight"""    )
			if "ln_1" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""ln_1"""		,				"""layer_norm1"""    )
			if "ln_2" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""ln_2"""		,				"""layer_norm2"""    )
			if "c_fc" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""c_fc"""		,				"""fc1"""    )
			if "c_proj" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""c_proj"""		,				"""fc2"""    )
			if name.startswith("""transformer.resblocks"""    ):
						SCREAMING_SNAKE_CASE__								=      name.replace("""transformer.resblocks"""		,				"""text_model.encoder.layers"""    )
			if "attn.out_proj" in name and "message" not in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""attn.out_proj"""		,				"""self_attn.out_proj"""    )
			if "ln_final" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""ln_final"""		,				"""text_model.final_layer_norm"""    )
			# visual encoder
			if name == "visual.class_embedding":
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.class_embedding"""		,				"""vision_model.embeddings.class_embedding"""    )
			if name == "visual.positional_embedding":
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.positional_embedding"""		,				"""vision_model.embeddings.position_embedding.weight"""    )
			if name.startswith("""visual.transformer.resblocks"""    ):
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.transformer.resblocks"""		,				"""vision_model.encoder.layers"""    )
			if "visual.conv1" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.conv1"""		,				"""vision_model.embeddings.patch_embedding"""    )
			if "visual.ln_pre" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.ln_pre"""		,				"""vision_model.pre_layernorm"""    )
			if "visual.ln_post" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.ln_post"""		,				"""vision_model.post_layernorm"""    )
			if "visual.proj" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""visual.proj"""		,				"""visual_projection.weight"""    )
			if "text_projection" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""text_projection"""		,				"""text_projection.weight"""    )
			# things on top
			if "prompts_visual_proj" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""prompts_visual_proj"""		,				"""prompts_visual_projection"""    )
			if "prompts_visual_ln" in name:
						SCREAMING_SNAKE_CASE__								=      name.replace("""prompts_visual_ln"""		,				"""prompts_visual_layernorm"""    )
			# mit
			if name == "mit.positional_embedding":
						SCREAMING_SNAKE_CASE__								=      name.replace("""positional"""		,				"""position"""    )
			if name.startswith("""mit.resblocks"""    ):
						SCREAMING_SNAKE_CASE__								=      name.replace("""mit.resblocks"""		,				"""mit.encoder.layers"""    )
			# prompts generator
			if name.startswith("""prompts_generator.norm"""    ):
						SCREAMING_SNAKE_CASE__								=      name.replace("""prompts_generator.norm"""		,				"""prompts_generator.layernorm"""    )

			return name

def 	A       (     snake_case__		,				snake_case__    ):




			'''simple docstring'''


			for key in orig_state_dict.copy().keys():
						SCREAMING_SNAKE_CASE__								=      orig_state_dict.pop(_snake_case    )

						if "attn.in_proj" in key:
									SCREAMING_SNAKE_CASE__								=      key.split("""."""    )
									if key.startswith("""visual"""    ):
												SCREAMING_SNAKE_CASE__								=      key_split[3]
												SCREAMING_SNAKE_CASE__								=      config.vision_config.hidden_size
												if "message_attn" in key:
															if "weight" in key:
																		SCREAMING_SNAKE_CASE__								=      val[
																		    :dim, :
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    dim : dim * 2, :
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    -dim:, :
																		]
															else:
																		SCREAMING_SNAKE_CASE__								=      val[
																		    :dim
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    dim : dim * 2
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    -dim:
																		]
												else:
															if "weight" in key:
																		SCREAMING_SNAKE_CASE__								=      val[
																		    :dim, :
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    dim : dim * 2, :
																		]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    -dim:, :
																		]
															else:
																		SCREAMING_SNAKE_CASE__								=      val[:dim]
																		SCREAMING_SNAKE_CASE__								=      val[
																		    dim : dim * 2
																		]
																		SCREAMING_SNAKE_CASE__								=      val[-dim:]
									elif key.startswith("""mit"""    ):
												SCREAMING_SNAKE_CASE__								=      key_split[2]
												SCREAMING_SNAKE_CASE__								=      config.vision_config.mit_hidden_size
												if "weight" in key:
															SCREAMING_SNAKE_CASE__								=      val[:dim, :]
															SCREAMING_SNAKE_CASE__								=      val[dim : dim * 2, :]
															SCREAMING_SNAKE_CASE__								=      val[-dim:, :]
												else:
															SCREAMING_SNAKE_CASE__								=      val[:dim]
															SCREAMING_SNAKE_CASE__								=      val[dim : dim * 2]
															SCREAMING_SNAKE_CASE__								=      val[-dim:]
									else:
												SCREAMING_SNAKE_CASE__								=      key_split[2]
												SCREAMING_SNAKE_CASE__								=      config.text_config.hidden_size
												if "weight" in key:
															SCREAMING_SNAKE_CASE__								=      val[:dim, :]
															SCREAMING_SNAKE_CASE__								=      val[
															    dim : dim * 2, :
															]
															SCREAMING_SNAKE_CASE__								=      val[-dim:, :]
												else:
															SCREAMING_SNAKE_CASE__								=      val[:dim]
															SCREAMING_SNAKE_CASE__								=      val[
															    dim : dim * 2
															]
															SCREAMING_SNAKE_CASE__								=      val[-dim:]
						else:
									SCREAMING_SNAKE_CASE__								=      rename_key(_snake_case    )
									if new_key_name in ["visual_projection.weight", "text_projection.weight"]:
												SCREAMING_SNAKE_CASE__								=      val.T
									SCREAMING_SNAKE_CASE__								=      val

			return orig_state_dict

def 	A       (     snake_case__    ):




			'''simple docstring'''


			if num_frames == 8:
						SCREAMING_SNAKE_CASE__								=      """eating_spaghetti_8_frames.npy"""
			elif num_frames == 16:
						SCREAMING_SNAKE_CASE__								=      """eating_spaghetti.npy"""
			elif num_frames == 32:
						SCREAMING_SNAKE_CASE__								=      """eating_spaghetti_32_frames.npy"""
			SCREAMING_SNAKE_CASE__								=      hf_hub_download(
			    repo_id="""hf-internal-testing/spaghetti-video"""		,				filename=_snake_case		,				repo_type="""dataset"""		,				)
			SCREAMING_SNAKE_CASE__								=      np.load(_snake_case    )
			return list(_snake_case    )

def 	A       (     snake_case__		,				snake_case__=None		,				snake_case__=False    ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__								=      {
			    # fully supervised kinetics-400 checkpoints
			    """xclip-base-patch32""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_8.pth""",
			    """xclip-base-patch32-16-frames""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_32_16.pth"""
			    ),
			    """xclip-base-patch16""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_8.pth""",
			    """xclip-base-patch16-16-frames""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k400_16_16.pth"""
			    ),
			    """xclip-large-patch14""": """https://drive.google.com/u/0/uc?id=1NUOImq0o5DlQTST17iIP3vG7DgmHQuCx&amp;export=download&amp;confirm=t&amp;uuid=b26caedc-88e2-473e-830a-9d158b653cdb""",
			    """xclip-large-patch14-16-frames""": """https://drive.google.com/u/0/uc?id=1FOYgnJc097OJ4lGwtRCCydQyVPJEOH7d&amp;export=download&amp;confirm=t&amp;uuid=538fa810-e671-4050-b385-9a623f89804f""",
			    # fully supervised kinetics-600 checkpoints
			    """xclip-base-patch16-kinetics-600""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_8.pth"""
			    ),
			    """xclip-base-patch16-kinetics-600-16-frames""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/k600_16_16.pth"""
			    ),
			    """xclip-large-patch14-kinetics-600""": """https://drive.google.com/u/0/uc?id=1FV8C1INuM91sLAN4ImjzePLIlpMSihwV&amp;export=download&amp;confirm=t&amp;uuid=141d4977-4a65-44ae-864f-4b0c19f838be""",
			    # few shot
			    """xclip-base-patch16-hmdb-2-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_2.pth"""
			    ),
			    """xclip-base-patch16-hmdb-4-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_4.pth"""
			    ),
			    """xclip-base-patch16-hmdb-8-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_8.pth"""
			    ),
			    """xclip-base-patch16-hmdb-16-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_hmdb_16.pth"""
			    ),
			    """xclip-base-patch16-ucf-2-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_2.pth"""
			    ),
			    """xclip-base-patch16-ucf-4-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_4.pth"""
			    ),
			    """xclip-base-patch16-ucf-8-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_8.pth"""
			    ),
			    """xclip-base-patch16-ucf-16-shot""": (
			        """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/few_ucf_16.pth"""
			    ),
			    # zero shot
			    """xclip-base-patch16-zero-shot""": """https://github.com/nbl97/X-CLIP_Model_Zoo/releases/download/v1.0/zero.pth""",
			}

			SCREAMING_SNAKE_CASE__								=      model_to_url[model_name]
			SCREAMING_SNAKE_CASE__								=      8
			if "16-frames" in model_name:
						SCREAMING_SNAKE_CASE__								=      16
			elif "shot" in model_name:
						SCREAMING_SNAKE_CASE__								=      32

			SCREAMING_SNAKE_CASE__								=      get_xclip_config(_snake_case		,				_snake_case    )
			SCREAMING_SNAKE_CASE__								=      XCLIPModel(_snake_case    )
			model.eval()

			if "drive" in checkpoint_url:
						SCREAMING_SNAKE_CASE__								=      """pytorch_model.bin"""
						gdown.cached_download(_snake_case		,				_snake_case		,				quiet=_snake_case    )
						SCREAMING_SNAKE_CASE__								=      torch.load(_snake_case		,				map_location="""cpu"""    )["""model"""]
			else:
						SCREAMING_SNAKE_CASE__								=      torch.hub.load_state_dict_from_url(_snake_case    )["""model"""]

			SCREAMING_SNAKE_CASE__								=      convert_state_dict(_snake_case		,				_snake_case    )

			SCREAMING_SNAKE_CASE__								=      XCLIPModel(_snake_case    )
			SCREAMING_SNAKE_CASE__							,		SCREAMING_SNAKE_CASE__								=      model.load_state_dict(_snake_case		,				strict=_snake_case    )
			assert missing_keys == ["text_model.embeddings.position_ids", "vision_model.embeddings.position_ids"]
			model.eval()

			SCREAMING_SNAKE_CASE__								=      3_36 if model_name == """xclip-large-patch14-16-frames""" else 2_24
			SCREAMING_SNAKE_CASE__								=      VideoMAEImageProcessor(size=_snake_case    )
			SCREAMING_SNAKE_CASE__								=      CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32"""    )
			SCREAMING_SNAKE_CASE__								=      CLIPTokenizerFast.from_pretrained("""openai/clip-vit-base-patch32"""    )
			SCREAMING_SNAKE_CASE__								=      XCLIPProcessor(image_processor=_snake_case		,				tokenizer=_snake_case    )

			SCREAMING_SNAKE_CASE__								=      prepare_video(_snake_case    )
			SCREAMING_SNAKE_CASE__								=      processor(
			    text=["""playing sports""", """eating spaghetti""", """go shopping"""]		,				videos=_snake_case		,				return_tensors="""pt"""		,				padding=_snake_case    )

			print("""Shape of pixel values:"""		,				inputs.pixel_values.shape    )

			with torch.no_grad():
						SCREAMING_SNAKE_CASE__								=      model(**_snake_case    )

			# Verify outputs
			SCREAMING_SNAKE_CASE__								=      outputs.logits_per_video
			SCREAMING_SNAKE_CASE__								=      logits_per_video.softmax(dim=1    )
			print("""Probs:"""		,				_snake_case    )
			# kinetics-400
			if model_name == "xclip-base-patch32":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.00_19, 0.99_51, 0.00_30]]    )
			elif model_name == "xclip-base-patch32-16-frames":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[7.0_999e-04, 9.9_883e-01, 4.5_580e-04]]    )
			elif model_name == "xclip-base-patch16":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.00_83, 0.96_81, 0.02_36]]    )
			elif model_name == "xclip-base-patch16-16-frames":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[7.6_937e-04, 9.9_728e-01, 1.9_473e-03]]    )
			elif model_name == "xclip-large-patch14":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.00_62, 0.98_64, 0.00_75]]    )
			elif model_name == "xclip-large-patch14-16-frames":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[3.3_877e-04, 9.9_937e-01, 2.8_888e-04]]    )
			# kinetics-600
			elif model_name == "xclip-base-patch16-kinetics-600":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.05_55, 0.89_14, 0.05_31]]    )
			elif model_name == "xclip-base-patch16-kinetics-600-16-frames":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[3.8_554e-04, 9.9_929e-01, 3.2_754e-04]]    )
			elif model_name == "xclip-large-patch14-kinetics-600":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.00_36, 0.99_20, 0.00_45]]    )
			# few shot
			elif model_name == "xclip-base-patch16-hmdb-2-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[7.1_890e-06, 9.9_994e-01, 5.6_559e-05]]    )
			elif model_name == "xclip-base-patch16-hmdb-4-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[1.0_320e-05, 9.9_993e-01, 6.2_435e-05]]    )
			elif model_name == "xclip-base-patch16-hmdb-8-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[4.1_377e-06, 9.9_990e-01, 9.8_386e-05]]    )
			elif model_name == "xclip-base-patch16-hmdb-16-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[4.1_347e-05, 9.9_962e-01, 3.3_411e-04]]    )
			elif model_name == "xclip-base-patch16-ucf-2-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]]    )
			elif model_name == "xclip-base-patch16-ucf-4-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[8.5_857e-05, 9.9_928e-01, 6.3_291e-04]]    )
			elif model_name == "xclip-base-patch16-ucf-8-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[0.00_27, 0.99_04, 0.00_70]]    )
			elif model_name == "xclip-base-patch16-ucf-16-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[9.8_219e-04, 9.9_593e-01, 3.0_863e-03]]    )
			# zero shot
			elif model_name == "xclip-base-patch16-zero-shot":
						SCREAMING_SNAKE_CASE__								=      torch.tensor([[3.5_082e-04, 9.9_785e-01, 1.7_966e-03]]    )
			else:
						raise ValueError(f"""Model name {model_name} not supported"""    )
			assert torch.allclose(_snake_case		,				_snake_case		,				atol=1e-3    )
			print("""Looks ok!"""    )

			if pytorch_dump_folder_path is not None:
						print(f"""Saving model {model_name} to {pytorch_dump_folder_path}"""    )
						model.save_pretrained(_snake_case    )

			if push_to_hub:
						print("""Pushing model, processor and slow tokenizer files to the hub..."""    )
						model.push_to_hub(_snake_case		,				organization="""nielsr"""    )
						processor.push_to_hub(_snake_case		,				organization="""nielsr"""    )
						slow_tokenizer.push_to_hub(_snake_case		,				organization="""nielsr"""    )


if __name__ == "__main__":
						A_							:			Any											= argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    "--model_name",
						    default="xclip-base-patch32",
						    type=str,
						    help="Name of the model.",
						)
						parser.add_argument(
						    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
						)
						parser.add_argument(
						    "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
						)

						A_							:			int											= parser.parse_args()
						convert_xclip_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





"""simple docstring"""




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
)
A_							:			Any											= logging.getLogger(__name__)

def 	A       (     snake_case__		,				snake_case__    ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__								=      np.argmax(snake_case__		,				axis=1    )
			return np.sum(outputs == labels    )

def 	A       (     snake_case__    ):




			'''simple docstring'''


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

def 	A       (     snake_case__		,				snake_case__		,				snake_case__		,				snake_case__		,				snake_case__		,				snake_case__    ):




			'''simple docstring'''


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

def 	A       (     ):




			'''simple docstring'''


			SCREAMING_SNAKE_CASE__								=      argparse.ArgumentParser()
			parser.add_argument("""--model_name"""		,				type=snake_case__		,				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=snake_case__		,				type=snake_case__		,				required=snake_case__		,				help="""The output directory where the model predictions and checkpoints will be written."""		,				)
			parser.add_argument("""--train_dataset"""		,				type=snake_case__		,				default=""""""    )
			parser.add_argument("""--eval_dataset"""		,				type=snake_case__		,				default=""""""    )
			parser.add_argument("""--seed"""		,				type=snake_case__		,				default=42    )
			parser.add_argument("""--num_train_epochs"""		,				type=snake_case__		,				default=3    )
			parser.add_argument("""--train_batch_size"""		,				type=snake_case__		,				default=8    )
			parser.add_argument("""--eval_batch_size"""		,				type=snake_case__		,				default=16    )
			parser.add_argument("""--adam_epsilon"""		,				default=1e-8		,				type=snake_case__		,				help="""Epsilon for Adam optimizer."""    )
			parser.add_argument("""--max_grad_norm"""		,				type=snake_case__		,				default=1    )
			parser.add_argument(
			    """--max_steps"""		,				default=-1		,				type=snake_case__		,				help=(
			        """If > 0: set total number of training                         steps to perform. Override num_train_epochs."""
			    )		,				)
			parser.add_argument(
			    """--gradient_accumulation_steps"""		,				type=snake_case__		,				default=1		,				help="""Number of updates steps to accumulate before                        performing a backward/update pass."""		,				)
			parser.add_argument("""--learning_rate"""		,				type=snake_case__		,				default=6.25e-5    )
			parser.add_argument("""--warmup_steps"""		,				default=0		,				type=snake_case__		,				help="""Linear warmup over warmup_steps."""    )
			parser.add_argument("""--lr_schedule"""		,				type=snake_case__		,				default="""warmup_linear"""    )
			parser.add_argument("""--weight_decay"""		,				type=snake_case__		,				default=0.01    )
			parser.add_argument("""--lm_coef"""		,				type=snake_case__		,				default=0.9    )
			parser.add_argument("""--n_valid"""		,				type=snake_case__		,				default=3_74    )

			parser.add_argument("""--server_ip"""		,				type=snake_case__		,				default=""""""		,				help="""Can be used for distant debugging."""    )
			parser.add_argument("""--server_port"""		,				type=snake_case__		,				default=""""""		,				help="""Can be used for distant debugging."""    )
			SCREAMING_SNAKE_CASE__								=      parser.parse_args()
			print(snake_case__    )

			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=snake_case__    )
						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    )

			SCREAMING_SNAKE_CASE__								=      torch.device("""cuda""" if torch.cuda.is_available() else """cpu"""    )
			SCREAMING_SNAKE_CASE__								=      torch.cuda.device_count()
			logger.info("""device: {}, n_gpu {}""".format(snake_case__		,				snake_case__    )    )

			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
			SCREAMING_SNAKE_CASE__								=      ["""_start_""", """_delimiter_""", """_classify_"""]
			SCREAMING_SNAKE_CASE__								=      OpenAIGPTTokenizer.from_pretrained(args.model_name    )
			tokenizer.add_tokens(snake_case__    )
			SCREAMING_SNAKE_CASE__								=      tokenizer.convert_tokens_to_ids(snake_case__    )
			SCREAMING_SNAKE_CASE__								=      OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name    )
			model.resize_token_embeddings(len(snake_case__    )    )
			model.to(snake_case__    )

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

			logger.info("""Encoding dataset..."""    )
			SCREAMING_SNAKE_CASE__								=      load_rocstories_dataset(args.train_dataset    )
			SCREAMING_SNAKE_CASE__								=      load_rocstories_dataset(args.eval_dataset    )
			SCREAMING_SNAKE_CASE__								=      (train_dataset, eval_dataset)
			SCREAMING_SNAKE_CASE__								=      tokenize_and_encode(snake_case__    )

			# Compute the max input length for the Transformer
			SCREAMING_SNAKE_CASE__								=      model.config.n_positions // 2 - 2
			SCREAMING_SNAKE_CASE__								=      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    )
			SCREAMING_SNAKE_CASE__								=      min(snake_case__		,				model.config.n_positions    )  # Max size of input for the pre-trained model

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

			SCREAMING_SNAKE_CASE__								=      TensorDataset(*snake_case__    )
			SCREAMING_SNAKE_CASE__								=      RandomSampler(snake_case__    )
			SCREAMING_SNAKE_CASE__								=      DataLoader(snake_case__		,				sampler=snake_case__		,				batch_size=args.train_batch_size    )

			SCREAMING_SNAKE_CASE__								=      TensorDataset(*snake_case__    )
			SCREAMING_SNAKE_CASE__								=      SequentialSampler(snake_case__    )
			SCREAMING_SNAKE_CASE__								=      DataLoader(snake_case__		,				sampler=snake_case__		,				batch_size=args.eval_batch_size    )

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

						SCREAMING_SNAKE_CASE__								=      list(model.named_parameters()    )
						SCREAMING_SNAKE_CASE__								=      ["""bias""", """LayerNorm.bias""", """LayerNorm.weight"""]
						SCREAMING_SNAKE_CASE__								=      [
						    {
						        """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},
						]
						SCREAMING_SNAKE_CASE__								=      AdamW(snake_case__		,				lr=args.learning_rate		,				eps=args.adam_epsilon    )
						SCREAMING_SNAKE_CASE__								=      get_linear_schedule_with_warmup(
						    snake_case__		,				num_warmup_steps=args.warmup_steps		,				num_training_steps=snake_case__    )

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

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

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

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

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

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

									SCREAMING_SNAKE_CASE__								=      mc_logits.detach().cpu().numpy()
									SCREAMING_SNAKE_CASE__								=      mc_labels.to("""cpu"""    ).numpy()
									SCREAMING_SNAKE_CASE__								=      accuracy(snake_case__		,				snake_case__    )

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

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

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

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


if __name__ == "__main__":
						main()


