





'''simple docstring'''




import os
import re
import shutil
import sys
import tempfile
import unittest

import black


__UpperCAmelCase            =       os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, """utils"""))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
__UpperCAmelCase            =       """    def __init__(self, config):
        super().__init__()
        self.transform = BertPredictionHeadTransform(config)

        # The output weights are the same as the input embeddings, but there is
        # an output-only bias for each token.
        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        self.bias = nn.Parameter(torch.zeros(config.vocab_size))

        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
        self.decoder.bias = self.bias

    def forward(self, hidden_states):
        hidden_states = self.transform(hidden_states)
        hidden_states = self.decoder(hidden_states)
        return hidden_states
"""




class      UpperCamelCase__					(					unittest.TestCase			):




					"""simple docstring"""


					def lowerCamelCase_			(						self				:			List[str]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			tempfile.mkdtemp()
							os.makedirs(os.path.join(self.transformer_dir      ,						"""models/bert/"""						)						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			self.transformer_dir
							shutil.copy(
							    os.path.join(lowerCamelCase_      ,						"""src/transformers/models/bert/modeling_bert.py"""						)      ,						os.path.join(self.transformer_dir      ,						"""models/bert/modeling_bert.py"""						)      ,						)


					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				str		=			"""src/transformers"""
							shutil.rmtree(self.transformer_dir						)


					def lowerCamelCase_			(						self				:			Union[str, Any]      ,						lowerCamelCase_				:			str      ,						lowerCamelCase_				:			Optional[int]      ,						lowerCamelCase_				:			Tuple      ,						lowerCamelCase_				:			Dict=None						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			comment + f'''\nclass {class_name}(nn.Module):\n''' + class_code
							if overwrite_result is not None:
									SCREAMING_SNAKE_CASE :				int		=			comment + f'''\nclass {class_name}(nn.Module):\n''' + overwrite_result
							SCREAMING_SNAKE_CASE :				int		=			black.Mode(target_versions={black.TargetVersion.PYaa}      ,						line_length=1_19						)
							SCREAMING_SNAKE_CASE :				str		=			black.format_str(lowerCamelCase_      ,						mode=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				int		=			os.path.join(self.transformer_dir      ,						"""new_code.py"""						)
							with open(lowerCamelCase_      ,						"""w"""      ,						newline="""\n"""						) as f:
									f.write(lowerCamelCase_						)
							if overwrite_result is None:
									self.assertTrue(len(check_copies.is_copy_consistent(lowerCamelCase_						)						) == 0						)
							else:
									check_copies.is_copy_consistent(f.name      ,						overwrite=lowerCamelCase_						)
									with open(lowerCamelCase_      ,						"""r"""						) as f:
											self.assertTrue(f.read()      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Any						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				int		=			check_copies.find_code_in_transformers("""models.bert.modeling_bert.BertLMPredictionHead"""						)
							self.assertEqual(lowerCamelCase_      ,						lowerCamelCase_						)


					def lowerCamelCase_			(						self				:			Tuple						):

							'''simple docstring'''



							self.check_copy_consistency(
							    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""      ,						"""BertLMPredictionHead"""      ,						REFERENCE_CODE + """\n"""      ,						)

							# With no empty line at the end
							self.check_copy_consistency(
							    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead"""      ,						"""BertLMPredictionHead"""      ,						lowerCamelCase_      ,						)

							# Copy consistency with rename
							self.check_copy_consistency(
							    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""      ,						"""TestModelLMPredictionHead"""      ,						re.sub("""Bert"""      ,						"""TestModel"""      ,						lowerCamelCase_						)      ,						)

							# Copy consistency with a really long name
							SCREAMING_SNAKE_CASE :				List[Any]		=			"""TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason"""
							self.check_copy_consistency(
							    f'''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}'''      ,						f'''{long_class_name}LMPredictionHead'''      ,						re.sub("""Bert"""      ,						lowerCamelCase_      ,						lowerCamelCase_						)      ,						)

							# Copy consistency with overwrite
							self.check_copy_consistency(
							    """# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel"""      ,						"""TestModelLMPredictionHead"""      ,						lowerCamelCase_      ,						overwrite_result=re.sub("""Bert"""      ,						"""TestModel"""      ,						lowerCamelCase_						)      ,						)



					def lowerCamelCase_			(						self				:			int						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Optional[int]		=			check_copies.LOCALIZED_READMES["""README_zh-hans.md"""]

							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
							    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
							    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
							    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1."""
							    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),"""
							    """ released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
							    """ lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same"""
							    """ method has been applied to compress GPT2 into"""
							    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
							    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
							    """ Multilingual BERT into"""
							    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
							    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**"""
							    """ (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders"""
							    """ as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang"""
							    """ Luong, Quoc V. Le, Christopher D. Manning."""
							)
							SCREAMING_SNAKE_CASE :				Any		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
							    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
							    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
							    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
							)
							SCREAMING_SNAKE_CASE :				Dict		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
							    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
							    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
							    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1."""
							    """ **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文"""
							    """ [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and"""
							    """ lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same"""
							    """ method has been applied to compress GPT2 into"""
							    """ [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into"""
							    """ [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),"""
							    """ Multilingual BERT into"""
							    """ [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German"""
							    """ version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自"""
							    """ Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather"""
							    """ than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,"""
							    """ Christopher D. Manning 发布。\n"""
							)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				int		=			check_copies.convert_to_localized_md(
							    lowerCamelCase_      ,						lowerCamelCase_      ,						localized_readme["""format_model_list"""]						)

							self.assertFalse(lowerCamelCase_						)
							self.assertEqual(lowerCamelCase_      ,						lowerCamelCase_						)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				List[str]		=			check_copies.convert_to_localized_md(
							    lowerCamelCase_      ,						lowerCamelCase_      ,						localized_readme["""format_model_list"""]						)

							# Check whether the number of models is equal to README.md after conversion.
							self.assertTrue(lowerCamelCase_						)

							SCREAMING_SNAKE_CASE :				int		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the"""
							    """ Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for"""
							    """ Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong"""
							    """ Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut."""
							)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and"""
							    """ the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
							    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
							    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
							)
							SCREAMING_SNAKE_CASE :				Any		=			(
							    """1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the"""
							    """ Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of"""
							    """ Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian"""
							    """ Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n"""
							)

							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				int		=			check_copies.convert_to_localized_md(
							    lowerCamelCase_      ,						lowerCamelCase_      ,						localized_readme["""format_model_list"""]						)

							# Check if the model link is synchronized.
							self.assertEqual(lowerCamelCase_      ,						lowerCamelCase_						)










'''simple docstring'''




import json
import os
from collections import Counter

import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from torch import nn
from torch.utils.data import Dataset


__UpperCAmelCase            =       {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)}




class      UpperCamelCase__					(					nn.Module			):




					"""simple docstring"""


					def __init__(						self				:			Dict      ,						lowerCamelCase_				:			Union[str, Any]						):

							'''simple docstring'''



							super().__init__()
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			torchvision.models.resnetaaa(pretrained=lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Any		=			list(model.children()						)[:-2]
							SCREAMING_SNAKE_CASE :				Any		=			nn.Sequential(*lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds]						)



					def lowerCamelCase_			(						self				:			List[str]      ,						lowerCamelCase_				:			List[Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[Any]		=			self.pool(self.model(lowerCamelCase_						)						)
							SCREAMING_SNAKE_CASE :				int		=			torch.flatten(lowerCamelCase_      ,						start_dim=2						)
							SCREAMING_SNAKE_CASE :				List[Any]		=			out.transpose(1      ,						2						).contiguous()
							return out  # BxNx2048







class      UpperCamelCase__					(					lowercase_			):




					"""simple docstring"""


					def __init__(						self				:			str      ,						lowerCamelCase_				:			List[Any]      ,						lowerCamelCase_				:			List[str]      ,						lowerCamelCase_				:			List[Any]      ,						lowerCamelCase_				:			List[Any]      ,						lowerCamelCase_				:			Tuple						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Tuple		=			[json.loads(lowerCamelCase_						) for l in open(lowerCamelCase_						)]
							SCREAMING_SNAKE_CASE :				Optional[Any]		=			os.path.dirname(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				Tuple		=			tokenizer
							SCREAMING_SNAKE_CASE :				Union[str, Any]		=			labels
							SCREAMING_SNAKE_CASE :				str		=			len(lowerCamelCase_						)
							SCREAMING_SNAKE_CASE :				int		=			max_seq_length

							SCREAMING_SNAKE_CASE :				List[Any]		=			transforms


					def __len__(						self				:			Any						):

							'''simple docstring'''



							return len(self.data						)


					def __getitem__(						self				:			Optional[int]      ,						lowerCamelCase_				:			List[str]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				List[Any]		=			torch.LongTensor(self.tokenizer.encode(self.data[index]["""text"""]      ,						add_special_tokens=lowerCamelCase_						)						)
							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Tuple		=			sentence[0], sentence[1:-1], sentence[-1]
							SCREAMING_SNAKE_CASE :				int		=			sentence[: self.max_seq_length]

							SCREAMING_SNAKE_CASE :				List[Any]		=			torch.zeros(self.n_classes						)
							SCREAMING_SNAKE_CASE :				List[str]		=			1

							SCREAMING_SNAKE_CASE :				int		=			Image.open(os.path.join(self.data_dir      ,						self.data[index]["""img"""]						)						).convert("""RGB"""						)
							SCREAMING_SNAKE_CASE :				str		=			self.transforms(lowerCamelCase_						)

							return {
							    "image_start_token": start_token,
							    "image_end_token": end_token,
							    "sentence": sentence,
							    "image": image,
							    "label": label,
							}



					def lowerCamelCase_			(						self				:			Optional[Any]						):

							'''simple docstring'''



							SCREAMING_SNAKE_CASE :				Any		=			Counter()
							for row in self.data:
									label_freqs.update(row["""label"""]						)
							return label_freqs







def 		__A		(  lowerCamelCase_	):


		"""simple docstring"""



		SCREAMING_SNAKE_CASE :				Tuple		=			[len(row["""sentence"""]	) for row in batch]
		SCREAMING_SNAKE_CASE,							SCREAMING_SNAKE_CASE :				Any		=			len(lowerCamelCase_	), max(lowerCamelCase_	)

		SCREAMING_SNAKE_CASE :				int		=			torch.zeros(lowerCamelCase_			,			lowerCamelCase_			,			dtype=torch.long	)
		SCREAMING_SNAKE_CASE :				Any		=			torch.zeros(lowerCamelCase_			,			lowerCamelCase_			,			dtype=torch.long	)

		for i_batch, (input_row, length) in enumerate(zip(lowerCamelCase_			,			lowerCamelCase_	)	):
				SCREAMING_SNAKE_CASE :				Union[str, Any]		=			input_row["""sentence"""]
				SCREAMING_SNAKE_CASE :				Union[str, Any]		=			1

		SCREAMING_SNAKE_CASE :				List[str]		=			torch.stack([row["""image"""] for row in batch]	)
		SCREAMING_SNAKE_CASE :				int		=			torch.stack([row["""label"""] for row in batch]	)
		SCREAMING_SNAKE_CASE :				str		=			torch.stack([row["""image_start_token"""] for row in batch]	)
		SCREAMING_SNAKE_CASE :				Any		=			torch.stack([row["""image_end_token"""] for row in batch]	)

		return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor



def 		__A		(  ):


		"""simple docstring"""



		return [
		    "Crime",
		    "Drama",
		    "Thriller",
		    "Action",
		    "Comedy",
		    "Romance",
		    "Documentary",
		    "Short",
		    "Mystery",
		    "History",
		    "Family",
		    "Adventure",
		    "Fantasy",
		    "Sci-Fi",
		    "Western",
		    "Horror",
		    "Sport",
		    "War",
		    "Music",
		    "Musical",
		    "Animation",
		    "Biography",
		    "Film-Noir",
		]



def 		__A		(  ):


		"""simple docstring"""



		return transforms.Compose(
		    [
		        transforms.Resize(2_56	),
		        transforms.CenterCrop(2_24	),
		        transforms.ToTensor(),
		        transforms.Normalize(
		            mean=[0.46_777_044, 0.44_531_429, 0.40_661_017]			,			std=[0.12_221_994, 0.12_145_835, 0.14_380_469]			,			),
		    ]	)



