


"""simple docstring"""


import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			__lowerCAmelCase							       =     384
			if "tiny" in model_name:
						__lowerCAmelCase							       =     [3, 3, 9, 3]
						__lowerCAmelCase							       =     [96, 192, 384, 768]
			if "small" in model_name:
						__lowerCAmelCase							       =     [3, 3, 27, 3]
						__lowerCAmelCase							       =     [96, 192, 384, 768]
			if "base" in model_name:
						__lowerCAmelCase							       =     [3, 3, 27, 3]
						__lowerCAmelCase							       =     [128, 256, 512, 1024]
						__lowerCAmelCase							       =     512
			if "large" in model_name:
						__lowerCAmelCase							       =     [3, 3, 27, 3]
						__lowerCAmelCase							       =     [192, 384, 768, 1536]
						__lowerCAmelCase							       =     768
			if "xlarge" in model_name:
						__lowerCAmelCase							       =     [3, 3, 27, 3]
						__lowerCAmelCase							       =     [256, 512, 1024, 2048]
						__lowerCAmelCase							       =     1024

			# set label information
			__lowerCAmelCase							       =     150
			__lowerCAmelCase							       =     "huggingface/label-files"
			__lowerCAmelCase							       =     "ade20k-id2label.json"
			__lowerCAmelCase							       =     json.load(open(hf_hub_download(_UpperCamelCase       ,					_UpperCamelCase       ,					repo_type="dataset" )       ,					"r" ) )
			__lowerCAmelCase							       =     {int(_UpperCamelCase ): v for k, v in idalabel.items()}
			__lowerCAmelCase							       =     {v: k for k, v in idalabel.items()}

			__lowerCAmelCase							       =     ConvNextConfig(
			    depths=_UpperCamelCase       ,					hidden_sizes=_UpperCamelCase       ,					out_features=["stage1", "stage2", "stage3", "stage4"] )
			__lowerCAmelCase							       =     UperNetConfig(
			    backbone_config=_UpperCamelCase       ,					auxiliary_in_channels=_UpperCamelCase       ,					num_labels=_UpperCamelCase       ,					idalabel=_UpperCamelCase       ,					labelaid=_UpperCamelCase       ,					)

			return config


def _lowerCamelCase      (						_UpperCamelCase ):

			'''simple docstring'''




			__lowerCAmelCase							       =     []

			# fmt: off
			# stem
			rename_keys.append(("backbone.downsample_layers.0.0.weight", "backbone.embeddings.patch_embeddings.weight") )
			rename_keys.append(("backbone.downsample_layers.0.0.bias", "backbone.embeddings.patch_embeddings.bias") )
			rename_keys.append(("backbone.downsample_layers.0.1.weight", "backbone.embeddings.layernorm.weight") )
			rename_keys.append(("backbone.downsample_layers.0.1.bias", "backbone.embeddings.layernorm.bias") )
			# stages
			for i in range(len(config.backbone_config.depths ) ):
						for j in range(config.backbone_config.depths[i] ):
									rename_keys.append((f"backbone.stages.{i}.{j}.gamma", f"backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter") )
									rename_keys.append((f"backbone.stages.{i}.{j}.depthwise_conv.weight", f"backbone.encoder.stages.{i}.layers.{j}.dwconv.weight") )
									rename_keys.append((f"backbone.stages.{i}.{j}.depthwise_conv.bias", f"backbone.encoder.stages.{i}.layers.{j}.dwconv.bias") )
									rename_keys.append((f"backbone.stages.{i}.{j}.norm.weight", f"backbone.encoder.stages.{i}.layers.{j}.layernorm.weight") )
									rename_keys.append((f"backbone.stages.{i}.{j}.norm.bias", f"backbone.encoder.stages.{i}.layers.{j}.layernorm.bias") )
									rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv1.weight", f"backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight") )
									rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv1.bias", f"backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias") )
									rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv2.weight", f"backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight") )
									rename_keys.append((f"backbone.stages.{i}.{j}.pointwise_conv2.bias", f"backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias") )
						if i > 0:
									rename_keys.append((f"backbone.downsample_layers.{i}.0.weight", f"backbone.encoder.stages.{i}.downsampling_layer.0.weight") )
									rename_keys.append((f"backbone.downsample_layers.{i}.0.bias", f"backbone.encoder.stages.{i}.downsampling_layer.0.bias") )
									rename_keys.append((f"backbone.downsample_layers.{i}.1.weight", f"backbone.encoder.stages.{i}.downsampling_layer.1.weight") )
									rename_keys.append((f"backbone.downsample_layers.{i}.1.bias", f"backbone.encoder.stages.{i}.downsampling_layer.1.bias") )

						rename_keys.append((f"backbone.norm{i}.weight", f"backbone.hidden_states_norms.stage{i+1}.weight") )
						rename_keys.append((f"backbone.norm{i}.bias", f"backbone.hidden_states_norms.stage{i+1}.bias") )

			# decode head
			rename_keys.extend(
			    [
			        ("decode_head.conv_seg.weight", "decode_head.classifier.weight"),
			        ("decode_head.conv_seg.bias", "decode_head.classifier.bias"),
			        ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"),
			        ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"),
			    ] )
			# fmt: on

			return rename_keys


def _lowerCamelCase      (						_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase ):

			'''simple docstring'''




			__lowerCAmelCase							       =     dct.pop(_UpperCamelCase )
			__lowerCAmelCase							       =     val


def _lowerCamelCase      (						_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase ):

			'''simple docstring'''




			__lowerCAmelCase							       =     {
			    "upernet-convnext-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth",
			    "upernet-convnext-small": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth",
			    "upernet-convnext-base": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth",
			    "upernet-convnext-large": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth",
			    "upernet-convnext-xlarge": "https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth",
			}
			__lowerCAmelCase							       =     model_name_to_url[model_name]
			__lowerCAmelCase							       =     torch.hub.load_state_dict_from_url(_UpperCamelCase       ,					map_location="cpu" )["state_dict"]

			__lowerCAmelCase							       =     get_upernet_config(_UpperCamelCase )
			__lowerCAmelCase							       =     UperNetForSemanticSegmentation(_UpperCamelCase )
			model.eval()

			# replace "bn" => "batch_norm"
			for key in state_dict.copy().keys():
						__lowerCAmelCase							       =     state_dict.pop(_UpperCamelCase )
						if "bn" in key:
									__lowerCAmelCase							       =     key.replace("bn"       ,					"batch_norm" )
						__lowerCAmelCase							       =     val

			# rename keys
			__lowerCAmelCase							       =     create_rename_keys(_UpperCamelCase )
			for src, dest in rename_keys:
						rename_key(_UpperCamelCase       ,					_UpperCamelCase       ,					_UpperCamelCase )

			model.load_state_dict(_UpperCamelCase )

			# verify on image
			__lowerCAmelCase							       =     "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
			__lowerCAmelCase							       =     Image.open(requests.get(_UpperCamelCase       ,					stream=_UpperCamelCase ).raw ).convert("RGB" )

			__lowerCAmelCase							       =     SegformerImageProcessor()
			__lowerCAmelCase							       =     processor(_UpperCamelCase       ,					return_tensors="pt" ).pixel_values

			with torch.no_grad():
						__lowerCAmelCase							       =     model(_UpperCamelCase )

			if model_name == "upernet-convnext-tiny":
						__lowerCAmelCase							       =     torch.tensor(
						    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]] )
			elif model_name == "upernet-convnext-small":
						__lowerCAmelCase							       =     torch.tensor(
						    [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]] )
			elif model_name == "upernet-convnext-base":
						__lowerCAmelCase							       =     torch.tensor(
						    [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]] )
			elif model_name == "upernet-convnext-large":
						__lowerCAmelCase							       =     torch.tensor(
						    [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]] )
			elif model_name == "upernet-convnext-xlarge":
						__lowerCAmelCase							       =     torch.tensor(
						    [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]] )
			print("Logits:"       ,					outputs.logits[0, 0, :3, :3] )
			assert torch.allclose(outputs.logits[0, 0, :3, :3]       ,					_UpperCamelCase       ,					atol=1e-4 )
			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(_UpperCamelCase )
						print(f"Saving processor to {pytorch_dump_folder_path}" )
						processor.save_pretrained(_UpperCamelCase )

			if push_to_hub:
						print(f"Pushing model and processor for {model_name} to hub" )
						model.push_to_hub(f"openmmlab/{model_name}" )
						processor.push_to_hub(f"openmmlab/{model_name}" )


if __name__ == "__main__":
	A	:  Union[str, Any]            =     argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    "--model_name",
	    default="upernet-convnext-tiny",
	    type=str,
	    choices=[f'''upernet-convnext-{size}''' for size in ["tiny", "small", "base", "large", "xlarge"]],
	    help="Name of the ConvNext UperNet model you'd like to convert.",
	)
	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	:  Union[str, Any]            =     parser.parse_args()
	convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)








"""simple docstring"""


import unittest

from transformers import AutoTokenizer, FalconConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    FalconForCausalLM,
	    FalconForQuestionAnswering,
	    FalconForSequenceClassification,
	    FalconForTokenClassification,
	    FalconModel,
	)
class     _UpperCamelCase    :
							'''simple docstring'''







							def __init__(	self       ,  __a       ,  __a=3       ,  __a=7       ,  __a=True       ,  __a=True       ,  __a=False       ,  __a=True       ,  __a=99       ,  __a=32       ,  __a=5       ,  __a=4       ,  __a=37       ,  __a="gelu"       ,  __a=0.1       ,  __a=0.1       ,  __a=5_12       ,  __a=16       ,  __a=2       ,  __a=0.0_2       ,  __a=3       ,  __a=4       ,  __a=None       ,  ):
										__lowerCAmelCase							       =     parent
										__lowerCAmelCase							       =     batch_size
										__lowerCAmelCase							       =     seq_length
										__lowerCAmelCase							       =     is_training
										__lowerCAmelCase							       =     use_input_mask
										__lowerCAmelCase							       =     use_token_type_ids
										__lowerCAmelCase							       =     use_labels
										__lowerCAmelCase							       =     vocab_size
										__lowerCAmelCase							       =     hidden_size
										__lowerCAmelCase							       =     num_hidden_layers
										__lowerCAmelCase							       =     num_attention_heads
										__lowerCAmelCase							       =     intermediate_size
										__lowerCAmelCase							       =     hidden_act
										__lowerCAmelCase							       =     hidden_dropout_prob
										__lowerCAmelCase							       =     attention_probs_dropout_prob
										__lowerCAmelCase							       =     max_position_embeddings
										__lowerCAmelCase							       =     type_vocab_size
										__lowerCAmelCase							       =     type_sequence_label_size
										__lowerCAmelCase							       =     initializer_range
										__lowerCAmelCase							       =     num_labels
										__lowerCAmelCase							       =     num_choices
										__lowerCAmelCase							       =     scope

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size      )

										__lowerCAmelCase							       =     None
										if self.use_input_mask:
													__lowerCAmelCase							       =     random_attention_mask([self.batch_size, self.seq_length]      )

										__lowerCAmelCase							       =     None

										__lowerCAmelCase							       =     None
										__lowerCAmelCase							       =     None
										__lowerCAmelCase							       =     None
										if self.use_labels:
													__lowerCAmelCase							       =     ids_tensor([self.batch_size]       ,  self.type_sequence_label_size      )
													__lowerCAmelCase							       =     ids_tensor([self.batch_size, self.seq_length]       ,  self.num_labels      )
													__lowerCAmelCase							       =     ids_tensor([self.batch_size]       ,  self.num_choices      )

										__lowerCAmelCase							       =     self.get_config()

										return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

							def      snake_case							(	self      ):
										return FalconConfig(
										    vocab_size=self.vocab_size       ,  hidden_size=self.hidden_size       ,  num_hidden_layers=self.num_hidden_layers       ,  num_attention_heads=self.num_attention_heads       ,  intermediate_size=self.intermediate_size       ,  hidden_act=self.hidden_act       ,  hidden_dropout_prob=self.hidden_dropout_prob       ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,  max_position_embeddings=self.max_position_embeddings       ,  type_vocab_size=self.type_vocab_size       ,  is_decoder=__a       ,  initializer_range=self.initializer_range       ,  pad_token_id=1       ,  new_decoder_architecture=__a       ,  )

							def      snake_case							(	self       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a      ):
										__lowerCAmelCase							       =     FalconModel(config=__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a      )
										__lowerCAmelCase							       =     model(__a      )
										self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size)      )

							def      snake_case							(	self       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  ):
										__lowerCAmelCase							       =     True
										__lowerCAmelCase							       =     FalconModel(__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(
										    __a       ,  attention_mask=__a       ,  encoder_hidden_states=__a       ,  encoder_attention_mask=__a       ,  )
										__lowerCAmelCase							       =     model(
										    __a       ,  attention_mask=__a       ,  encoder_hidden_states=__a       ,  )
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a      )
										self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size)      )

							def      snake_case							(	self       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  ):
										__lowerCAmelCase							       =     FalconForCausalLM(config=__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a       ,  labels=__a      )
										self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)      )

							def      snake_case							(	self       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  __a       ,  ):
										__lowerCAmelCase							       =     True
										__lowerCAmelCase							       =     True
										__lowerCAmelCase							       =     FalconForCausalLM(config=__a      )
										model.to(__a      )
										model.eval()

										# first forward pass
										__lowerCAmelCase							       =     model(
										    __a       ,  attention_mask=__a       ,  encoder_hidden_states=__a       ,  encoder_attention_mask=__a       ,  use_cache=__a       ,  )
										__lowerCAmelCase							       =     outputs.past_key_values

										# create hypothetical multiple next token and extent to next_input_ids
										__lowerCAmelCase							       =     ids_tensor((self.batch_size, 3)       ,  config.vocab_size      )
										__lowerCAmelCase							       =     ids_tensor((self.batch_size, 3)       ,  vocab_size=2      )

										# append to next input_ids and
										__lowerCAmelCase							       =     torch.cat([input_ids, next_tokens]       ,  dim=-1      )
										__lowerCAmelCase							       =     torch.cat([input_mask, next_mask]       ,  dim=-1      )

										__lowerCAmelCase							       =     model(
										    __a       ,  attention_mask=__a       ,  encoder_hidden_states=__a       ,  encoder_attention_mask=__a       ,  output_hidden_states=__a       ,  )["hidden_states"][0]
										__lowerCAmelCase							       =     model(
										    __a       ,  attention_mask=__a       ,  encoder_hidden_states=__a       ,  encoder_attention_mask=__a       ,  past_key_values=__a       ,  output_hidden_states=__a       ,  )["hidden_states"][0]

										# select random slice
										__lowerCAmelCase							       =     ids_tensor((1,)       ,  output_from_past.shape[-1]      ).item()
										__lowerCAmelCase							       =     output_from_no_past[:, -3:, random_slice_idx].detach()
										__lowerCAmelCase							       =     output_from_past[:, :, random_slice_idx].detach()

										self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]      )

										# test that outputs are equal for slice
										self.parent.assertTrue(torch.allclose(__a       ,  __a       ,  atol=1e-3      )      )



							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     self.prepare_config_and_inputs()
										(
										    (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      (
										    __lowerCAmelCase
										)       ,      
										)							       =     config_and_inputs
										__lowerCAmelCase							       =     {"input_ids": input_ids, "attention_mask": input_mask}
										return config, inputs_dict
@require_torch
class     _UpperCamelCase    (  lowerCAmelCase__			,lowerCAmelCase__			,lowerCAmelCase__			,unittest.TestCase						):
							'''simple docstring'''







							__UpperCAmelCase		:       int							 =(
							    (
							        FalconModel,
							        FalconForCausalLM,
							        FalconForSequenceClassification,
							        FalconForTokenClassification,
							        FalconForQuestionAnswering,
							    )
							    if is_torch_available()
							    else ()
							)
							__UpperCAmelCase		:       Union[str, Any]							 =(FalconForCausalLM,) if is_torch_available() else ()
							__UpperCAmelCase		:       List[Any]							 =(
							    {
							        """feature-extraction""": FalconModel,
							        """text-classification""": FalconForSequenceClassification,
							        """text-generation""": FalconForCausalLM,
							        """question-answering""": FalconForQuestionAnswering,
							        """token-classification""": FalconForTokenClassification,
							        """zero-shot""": FalconForSequenceClassification,
							    }
							    if is_torch_available()
							    else {}
							)
							__UpperCAmelCase		:       Any							 =False
							__UpperCAmelCase		:       Tuple							 =False

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     FalconModelTester(self      )
										__lowerCAmelCase							       =     ConfigTester(self       ,  config_class=__a       ,  hidden_size=37      )

							def      snake_case							(	self      ):
										self.config_tester.run_common_tests()

							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__a      )

							def      snake_case							(	self      ):
										__lowerCAmelCase       ,      *__lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs()
										for alibi in [True, False]:
													__lowerCAmelCase							       =     alibi
													self.model_tester.create_and_check_model(__a       ,  *__a      )

							def      snake_case							(	self      ):
										__lowerCAmelCase       ,      __lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()
										__lowerCAmelCase							       =     3
										__lowerCAmelCase							       =     input_dict["input_ids"]
										__lowerCAmelCase							       =     input_ids.ne(1      ).to(__a      )
										__lowerCAmelCase							       =     ids_tensor([self.model_tester.batch_size]       ,  self.model_tester.type_sequence_label_size      )
										__lowerCAmelCase							       =     FalconForSequenceClassification(__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a       ,  labels=__a      )
										self.assertEqual(result.logits.shape       ,  (self.model_tester.batch_size, self.model_tester.num_labels)      )

							def      snake_case							(	self      ):
										__lowerCAmelCase       ,      __lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()
										__lowerCAmelCase							       =     3
										__lowerCAmelCase							       =     "single_label_classification"
										__lowerCAmelCase							       =     input_dict["input_ids"]
										__lowerCAmelCase							       =     input_ids.ne(1      ).to(__a      )
										__lowerCAmelCase							       =     ids_tensor([self.model_tester.batch_size]       ,  self.model_tester.type_sequence_label_size      )
										__lowerCAmelCase							       =     FalconForSequenceClassification(__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a       ,  labels=__a      )
										self.assertEqual(result.logits.shape       ,  (self.model_tester.batch_size, self.model_tester.num_labels)      )

							def      snake_case							(	self      ):
										__lowerCAmelCase       ,      __lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()
										__lowerCAmelCase							       =     input_dict["input_ids"]
										__lowerCAmelCase							       =     FalconForCausalLM(__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  use_cache=__a      )
										__lowerCAmelCase							       =     input_ids.shape[0]
										__lowerCAmelCase							       =     model._convert_to_rw_cache(result.past_key_values      )
										__lowerCAmelCase							       =     model._convert_cache_to_standard_format(__a       ,  __a      )
										for layer in range(len(__a      )      ):
													for tensor_idx in range(2      ):
																self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3      )
																self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4      )
																self.assertTrue(
																    torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx]      )      )

							def      snake_case							(	self      ):
										__lowerCAmelCase       ,      __lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()
										__lowerCAmelCase							       =     3
										__lowerCAmelCase							       =     "multi_label_classification"
										__lowerCAmelCase							       =     input_dict["input_ids"]
										__lowerCAmelCase							       =     input_ids.ne(1      ).to(__a      )
										__lowerCAmelCase							       =     ids_tensor(
										    [self.model_tester.batch_size, config.num_labels]       ,  self.model_tester.type_sequence_label_size      ).to(torch.float      )
										__lowerCAmelCase							       =     FalconForSequenceClassification(__a      )
										model.to(__a      )
										model.eval()
										__lowerCAmelCase							       =     model(__a       ,  attention_mask=__a       ,  labels=__a      )
										self.assertEqual(result.logits.shape       ,  (self.model_tester.batch_size, self.model_tester.num_labels)      )



							def      snake_case							(	self      ):
										# Falcon can have different numbers of KV-heads than the number of query heads, so we need
										# to override this test to use the right head counts.
										for model_class in self.all_generative_model_classes:
													__lowerCAmelCase       ,      __lowerCAmelCase							       =     self.model_tester.prepare_config_and_inputs_for_common()

													# If it doesn't support cache, pass the test
													if not hasattr(__a       ,  "use_cache"      ):
																return

													__lowerCAmelCase							       =     model_class(__a      ).to(__a      )
													if "use_cache" not in inputs:
																__lowerCAmelCase							       =     True
													__lowerCAmelCase							       =     model(**__a      )

													# If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format)
													if "past_key_values" not in outputs:
																return

													__lowerCAmelCase							       =     (
													    getattr(__a       ,  "decoder_layers"       ,  __a      )
													    or getattr(__a       ,  "num_decoder_layers"       ,  __a      )
													    or config.num_hidden_layers
													)
													__lowerCAmelCase							       =     getattr(__a       ,  "num_kv_heads"       ,  config.num_attention_heads      )
													__lowerCAmelCase							       =     getattr(__a       ,  "d_model"       ,  config.hidden_size      )
													__lowerCAmelCase							       =     embed_dim // num_attention_heads

													__lowerCAmelCase							       =     outputs["past_key_values"]
													self.assertEqual(len(__a      )       ,  __a      )

													__lowerCAmelCase       ,      __lowerCAmelCase							       =     inputs["input_ids"].shape
													for i in range(__a      ):
																if config.new_decoder_architecture:
																			__lowerCAmelCase							       =     config.num_attention_heads
																elif config.multi_query:
																			__lowerCAmelCase							       =     1
																self.assertEqual(len(past_kv[0]      )       ,  2      )  # K V for the decoder = 2
																self.assertEqual(
																    past_kv[i][0].shape       ,  (batch_size, num_attention_heads, seq_length, per_head_embed_dim)      )
																self.assertEqual(
																    past_kv[i][1].shape       ,  (batch_size, num_attention_heads, seq_length, per_head_embed_dim)      )
@require_torch
class     _UpperCamelCase    (  unittest.TestCase						):
							'''simple docstring'''







							@slow
							def      snake_case							(	self      ):
										__lowerCAmelCase							       =     AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b"      )
										__lowerCAmelCase							       =     FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b"      )
										model.eval()
										model.to(__a      )
										__lowerCAmelCase							       =     tokenizer("My favorite food is"       ,  return_tensors="pt"      ).to(__a      )

										__lowerCAmelCase							       =     (
										    "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday."
										)

										__lowerCAmelCase							       =     model.generate(**__a       ,  do_sample=__a       ,  max_new_tokens=19      )
										__lowerCAmelCase							       =     tokenizer.batch_decode(__a      )[0]

										self.assertEqual(__a       ,  __a      )

							@slow
							def      snake_case							(	self      ):
										# The big models are way too big for the CI, so we use tiny random models that resemble their
										# architectures but with much smaller and fewer layers
										for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]:
													__lowerCAmelCase							       =     AutoTokenizer.from_pretrained(__a      )
													__lowerCAmelCase							       =     FalconForCausalLM.from_pretrained(__a      )
													model.eval()
													model.to(__a      )
													__lowerCAmelCase							       =     tokenizer("My favorite food is"       ,  return_tensors="pt"      ).to(__a      )

													# We just test that these run without errors - the models are randomly initialized
													# and so the actual text outputs will be garbage
													model.generate(**__a       ,  do_sample=__a       ,  max_new_tokens=4      )
													model.generate(**__a       ,  do_sample=__a       ,  max_new_tokens=4      )
													model.generate(**__a       ,  num_beams=2       ,  max_new_tokens=4      )



							@slow
							def      snake_case							(	self      ):
										# The big models are way too big for the CI, so we use tiny random models that resemble their
										# architectures but with much smaller and fewer layers
										with torch.no_grad():
													for repo in [
													    "Rocketknight1/falcon-rw-1b",
													    "Rocketknight1/tiny-random-falcon-7b",
													    "Rocketknight1/tiny-random-falcon-40b",
													]:
																__lowerCAmelCase							       =     AutoTokenizer.from_pretrained(__a      )
																__lowerCAmelCase							       =     FalconForCausalLM.from_pretrained(__a      )
																model.eval()
																model.to(device=__a      )
																__lowerCAmelCase							       =     tokenizer("My favorite food is"       ,  return_tensors="pt"      ).to(__a      )

																# Test results are the same with and without cache
																__lowerCAmelCase							       =     model.generate(**__a       ,  do_sample=__a       ,  max_new_tokens=20       ,  use_cache=__a      )
																__lowerCAmelCase							       =     model.generate(**__a       ,  do_sample=__a       ,  max_new_tokens=20       ,  use_cache=__a      )
																self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0      )




