


import argparse
import json
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Callable, Dict, List, Tuple

import timm
import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.utils import logging


logging.set_verbosity_info()
snake_case							:	Dict					      =				logging.get_logger()
@dataclass
class 	snake_case_       :
					UpperCAmelCase__ :   nn.Module
					UpperCAmelCase__ :   List[nn.Module]   				=      field(default_factory=__snake_case				)
					UpperCAmelCase__ :   list   				=      field(default_factory=__snake_case				)
					def 			lowerCamelCase__(				self       :str      ,__snake_case       :List[str]      ,__snake_case       :Tensor      ,__snake_case       :Tensor				) ->   Optional[int]:
												a__					=					len(list(m.modules()				)				) == 1 or isinstance(lowerCamelCase_      ,nn.Convad				) or isinstance(lowerCamelCase_      ,nn.BatchNormad				)
												if has_not_submodules:
																			self.traced.append(lowerCamelCase_				)
					def __call__(				self       :Tuple      ,__snake_case       :Tensor				) ->   Dict:
												for m in self.module.modules():
																			self.handles.append(m.register_forward_hook(self._forward_hook				)				)
												self.module(lowerCamelCase_				)
												[x.remove() for x in self.handles]
												return self



					@property
					def 			lowerCamelCase__(				self       :List[str]				) ->   int:
												# check the len of the state_dict keys to see if we have learnable params
												return list(filter(lambda __snake_case				: len(list(x.state_dict().keys()				)				) > 0      ,self.traced				)				)





@dataclass
class 	snake_case_       :
					UpperCAmelCase__ :   nn.Module
					UpperCAmelCase__ :   nn.Module
					UpperCAmelCase__ :   int   				=      1
					UpperCAmelCase__ :   List   				=      field(default_factory=__snake_case				)
					UpperCAmelCase__ :   List   				=      field(default_factory=__snake_case				)
					UpperCAmelCase__ :   bool   				=      True
					def __call__(				self       :Tuple      ,__snake_case       :Tensor				) ->   Optional[Any]:
												a__					=					Tracker(self.dest				)(lowerCamelCase_				).parametrized
												a__					=					Tracker(self.src				)(lowerCamelCase_				).parametrized

												a__					=					list(filter(lambda __snake_case				: type(lowerCamelCase_				) not in self.src_skip      ,lowerCamelCase_				)				)
												a__					=					list(filter(lambda __snake_case				: type(lowerCamelCase_				) not in self.dest_skip      ,lowerCamelCase_				)				)

												if len(lowerCamelCase_				) != len(lowerCamelCase_				) and self.raise_if_mismatch:
																			raise Exception(
																			    F'Numbers of operations are different. Source module has {len(lowerCamelCase_				)} operations while'
																			    F' destination module has {len(lowerCamelCase_				)}.'				)

												for dest_m, src_m in zip(lowerCamelCase_      ,lowerCamelCase_				):
																			dest_m.load_state_dict(src_m.state_dict()				)
																			if self.verbose == 1:
																										print(F'Transfered from={src_m} to={dest_m}'				)





class 	snake_case_       (nn.Module				):
					def __init__(				self       :List[str]      ,__snake_case       :nn.Module				) ->   List[str]:
												super().__init__()

												a__					=					[]
												# - get the stem
												feature_blocks.append(('conv1', model.stem)				)
												# - get all the feature blocks
												for k, v in model.trunk_output.named_children():
																			assert k.startswith('block'				), F'Unexpected layer name {k}'
																			a__					=					len(lowerCamelCase_				) + 1
																			feature_blocks.append((F'res{block_index}', v)				)

												a__					=					nn.ModuleDict(lowerCamelCase_				)



					def 			lowerCamelCase__(				self       :Union[str, Any]      ,__snake_case       :Tensor				) ->   List[str]:
												return get_trunk_forward_outputs(
												    lowerCamelCase_      ,out_feat_keys=lowerCamelCase_      ,feature_blocks=self._feature_blocks      ,)





class 	snake_case_       (__snake_case				):
					def 			lowerCamelCase__(				self       :Dict      ,__snake_case       :str				) ->   str:
												a__					=					x.split('-'				)
												return x_split[0] + x_split[1] + "_" + "".join(x_split[2:]				)



					def __getitem__(				self       :Union[str, Any]      ,__snake_case       :str				) ->   Callable[[], Tuple[nn.Module, Dict]]:
												# default to timm!
												if x not in self:
																			a__					=					self.convert_name_to_timm(lowerCamelCase_				)
																			a__					=					partial(lambda: (timm.create_model(lowerCamelCase_      ,pretrained=lowerCamelCase_				).eval(), None)				)

												else:
																			a__					=					super().__getitem__(lowerCamelCase_				)

												return val





class 	snake_case_       (__snake_case				):
					def __getitem__(				self       :Union[str, Any]      ,__snake_case       :str				) ->   Callable[[], nn.Module]:
												if "seer" in x and "in1k" not in x:
																			a__					=					RegNetModel
												else:
																			a__					=					RegNetForImageClassification
												return val






def 							__lowercase       (			__lowerCAmelCase							:    str ,   __lowerCAmelCase							:    int ,   __lowerCAmelCase							:    List[Tuple[str, str]]       ):




							for from_key, to_key in keys:
														a__					=					from_state_dict[from_key].clone()
														print(F'Copied key={from_key} to={to_key}'       )
							return to_state_dict






def 							__lowercase       (			__lowerCAmelCase							:    str ,   __lowerCAmelCase							:    Callable[[], nn.Module] ,   __lowerCAmelCase							:    Callable[[], nn.Module] ,   __lowerCAmelCase							:    RegNetConfig ,   __lowerCAmelCase							:    Path ,   __lowerCAmelCase							:    bool = True ,   ):
							print(F'Converting {name}...'       )
							with torch.no_grad():
														a__					=					from_model_func()
														a__					=					our_model_func(_a       ).eval()
														a__					=					ModuleTransfer(src=_a ,   dest=_a ,   raise_if_mismatch=_a       )
														a__					=					torch.randn((1, 3, 2_2_4, 2_2_4)       )
														module_transfer(_a       )

							if from_state_dict is not None:
														a__					=					[]
														# for seer - in1k finetuned we have to manually copy the head
														if "seer" in name and "in1k" in name:
																					a__					=					[("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")]
														a__					=					manually_copy_vissl_head(_a ,   our_model.state_dict() ,   _a       )
														our_model.load_state_dict(_a       )

							a__					=					our_model(_a ,   output_hidden_states=_a       )
							a__					=					(
							    our_outputs.logits if isinstance(_a ,   _a       ) else our_outputs.last_hidden_state
							)

							a__					=					from_model(_a       )
							a__					=					from_output[-1] if type(_a       ) is list else from_output

							# now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state
							if "seer" in name and "in1k" in name:
														a__					=					our_outputs.hidden_states[-1]

							assert torch.allclose(_a ,   _a       ), "The model logits don't match the original one."

							if push_to_hub:
														our_model.push_to_hub(
														    repo_path_or_name=save_directory / name ,   commit_message='Add model' ,   use_temp_dir=_a ,   )

														a__					=					2_2_4 if """seer""" not in name else 3_8_4
														# we can use the convnext one
														a__					=					AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ,   size=_a       )
														image_processor.push_to_hub(
														    repo_path_or_name=save_directory / name ,   commit_message='Add image processor' ,   use_temp_dir=_a ,   )

														print(F'Pushed {name}'       )






def 							__lowercase       (			__lowerCAmelCase							:    Path ,   __lowerCAmelCase							:    str = None ,   __lowerCAmelCase							:    bool = True       ):
							a__					=					"""imagenet-1k-id2label.json"""
							a__					=					1_0_0_0
							a__					=					(1, num_labels)

							a__					=					"""huggingface/label-files"""
							a__					=					num_labels
							a__					=					json.load(open(cached_download(hf_hub_url(_a ,   _a ,   repo_type='dataset'       )       ) ,   'r'       )       )
							a__					=					{int(_a       ): v for k, v in idalabel.items()}

							a__					=					idalabel
							a__					=					{v: k for k, v in idalabel.items()}

							a__					=					partial(_a ,   num_labels=_a ,   idalabel=_a ,   labelaid=_a       )

							a__					=					{
							    """regnet-x-002""": ImageNetPreTrainedConfig(
							        depths=[1, 1, 4, 7] ,   hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8] ,   groups_width=8 ,   layer_type='x'       ),
							    """regnet-x-004""": ImageNetPreTrainedConfig(
							        depths=[1, 2, 7, 1_2] ,   hidden_sizes=[3_2, 6_4, 1_6_0, 3_8_4] ,   groups_width=1_6 ,   layer_type='x'       ),
							    """regnet-x-006""": ImageNetPreTrainedConfig(
							        depths=[1, 3, 5, 7] ,   hidden_sizes=[4_8, 9_6, 2_4_0, 5_2_8] ,   groups_width=2_4 ,   layer_type='x'       ),
							    """regnet-x-008""": ImageNetPreTrainedConfig(
							        depths=[1, 3, 7, 5] ,   hidden_sizes=[6_4, 1_2_8, 2_8_8, 6_7_2] ,   groups_width=1_6 ,   layer_type='x'       ),
							    """regnet-x-016""": ImageNetPreTrainedConfig(
							        depths=[2, 4, 1_0, 2] ,   hidden_sizes=[7_2, 1_6_8, 4_0_8, 9_1_2] ,   groups_width=2_4 ,   layer_type='x'       ),
							    """regnet-x-032""": ImageNetPreTrainedConfig(
							        depths=[2, 6, 1_5, 2] ,   hidden_sizes=[9_6, 1_9_2, 4_3_2, 1_0_0_8] ,   groups_width=4_8 ,   layer_type='x'       ),
							    """regnet-x-040""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_4, 2] ,   hidden_sizes=[8_0, 2_4_0, 5_6_0, 1_3_6_0] ,   groups_width=4_0 ,   layer_type='x'       ),
							    """regnet-x-064""": ImageNetPreTrainedConfig(
							        depths=[2, 4, 1_0, 1] ,   hidden_sizes=[1_6_8, 3_9_2, 7_8_4, 1_6_2_4] ,   groups_width=5_6 ,   layer_type='x'       ),
							    """regnet-x-080""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_5, 1] ,   hidden_sizes=[8_0, 2_4_0, 7_2_0, 1_9_2_0] ,   groups_width=1_2_0 ,   layer_type='x'       ),
							    """regnet-x-120""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_1, 1] ,   hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0] ,   groups_width=1_1_2 ,   layer_type='x'       ),
							    """regnet-x-160""": ImageNetPreTrainedConfig(
							        depths=[2, 6, 1_3, 1] ,   hidden_sizes=[2_5_6, 5_1_2, 8_9_6, 2_0_4_8] ,   groups_width=1_2_8 ,   layer_type='x'       ),
							    """regnet-x-320""": ImageNetPreTrainedConfig(
							        depths=[2, 7, 1_3, 1] ,   hidden_sizes=[3_3_6, 6_7_2, 1_3_4_4, 2_5_2_0] ,   groups_width=1_6_8 ,   layer_type='x'       ),
							    # y variant
							    """regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] ,   hidden_sizes=[2_4, 5_6, 1_5_2, 3_6_8] ,   groups_width=8       ),
							    """regnet-y-004""": ImageNetPreTrainedConfig(
							        depths=[1, 3, 6, 6] ,   hidden_sizes=[4_8, 1_0_4, 2_0_8, 4_4_0] ,   groups_width=8       ),
							    """regnet-y-006""": ImageNetPreTrainedConfig(
							        depths=[1, 3, 7, 4] ,   hidden_sizes=[4_8, 1_1_2, 2_5_6, 6_0_8] ,   groups_width=1_6       ),
							    """regnet-y-008""": ImageNetPreTrainedConfig(
							        depths=[1, 3, 8, 2] ,   hidden_sizes=[6_4, 1_2_8, 3_2_0, 7_6_8] ,   groups_width=1_6       ),
							    """regnet-y-016""": ImageNetPreTrainedConfig(
							        depths=[2, 6, 1_7, 2] ,   hidden_sizes=[4_8, 1_2_0, 3_3_6, 8_8_8] ,   groups_width=2_4       ),
							    """regnet-y-032""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_3, 1] ,   hidden_sizes=[7_2, 2_1_6, 5_7_6, 1_5_1_2] ,   groups_width=2_4       ),
							    """regnet-y-040""": ImageNetPreTrainedConfig(
							        depths=[2, 6, 1_2, 2] ,   hidden_sizes=[1_2_8, 1_9_2, 5_1_2, 1_0_8_8] ,   groups_width=6_4       ),
							    """regnet-y-064""": ImageNetPreTrainedConfig(
							        depths=[2, 7, 1_4, 2] ,   hidden_sizes=[1_4_4, 2_8_8, 5_7_6, 1_2_9_6] ,   groups_width=7_2       ),
							    """regnet-y-080""": ImageNetPreTrainedConfig(
							        depths=[2, 4, 1_0, 1] ,   hidden_sizes=[1_6_8, 4_4_8, 8_9_6, 2_0_1_6] ,   groups_width=5_6       ),
							    """regnet-y-120""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_1, 1] ,   hidden_sizes=[2_2_4, 4_4_8, 8_9_6, 2_2_4_0] ,   groups_width=1_1_2       ),
							    """regnet-y-160""": ImageNetPreTrainedConfig(
							        depths=[2, 4, 1_1, 1] ,   hidden_sizes=[2_2_4, 4_4_8, 1_2_3_2, 3_0_2_4] ,   groups_width=1_1_2       ),
							    """regnet-y-320""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_2, 1] ,   hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2] ,   groups_width=2_3_2       ),
							    # models created by SEER -> https://arxiv.org/abs/2202.08360
							    """regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 1_2, 1] ,   hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2] ,   groups_width=2_3_2       ),
							    """regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 1_2, 1] ,   hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0] ,   groups_width=3_2_8       ),
							    """regnet-y-1280-seer""": RegNetConfig(
							        depths=[2, 7, 1_7, 1] ,   hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2] ,   groups_width=2_6_4       ),
							    """regnet-y-2560-seer""": RegNetConfig(
							        depths=[3, 7, 1_6, 1] ,   hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8] ,   groups_width=6_4_0       ),
							    """regnet-y-10b-seer""": ImageNetPreTrainedConfig(
							        depths=[2, 7, 1_7, 1] ,   hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0] ,   groups_width=1_0_1_0       ),
							    # finetuned on imagenet
							    """regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_2, 1] ,   hidden_sizes=[2_3_2, 6_9_6, 1_3_9_2, 3_7_1_2] ,   groups_width=2_3_2       ),
							    """regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig(
							        depths=[2, 5, 1_2, 1] ,   hidden_sizes=[3_2_8, 9_8_4, 1_9_6_8, 4_9_2_0] ,   groups_width=3_2_8       ),
							    """regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig(
							        depths=[2, 7, 1_7, 1] ,   hidden_sizes=[5_2_8, 1_0_5_6, 2_9_0_4, 7_3_9_2] ,   groups_width=2_6_4       ),
							    """regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig(
							        depths=[3, 7, 1_6, 1] ,   hidden_sizes=[6_4_0, 1_6_9_6, 2_5_4_4, 5_0_8_8] ,   groups_width=6_4_0       ),
							    """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig(
							        depths=[2, 7, 1_7, 1] ,   hidden_sizes=[2_0_2_0, 4_0_4_0, 1_1_1_1_0, 2_8_2_8_0] ,   groups_width=1_0_1_0       ),
							}

							a__					=					NameToOurModelFuncMap()
							a__					=					NameToFromModelFuncMap()
							# add seer weights logic

							def load_using_classy_vision(__lowerCAmelCase							:    str ,   __lowerCAmelCase							:    Callable[[], nn.Module]       ) -> Tuple[nn.Module, Dict]:
														a__					=					torch.hub.load_state_dict_from_url(_a ,   model_dir=str(_a       ) ,   map_location='cpu'       )
														a__					=					model_func()
														# check if we have a head, if yes add it
														a__					=					files["""classy_state_dict"""]["""base_model"""]["""model"""]
														a__					=					model_state_dict["""trunk"""]
														model.load_state_dict(_a       )
														return model.eval(), model_state_dict["heads"]

							# pretrained
							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' ,   lambda: FakeRegNetVisslWrapper(
							        RegNet(RegNetParams(depth=2_7 ,   group_width=1_0_1_0 ,   w_a=1_7_4_4 ,   w_a=6_2_0.8_3 ,   w_m=2.52       )       )       ) ,   )

							# IN1K finetuned
							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' ,   lambda: FakeRegNetVisslWrapper(RegNetYaaagf()       ) ,   )

							a__					=					partial(
							    _a ,   'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' ,   lambda: FakeRegNetVisslWrapper(
							        RegNet(RegNetParams(depth=2_7 ,   group_width=1_0_1_0 ,   w_a=1_7_4_4 ,   w_a=6_2_0.8_3 ,   w_m=2.52       )       )       ) ,   )

							if model_name:
														convert_weight_and_push(
														    _a ,   names_to_from_model_map[model_name] ,   names_to_ours_model_map[model_name] ,   names_to_config[model_name] ,   _a ,   _a ,   )
							else:
														for model_name, config in names_to_config.items():
																					convert_weight_and_push(
																					    _a ,   names_to_from_model_map[model_name] ,   names_to_ours_model_map[model_name] ,   _a ,   _a ,   _a ,   )
							return config, expected_shape


if __name__ == "__main__":
						snake_case							:	int					      =				argparse.ArgumentParser()
						# Required parameters
						parser.add_argument(
						    '''--model_name''',
						    default=None,
						    type=str,
						    help=(
						        '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,'''
						        ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'''
						    ),
						)
						parser.add_argument(
						    '''--pytorch_dump_folder_path''',
						    default=None,
						    type=Path,
						    required=True,
						    help='''Path to the output PyTorch model directory.''',
						)
						parser.add_argument(
						    '''--push_to_hub''',
						    default=True,
						    type=bool,
						    required=False,
						    help='''If True, push model and image processor to the hub.''',
						)

						snake_case							:	Dict					      =				parser.parse_args()

						snake_case							:	Union[str, Any]					      =				args.pytorch_dump_folder_path
						pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
						convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)








import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


snake_case							:	Dict					      =				get_logger(__name__)


snake_case							:	str					      =				r'''
    Args:
        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
            search or log softmax for each vocabulary token when using beam search
        kwargs (`Dict[str, Any]`, *optional*):
            Additional logits processor specific kwargs.

    Return:
        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.

'''







class 	snake_case_       :
					@add_start_docstrings(__snake_case				)
					def __call__(				self       :Dict      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray				) ->   jnp.ndarray:
												raise NotImplementedError(
												    F'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'				)







class 	snake_case_       :
					@add_start_docstrings(__snake_case				)
					def __call__(				self       :List[str]      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray				) ->   jnp.ndarray:
												raise NotImplementedError(
												    F'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'				)







class 	snake_case_       (lowerCamelCase_				):
					@add_start_docstrings(__snake_case				)
					def __call__(				self       :Dict      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int      ,**__snake_case       :Any				) ->   jnp.ndarray:
												for processor in self:
																			a__					=					inspect.signature(processor.__call__				).parameters
																			if len(__snake_case				) > 3:
																										if not all(arg in kwargs for arg in list(function_args.keys()				)[2:]				):
																																	raise ValueError(
																																	    F'Make sure that all the required parameters: {list(function_args.keys()				)} for '
																																	    F'{processor.__class__} are passed to the logits processor.'				)
																										a__					=					processor(__snake_case      ,__snake_case      ,__snake_case      ,**__snake_case				)
																			else:
																										a__					=					processor(__snake_case      ,__snake_case      ,__snake_case				)
												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :str      ,__snake_case       :float				) ->   Tuple:
												if not isinstance(__snake_case      ,__snake_case				) or not (temperature > 0):
																			raise ValueError(F'`temperature` has to be a strictly positive float, but is {temperature}'				)

												a__					=					temperature



					def __call__(				self       :Optional[int]      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__					=					scores / self.temperature
												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :Any      ,__snake_case       :float      ,__snake_case       :float = -float('Inf'				)      ,__snake_case       :int = 1				) ->   Dict:
												if not isinstance(__snake_case      ,__snake_case				) or (top_p < 0 or top_p > 1.0):
																			raise ValueError(F'`top_p` has to be a float > 0 and < 1, but is {top_p}'				)
												if not isinstance(__snake_case      ,__snake_case				) or (min_tokens_to_keep < 1):
																			raise ValueError(F'`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}'				)

												a__					=					top_p
												a__					=					filter_value
												a__					=					min_tokens_to_keep



					def __call__(				self       :Optional[int]      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__				, a__					=					lax.top_k(__snake_case      ,scores.shape[-1]				)

												a__					=					jnp.full_like(__snake_case      ,self.filter_value				)
												a__					=					jax.nn.softmax(__snake_case      ,axis=-1				).cumsum(axis=-1				)
												a__					=					cumulative_probs < self.top_p

												# include the token that is higher than top_p as well
												a__					=					jnp.roll(__snake_case      ,1				)
												score_mask |= score_mask.at[:, 0].set(__snake_case				)

												# min tokens to keep
												a__					=					score_mask.at[:, : self.min_tokens_to_keep].set(__snake_case				)

												a__					=					jnp.where(__snake_case      ,__snake_case      ,__snake_case				)
												a__					=					jax.lax.sort_key_val(__snake_case      ,__snake_case				)[-1]

												return next_scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :List[str]      ,__snake_case       :int      ,__snake_case       :float = -float('Inf'				)      ,__snake_case       :int = 1				) ->   Any:
												if not isinstance(__snake_case      ,__snake_case				) or top_k <= 0:
																			raise ValueError(F'`top_k` has to be a strictly positive integer, but is {top_k}'				)

												a__					=					max(__snake_case      ,__snake_case				)
												a__					=					filter_value



					def __call__(				self       :int      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__				, a__					=					scores.shape
												a__					=					jnp.full(batch_size * vocab_size      ,self.filter_value				)

												a__					=					min(self.top_k      ,scores.shape[-1]				)  # Safety check
												a__				, a__					=					lax.top_k(__snake_case      ,__snake_case				)
												a__					=					jnp.broadcast_to((jnp.arange(__snake_case				) * vocab_size)[:, None]      ,(batch_size, topk)				).flatten()
												a__					=					topk_scores.flatten()
												a__					=					topk_indices.flatten() + shift

												a__					=					next_scores_flat.at[topk_indices_flat].set(__snake_case				)
												a__					=					next_scores_flat.reshape(__snake_case      ,__snake_case				)
												return next_scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :int      ,__snake_case       :int				) ->   str:
												a__					=					bos_token_id



					def __call__(				self       :List[Any]      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__					=					jnp.full(scores.shape      ,-float('inf'				)				)

												a__					=					1 - jnp.bool_(cur_len - 1				)

												a__					=					jnp.where(__snake_case      ,new_scores.at[:, self.bos_token_id].set(0				)      ,__snake_case				)

												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :Union[str, Any]      ,__snake_case       :int      ,__snake_case       :int				) ->   List[Any]:
												a__					=					max_length
												a__					=					eos_token_id



					def __call__(				self       :int      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__					=					jnp.full(scores.shape      ,-float('inf'				)				)

												a__					=					1 - jnp.bool_(cur_len - self.max_length + 1				)

												a__					=					jnp.where(__snake_case      ,new_scores.at[:, self.eos_token_id].set(0				)      ,__snake_case				)

												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :str      ,__snake_case       :int      ,__snake_case       :int				) ->   List[str]:
												if not isinstance(__snake_case      ,__snake_case				) or min_length < 0:
																			raise ValueError(F'`min_length` has to be a positive integer, but is {min_length}'				)

												if not isinstance(__snake_case      ,__snake_case				) or eos_token_id < 0:
																			raise ValueError(F'`eos_token_id` has to be a positive integer, but is {eos_token_id}'				)

												a__					=					min_length
												a__					=					eos_token_id



					def __call__(				self       :Any      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												# create boolean flag to decide if min length penalty should be applied
												a__					=					1 - jnp.clip(cur_len - self.min_length      ,0      ,1				)

												a__					=					jnp.where(__snake_case      ,scores.at[:, self.eos_token_id].set(-float('inf'				)				)      ,__snake_case				)

												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :Optional[int]      ,__snake_case       :List[str]      ,__snake_case       :Optional[int]				) ->   Tuple:
												a__					=					list(__snake_case				)
												a__					=					begin_index



					def __call__(				self       :str      ,__snake_case       :List[str]      ,__snake_case       :str      ,__snake_case       :int				) ->   str:
												a__					=					1 - jnp.bool_(cur_len - self.begin_index				)

												a__					=					jnp.where(__snake_case      ,scores.at[:, self.begin_suppress_tokens].set(-float('inf'				)				)      ,__snake_case				)

												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :List[str]      ,__snake_case       :list				) ->   List[Any]:
												a__					=					list(__snake_case				)



					def __call__(				self       :Dict      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												a__					=					scores.at[..., self.suppress_tokens].set(-float('inf'				)				)

												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :Dict      ,__snake_case       :Optional[int]				) ->   Union[str, Any]:
												a__					=					dict(__snake_case				)
												# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
												# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
												# Indexes without forced tokens will have a negative value.
												a__					=					jnp.ones((max(force_token_map.keys()				) + 1)      ,dtype=jnp.intaa				) * -1
												for index, token in force_token_map.items():
																			if token is not None:
																										a__					=					force_token_array.at[index].set(__snake_case				)
												a__					=					jnp.intaa(__snake_case				)



					def __call__(				self       :Optional[int]      ,__snake_case       :jnp.ndarray      ,__snake_case       :jnp.ndarray      ,__snake_case       :int				) ->   jnp.ndarray:
												def _force_token(__snake_case       :Optional[Any]				):
																			a__					=					scores.shape[0]
																			a__					=					self.force_token_array[generation_idx]

																			a__					=					jnp.ones_like(__snake_case      ,dtype=scores.dtype				) * -float('inf'				)
																			a__					=					jnp.zeros((batch_size, 1)      ,dtype=scores.dtype				)
																			a__					=					lax.dynamic_update_slice(__snake_case      ,__snake_case      ,(0, current_token)				)
																			return new_scores

												a__					=					lax.cond(
												    cur_len >= self.force_token_array.shape[0]      ,lambda: scores      ,lambda: lax.cond(
												        self.force_token_array[cur_len] >= 0      ,lambda: _force_token(__snake_case				)      ,lambda: scores      ,)      ,)
												return scores







class 	snake_case_       (lowerCamelCase_				):
					def __init__(				self       :Any      ,__snake_case       :List[str]      ,__snake_case       :str      ,__snake_case       :List[Any]				) ->   Optional[int]:
												a__					=					generate_config.eos_token_id
												a__					=					generate_config.no_timestamps_token_id
												a__					=					generate_config.no_timestamps_token_id + 1

												a__					=					decoder_input_length + 1

												if generate_config.is_multilingual:
																			# room for language token and task token
																			self.begin_index += 2
												if hasattr(__snake_case      ,'max_initial_timestamp_index'				):
																			a__					=					generate_config.max_initial_timestamp_index
												else:
																			a__					=					model_config.vocab_size
												if self.max_initial_timestamp_index is None:
																			a__					=					model_config.vocab_size



					def __call__(				self       :Any      ,__snake_case       :List[Any]      ,__snake_case       :Optional[int]      ,__snake_case       :Optional[Any]				) ->   Tuple:
												# suppress <|notimestamps|> which is handled by without_timestamps
												a__					=					scores.at[:, self.no_timestamps_token_id].set(-float('inf'				)				)

												def handle_pairs(__snake_case       :List[str]      ,__snake_case       :Union[str, Any]				):
																			a__					=					jnp.where((cur_len - self.begin_index) >= 1      ,__snake_case      ,__snake_case				)
																			a__					=					jnp.where(
																			    input_ids_k[cur_len - 1] >= self.timestamp_begin      ,True and last_was_timestamp      ,__snake_case      ,)

																			a__					=					jnp.where((cur_len - self.begin_index) < 2      ,__snake_case      ,__snake_case				)
																			a__					=					jnp.where(
																			    input_ids_k[cur_len - 2] >= self.timestamp_begin      ,__snake_case      ,__snake_case      ,)

																			return jnp.where(
																			    __snake_case      ,jnp.where(
																			        penultimate_was_timestamp > 0      ,scores_k.at[self.timestamp_begin :].set(-float('inf'				)				)      ,scores_k.at[: self.eos_token_id].set(-float('inf'				)				)      ,)      ,__snake_case      ,)

												a__					=					jax.vmap(__snake_case				)(__snake_case      ,__snake_case				)

												a__					=					jnp.where(cur_len == self.begin_index      ,__snake_case      ,__snake_case				)
												a__					=					jnp.where(
												    self.max_initial_timestamp_index is not None      ,True and apply_max_initial_timestamp      ,__snake_case      ,)

												a__					=					self.timestamp_begin + self.max_initial_timestamp_index

												a__					=					jnp.where(
												    __snake_case      ,scores.at[:, last_allowed + 1 :].set(-float('inf'				)				)      ,__snake_case      ,)

												# if sum of probability over timestamps is above any other token, sample timestamp
												a__					=					jax.nn.log_softmax(__snake_case      ,axis=-1				)

												def handle_cumulative_probs(__snake_case       :Dict      ,__snake_case       :List[Any]				):
																			a__					=					jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]      ,axis=-1				)
																			a__					=					jnp.max(logprobs_k[: self.timestamp_begin]				)
																			return jnp.where(
																			    timestamp_logprob > max_text_token_logprob      ,scores_k.at[: self.timestamp_begin].set(-float('inf'				)				)      ,__snake_case      ,)

												a__					=					jax.vmap(__snake_case				)(__snake_case      ,__snake_case				)

												return scores




