






import argparse
import json

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

from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[Any]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Tuple													=   384
				SCREAMING_SNAKE_CASE_   :	List[str]													=   7
				if "tiny" in model_name:
								SCREAMING_SNAKE_CASE_   :	List[str]													=   96
								SCREAMING_SNAKE_CASE_   :	int													=   (2, 2, 6, 2)
								SCREAMING_SNAKE_CASE_   :	Tuple													=   (3, 6, 12, 24)
				elif "small" in model_name:
								SCREAMING_SNAKE_CASE_   :	int													=   96
								SCREAMING_SNAKE_CASE_   :	Any													=   (2, 2, 18, 2)
								SCREAMING_SNAKE_CASE_   :	Tuple													=   (3, 6, 12, 24)
				elif "base" in model_name:
								SCREAMING_SNAKE_CASE_   :	Dict													=   128
								SCREAMING_SNAKE_CASE_   :	Tuple													=   (2, 2, 18, 2)
								SCREAMING_SNAKE_CASE_   :	Tuple													=   (4, 8, 16, 32)
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   12
								SCREAMING_SNAKE_CASE_   :	int													=   512
				elif "large" in model_name:
								SCREAMING_SNAKE_CASE_   :	str													=   192
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   (2, 2, 18, 2)
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   (6, 12, 24, 48)
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   12
								SCREAMING_SNAKE_CASE_   :	Any													=   768

				# set label information
				SCREAMING_SNAKE_CASE_   :	Any													=   150
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   'huggingface/label-files'
				SCREAMING_SNAKE_CASE_   :	Any													=   'ade20k-id2label.json'
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   json.load(open(hf_hub_download(lowerCAmelCase__    ,    lowerCAmelCase__    ,    repo_type='dataset'      )    ,    'r'      )      )
				SCREAMING_SNAKE_CASE_   :	Any													=   {int(lowerCAmelCase__      ): v for k, v in idalabel.items()}
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   {v: k for k, v in idalabel.items()}

				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   SwinConfig(
				    embed_dim=lowerCAmelCase__    ,    depths=lowerCAmelCase__    ,    num_heads=lowerCAmelCase__    ,    window_size=lowerCAmelCase__    ,    out_features=['stage1', 'stage2', 'stage3', 'stage4']    ,    )
				SCREAMING_SNAKE_CASE_   :	List[str]													=   UperNetConfig(
				    backbone_config=lowerCAmelCase__    ,    auxiliary_in_channels=lowerCAmelCase__    ,    num_labels=lowerCAmelCase__    ,    idalabel=lowerCAmelCase__    ,    labelaid=lowerCAmelCase__    ,    )

				return config



def 					_lowerCamelCase(			lowerCAmelCase__				:		str      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Dict													=   []

				# fmt: off
				# stem
				rename_keys.append(('backbone.patch_embed.projection.weight', 'backbone.embeddings.patch_embeddings.projection.weight')      )
				rename_keys.append(('backbone.patch_embed.projection.bias', 'backbone.embeddings.patch_embeddings.projection.bias')      )
				rename_keys.append(('backbone.patch_embed.norm.weight', 'backbone.embeddings.norm.weight')      )
				rename_keys.append(('backbone.patch_embed.norm.bias', 'backbone.embeddings.norm.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}.blocks.{j}.norm1.weight''', F'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.norm1.bias''', F'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', F'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', F'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', F'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', F'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.norm2.weight''', F'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.norm2.bias''', F'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', F'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', F'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', F'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', F'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''')      )

								if i < 3:
												rename_keys.append((F'''backbone.stages.{i}.downsample.reduction.weight''', F'''backbone.encoder.layers.{i}.downsample.reduction.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.downsample.norm.weight''', F'''backbone.encoder.layers.{i}.downsample.norm.weight''')      )
												rename_keys.append((F'''backbone.stages.{i}.downsample.norm.bias''', F'''backbone.encoder.layers.{i}.downsample.norm.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(			lowerCAmelCase__				:		str    ,    lowerCAmelCase__				:		List[Any]    ,    lowerCAmelCase__				:		Dict      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Tuple													=   dct.pop(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	str													=   val



def 					_lowerCamelCase(			lowerCAmelCase__				:		Optional[Any]    ,    lowerCAmelCase__				:		List[Any]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Dict													=   [int(backbone_config.embed_dim * 2**i      ) for i in range(len(backbone_config.depths      )      )]
				for i in range(len(backbone_config.depths      )      ):
								SCREAMING_SNAKE_CASE_   :	Dict													=   num_features[i]
								for j in range(backbone_config.depths[i]      ):
												# fmt: off
												# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
												SCREAMING_SNAKE_CASE_   :	Tuple													=   state_dict.pop(F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight'''      )
												SCREAMING_SNAKE_CASE_   :	List[Any]													=   state_dict.pop(F'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias'''      )
												# next, add query, keys and values (in that order) to the state dict
												SCREAMING_SNAKE_CASE_   :	List[Any]													=   in_proj_weight[:dim, :]
												SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   in_proj_bias[: dim]
												SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_weight[
												    dim : dim * 2, :
												]
												SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   in_proj_bias[
												    dim : dim * 2
												]
												SCREAMING_SNAKE_CASE_   :	List[Any]													=   in_proj_weight[
												    -dim :, :
												]
												SCREAMING_SNAKE_CASE_   :	Dict													=   in_proj_bias[-dim :]
												# fmt: on



def 					_lowerCamelCase(			lowerCAmelCase__				:		Tuple      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   x.shape
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   x.reshape(lowerCAmelCase__    ,    4    ,    in_channel // 4      )
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   x[:, [0, 2, 1, 3], :].transpose(1    ,    2      ).reshape(lowerCAmelCase__    ,    lowerCAmelCase__      )
				return x



def 					_lowerCamelCase(			lowerCAmelCase__				:		str      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	List[str]													=   x.shape
				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   x.reshape(lowerCAmelCase__    ,    in_channel // 4    ,    4      )
				SCREAMING_SNAKE_CASE_   :	Tuple													=   x[:, :, [0, 2, 1, 3]].transpose(1    ,    2      ).reshape(lowerCAmelCase__    ,    lowerCAmelCase__      )

				return x



def 					_lowerCamelCase(			lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	str													=   x.shape[0]
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   x.reshape(4    ,    in_channel // 4      )
				SCREAMING_SNAKE_CASE_   :	Dict													=   x[[0, 2, 1, 3], :].transpose(0    ,    1      ).reshape(lowerCAmelCase__      )
				return x



def 					_lowerCamelCase(			lowerCAmelCase__				:		Any      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   x.shape[0]
				SCREAMING_SNAKE_CASE_   :	Tuple													=   x.reshape(in_channel // 4    ,    4      )
				SCREAMING_SNAKE_CASE_   :	str													=   x[:, [0, 2, 1, 3]].transpose(0    ,    1      ).reshape(lowerCAmelCase__      )
				return x



def 					_lowerCamelCase(			lowerCAmelCase__				:		str    ,    lowerCAmelCase__				:		Dict    ,    lowerCAmelCase__				:		List[str]      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_   :	int													=   {
				    'upernet-swin-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth',
				    'upernet-swin-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth',
				    'upernet-swin-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth',
				    'upernet-swin-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth',
				}
				SCREAMING_SNAKE_CASE_   :	str													=   model_name_to_url[model_name]
				SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.hub.load_state_dict_from_url(lowerCAmelCase__    ,    map_location='cpu'    ,    file_name=lowerCAmelCase__      )[
				    'state_dict'
				]

				for name, param in state_dict.items():
								print(lowerCAmelCase__    ,    param.shape      )

				SCREAMING_SNAKE_CASE_   :	List[str]													=   get_upernet_config(lowerCAmelCase__      )
				SCREAMING_SNAKE_CASE_   :	List[Any]													=   UperNetForSemanticSegmentation(lowerCAmelCase__      )
				model.eval()

				# replace "bn" => "batch_norm"
				for key in state_dict.copy().keys():
								SCREAMING_SNAKE_CASE_   :	str													=   state_dict.pop(lowerCAmelCase__      )
								if "bn" in key:
												SCREAMING_SNAKE_CASE_   :	str													=   key.replace('bn'    ,    'batch_norm'      )
								SCREAMING_SNAKE_CASE_   :	Tuple													=   val

				# rename keys
				SCREAMING_SNAKE_CASE_   :	Any													=   create_rename_keys(lowerCAmelCase__      )
				for src, dest in rename_keys:
								rename_key(lowerCAmelCase__    ,    lowerCAmelCase__    ,    lowerCAmelCase__      )
				read_in_q_k_v(lowerCAmelCase__    ,    config.backbone_config      )

				# fix downsample parameters
				for key, value in state_dict.items():
								if "downsample" in key:
												if "reduction" in key:
																SCREAMING_SNAKE_CASE_   :	Dict													=   reverse_correct_unfold_reduction_order(lowerCAmelCase__      )
												if "norm" in key:
																SCREAMING_SNAKE_CASE_   :	List[str]													=   reverse_correct_unfold_norm_order(lowerCAmelCase__      )

				model.load_state_dict(lowerCAmelCase__      )

				# verify on image
				SCREAMING_SNAKE_CASE_   :	Optional[int]													=   'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'
				SCREAMING_SNAKE_CASE_   :	Dict													=   Image.open(requests.get(lowerCAmelCase__    ,    stream=lowerCAmelCase__      ).raw      ).convert('RGB'      )

				SCREAMING_SNAKE_CASE_   :	Dict													=   SegformerImageProcessor()
				SCREAMING_SNAKE_CASE_   :	str													=   processor(lowerCAmelCase__    ,    return_tensors='pt'      ).pixel_values

				with torch.no_grad():
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   model(lowerCAmelCase__      )
								SCREAMING_SNAKE_CASE_   :	List[Any]													=   outputs.logits

				print(logits.shape      )
				print('First values of logits:'    ,    logits[0, 0, :3, :3]      )
				# assert values
				if model_name == "upernet-swin-tiny":
								SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   torch.tensor(
								    [[-7.5_958, -7.5_958, -7.4_302], [-7.5_958, -7.5_958, -7.4_302], [-7.4_797, -7.4_797, -7.3_068]]      )
				elif model_name == "upernet-swin-small":
								SCREAMING_SNAKE_CASE_   :	Optional[int]													=   torch.tensor(
								    [[-7.1_921, -7.1_921, -6.9_532], [-7.1_921, -7.1_921, -6.9_532], [-7.0_908, -7.0_908, -6.8_534]]      )
				elif model_name == "upernet-swin-base":
								SCREAMING_SNAKE_CASE_   :	Tuple													=   torch.tensor(
								    [[-6.5_851, -6.5_851, -6.4_330], [-6.5_851, -6.5_851, -6.4_330], [-6.4_763, -6.4_763, -6.3_254]]      )
				elif model_name == "upernet-swin-large":
								SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   torch.tensor(
								    [[-7.5_297, -7.5_297, -7.3_802], [-7.5_297, -7.5_297, -7.3_802], [-7.4_044, -7.4_044, -7.2_586]]      )
				print('Logits:'    ,    outputs.logits[0, 0, :3, :3]      )
				assert torch.allclose(outputs.logits[0, 0, :3, :3]    ,    lowerCAmelCase__    ,    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(lowerCAmelCase__      )
								print(F'''Saving processor to {pytorch_dump_folder_path}'''      )
								processor.save_pretrained(lowerCAmelCase__      )

				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        =			argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    '--model_name',
				    default='upernet-swin-tiny',
				    type=str,
				    choices=[f"""upernet-swin-{size}""" for size in ['tiny', 'small', 'base', 'large']],
				    help='Name of the Swin + 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        =			parser.parse_args()
				convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)







from abc import ABC, abstractmethod
from typing import List, Optional


class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self       ):
						# test for the above condition
						self.test()


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   0
						SCREAMING_SNAKE_CASE_   :	Dict													=   False
						while not completed:
										if counter == 1:
														self.reset()
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.advance()
										if not self.does_advance(UpperCamelCase__       ):
														raise Exception(
														    'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'       )

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Any													=   self.update(UpperCamelCase__       )
										counter += 1

										if counter > 10000:
														raise Exception('update() does not fulfill the constraint.'       )

						if self.remaining() != 0:
										raise Exception('Custom Constraint is not defined correctly.'       )


		@abstractmethod
		def   __snake_case			(						self       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )


		@abstractmethod
		def   __snake_case			(						self       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )






		@abstractmethod
		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						raise NotImplementedError(
						    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''       )






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) or len(UpperCamelCase__       ) == 0:
										raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.'''       )
						if any((not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) or token_id < 0) for token_id in token_ids       ):
										raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''       )

						SCREAMING_SNAKE_CASE_   :	List[str]													=   token_ids

						SCREAMING_SNAKE_CASE_   :	Tuple													=   len(self.token_ids       )
						SCREAMING_SNAKE_CASE_   :	Any													=   -1  # the index of the currently fulfilled step
						SCREAMING_SNAKE_CASE_   :	Any													=   False


		def   __snake_case			(						self       ):
						if self.completed:
										return None
						return self.token_ids[self.fulfilled_idx + 1]


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						if self.completed:
										return False

						return token_id == self.token_ids[self.fulfilled_idx + 1]


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False

						if self.does_advance(UpperCamelCase__       ):
										self.fulfilled_idx += 1
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   True
										if self.fulfilled_idx == (self.seqlen - 1):
														SCREAMING_SNAKE_CASE_   :	Dict													=   True
										SCREAMING_SNAKE_CASE_   :	List[str]													=   completed
						else:
										# failed to make progress.
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   True
										self.reset()
						return stepped, completed, reset


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   False
						SCREAMING_SNAKE_CASE_   :	List[str]													=   0


		def   __snake_case			(						self       ):
						return self.seqlen - (self.fulfilled_idx + 1)






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	str													=   PhrasalConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Any													=   self.fulfilled_idx
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__ ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   max([len(UpperCamelCase__       ) for one in nested_token_ids]       )

						SCREAMING_SNAKE_CASE_   :	List[Any]													=   {}
						for token_ids in nested_token_ids:
										SCREAMING_SNAKE_CASE_   :	Dict													=   root
										for tidx, token_id in enumerate(UpperCamelCase__       ):
														if token_id not in level:
																		SCREAMING_SNAKE_CASE_   :	Tuple													=   {}

														SCREAMING_SNAKE_CASE_   :	List[str]													=   level[token_id]

						if no_subsets and self.has_subsets(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(
										    'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
										    F''' {nested_token_ids}.'''       )

						SCREAMING_SNAKE_CASE_   :	Tuple													=   root


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	int													=   self.trie

						for current_token in current_seq:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   start[current_token]

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   list(start.keys()       )

						return next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.next_tokens(UpperCamelCase__       )

						return len(UpperCamelCase__       ) == 0


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   list(root.values()       )
						if len(UpperCamelCase__       ) == 0:
										return 1
						else:
										return sum([self.count_leaves(UpperCamelCase__       ) for nn in next_nodes]       )






		def   __snake_case			(						self ,    UpperCamelCase__ ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Dict													=   self.count_leaves(UpperCamelCase__       )
						return len(UpperCamelCase__       ) != leaf_count






class 							__a							(  __A						):





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						super(UpperCamelCase__ ,    self       ).__init__()

						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) or len(UpperCamelCase__       ) == 0:
										raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''       )
						if any(not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) for token_ids in nested_token_ids       ):
										raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''       )
						if any(
						    any((not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ) or token_id < 0) for token_id in token_ids       )
						    for token_ids in nested_token_ids       ):
										raise ValueError(
										    F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   DisjunctiveTrie(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Dict													=   nested_token_ids

						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.max_height
						SCREAMING_SNAKE_CASE_   :	str													=   []
						SCREAMING_SNAKE_CASE_   :	List[str]													=   False


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[str]													=   self.trie.next_tokens(self.current_seq       )

						if len(UpperCamelCase__       ) == 0:
										return None
						else:
										return token_list


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	str													=   self.trie.next_tokens(self.current_seq       )

						return token_id in next_tokens


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase__       )}'''       )

						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Tuple													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   False

						if self.does_advance(UpperCamelCase__       ):
										self.current_seq.append(UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	int													=   True
						else:
										SCREAMING_SNAKE_CASE_   :	Tuple													=   True
										self.reset()

						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   self.trie.reached_leaf(self.current_seq       )
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   completed

						return stepped, completed, reset


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   False
						SCREAMING_SNAKE_CASE_   :	Dict													=   []


		def   __snake_case			(						self       ):
						if self.completed:
										# since this can be completed without reaching max height
										return 0
						else:
										return self.seqlen - len(self.current_seq       )






		def   __snake_case			(						self ,    UpperCamelCase__=False       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   DisjunctiveConstraint(self.token_ids       )

						if stateful:
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   self.seqlen
										SCREAMING_SNAKE_CASE_   :	Optional[int]													=   self.current_seq
										SCREAMING_SNAKE_CASE_   :	List[str]													=   self.completed

						return new_constraint






class 							__a							:





		'''simple docstring'''



		def __init__(						self ,    UpperCamelCase__       ):
						SCREAMING_SNAKE_CASE_   :	Any													=   constraints

						# max # of steps required to fulfill a given constraint
						SCREAMING_SNAKE_CASE_   :	Dict													=   max([c.seqlen for c in constraints]       )
						SCREAMING_SNAKE_CASE_   :	Tuple													=   len(UpperCamelCase__       )
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   False

						self.init_state()


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	List[Any]													=   []
						SCREAMING_SNAKE_CASE_   :	int													=   None
						SCREAMING_SNAKE_CASE_   :	Optional[int]													=   [constraint.copy(stateful=UpperCamelCase__       ) for constraint in self.constraints]


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   0
						if self.inprogress_constraint:
										# extra points for having a constraint mid-fulfilled
										add += self.max_seqlen - self.inprogress_constraint.remaining()

						return (len(self.complete_constraints       ) * self.max_seqlen) + add


		def   __snake_case			(						self       ):
						SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   []
						if self.inprogress_constraint is None:
										for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
														SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   constraint.advance()
														if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
																		token_list.append(UpperCamelCase__       )
														elif isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
																		token_list.extend(UpperCamelCase__       )
						else:
										SCREAMING_SNAKE_CASE_   :	List[str]													=   self.inprogress_constraint.advance()
										if isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
														token_list.append(UpperCamelCase__       )
										elif isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
														token_list.extend(UpperCamelCase__       )

						if len(UpperCamelCase__       ) == 0:
										return None
						else:
										return token_list


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						self.init_state()

						if token_ids is not None:
										for token in token_ids:
														# completes or steps **one** constraint
														SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	str													=   self.add(UpperCamelCase__       )

														# the entire list of constraints are fulfilled
														if self.completed:
																		break


		def   __snake_case			(						self ,    UpperCamelCase__       ):
						if not isinstance(UpperCamelCase__ ,    UpperCamelCase__       ):
										raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''       )

						SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   False, False

						if self.completed:
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   True
										SCREAMING_SNAKE_CASE_   :	Union[str, Any]													=   False
										return complete, stepped

						if self.inprogress_constraint is not None:
										# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
										# job, simply update the state

										SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   self.inprogress_constraint.update(UpperCamelCase__       )
										if reset:
														# 1. If the next token breaks the progress, then we must restart.
														#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

														#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
														#     constraint, not the full list of constraints.

														self.pending_constraints.append(self.inprogress_constraint.copy(stateful=UpperCamelCase__       )       )
														SCREAMING_SNAKE_CASE_   :	Dict													=   None

										if complete:
														# 2. If the next token completes the constraint, move it to completed list, set
														#     inprogress to None. If there are no pending constraints either, then this full list of constraints
														#     is complete.

														self.complete_constraints.append(self.inprogress_constraint       )
														SCREAMING_SNAKE_CASE_   :	str													=   None

														if len(self.pending_constraints       ) == 0:
																		# we're done!
																		SCREAMING_SNAKE_CASE_   :	Tuple													=   True

						else:
										# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
										# of constraints?

										for cidx, pending_constraint in enumerate(self.pending_constraints       ):
														if pending_constraint.does_advance(UpperCamelCase__       ):
																		SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_							,       SCREAMING_SNAKE_CASE_   :	Dict													=   pending_constraint.update(UpperCamelCase__       )

																		if not stepped:
																						raise Exception(
																						    '`constraint.update(token_id)` is not yielding incremental progress, '
																						    'even though `constraint.does_advance(token_id)` is true.'       )

																		if complete:
																						self.complete_constraints.append(UpperCamelCase__       )
																						SCREAMING_SNAKE_CASE_   :	List[str]													=   None

																		if not complete and stepped:
																						SCREAMING_SNAKE_CASE_   :	List[str]													=   pending_constraint

																		if complete or stepped:
																						# If we made any progress at all, then it's at least not a "pending constraint".

																						SCREAMING_SNAKE_CASE_   :	Any													=   (
																						    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																						)

																						if len(self.pending_constraints       ) == 0 and self.inprogress_constraint is None:
																										# If there's no longer any pending after this and no inprogress either, then we must be
																										# complete.

																										SCREAMING_SNAKE_CASE_   :	Dict													=   True

																						break  # prevent accidentally stepping through multiple constraints with just one token.

						return complete, stepped






		def   __snake_case			(						self ,    UpperCamelCase__=True       ):
						SCREAMING_SNAKE_CASE_   :	Tuple													=   ConstraintListState(self.constraints       )  # we actually never though self.constraints objects
						# throughout this process. So it's at initialization state.

						if stateful:
										SCREAMING_SNAKE_CASE_   :	List[str]													=   [
										    constraint.copy(stateful=UpperCamelCase__       ) for constraint in self.complete_constraints
										]
										if self.inprogress_constraint is not None:
														SCREAMING_SNAKE_CASE_   :	List[Any]													=   self.inprogress_constraint.copy(stateful=UpperCamelCase__       )
										SCREAMING_SNAKE_CASE_   :	Optional[Any]													=   [constraint.copy() for constraint in self.pending_constraints]

						return new_state