
from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


snake_case__  							=							logging.get_logger(__name__)

# General docstring
snake_case__  							=							"""ResNetConfig"""

# Base docstring
snake_case__  							=							"""microsoft/resnet-50"""
snake_case__  							=							[1, 20_48, 7, 7]

# Image classification docstring
snake_case__  							=							"""microsoft/resnet-50"""
snake_case__  							=							"""tiger cat"""

snake_case__  							=							[
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					Tuple ,      lowerCAmelCase      :					Tuple ,      lowerCAmelCase      :					str = 3 ,      lowerCAmelCase      :					Tuple = 1 ,      lowerCAmelCase      :					List[Any] = "relu" ,      **lowerCAmelCase      :					List[str]					):
											super().__init__(**lowercase_					)
											lowercase       :    List[Any]											=  kernel_size // 2
											lowercase       :    Tuple											=  tf.keras.layers.ConvaD(
											    lowercase_ ,      kernel_size=lowercase_ ,      strides=lowercase_ ,      padding='''valid''' ,      use_bias=lowercase_ ,      name='''convolution'''					)
											# Use same default momentum and epsilon as PyTorch equivalent
											lowercase       :    Optional[int]											=  tf.keras.layers.BatchNormalization(epsilon=1E-5 ,      momentum=0.9 ,      name='''normalization'''					)
											lowercase       :    List[Any]											=  ACTaFN[activation] if activation is not None else tf.keras.layers.Activation('''linear'''					)

					def        _lowerCAmelCase	(			self      :					Optional[int] ,      lowerCAmelCase      :					int					):
											lowercase       :    List[Any]											=  (self.pad_value, self.pad_value)
											lowercase       :    Tuple											=  tf.pad(lowercase_ ,      [(0, 0), height_pad, width_pad, (0, 0)]					)
											lowercase       :    Union[str, Any]											=  self.conv(lowercase_					)
											return hidden_state




					def        _lowerCAmelCase	(			self      :					Tuple ,      lowerCAmelCase      :					Dict ,      lowerCAmelCase      :					List[Any] = False					):
											lowercase       :    Optional[int]											=  self.convolution(lowercase_					)
											lowercase       :    Dict											=  self.normalization(lowercase_ ,      training=lowercase_					)
											lowercase       :    Any											=  self.activation(lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					int ,      lowerCAmelCase      :					Union[str, Any] ,      **lowerCAmelCase      :					Tuple					):
											super().__init__(**lowercase_					)
											lowercase       :    List[Any]											=  TFResNetConvLayer(
											    config.embedding_size ,      kernel_size=7 ,      stride=2 ,      activation=config.hidden_act ,      name='''embedder''' ,      )
											lowercase       :    Any											=  tf.keras.layers.MaxPoolaD(pool_size=3 ,      strides=2 ,      padding='''valid''' ,      name='''pooler'''					)
											lowercase       :    Optional[Any]											=  config.num_channels




					def        _lowerCAmelCase	(			self      :					List[str] ,      lowerCAmelCase      :					List[str] ,      lowerCAmelCase      :					Tuple = False					):
											lowercase       :    List[Any]											=  shape_list(lowercase_					)
											if tf.executing_eagerly() and num_channels != self.num_channels:
																	raise ValueError(
																	    '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''					)
											lowercase       :    Optional[Any]											=  pixel_values
											lowercase       :    Union[str, Any]											=  self.embedder(lowercase_					)
											lowercase       :    str											=  tf.pad(lowercase_ ,      [[0, 0], [1, 1], [1, 1], [0, 0]]					)
											lowercase       :    Dict											=  self.pooler(lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					List[str] ,      lowerCAmelCase      :					Tuple ,      lowerCAmelCase      :					Union[str, Any] = 2 ,      **lowerCAmelCase      :					Union[str, Any]					):
											super().__init__(**lowercase_					)
											lowercase       :    Optional[int]											=  tf.keras.layers.ConvaD(
											    lowercase_ ,      kernel_size=1 ,      strides=lowercase_ ,      use_bias=lowercase_ ,      name='''convolution'''					)
											# Use same default momentum and epsilon as PyTorch equivalent
											lowercase       :    Optional[Any]											=  tf.keras.layers.BatchNormalization(epsilon=1E-5 ,      momentum=0.9 ,      name='''normalization'''					)




					def        _lowerCAmelCase	(			self      :					Tuple ,      lowerCAmelCase      :					Optional[int] ,      lowerCAmelCase      :					List[Any] = False					):
											lowercase       :    Optional[Any]											=  x
											lowercase       :    Any											=  self.convolution(lowercase_					)
											lowercase       :    Optional[int]											=  self.normalization(lowercase_ ,      training=lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					int ,      lowerCAmelCase      :					Union[str, Any] ,      lowerCAmelCase      :					Any ,      lowerCAmelCase      :					List[str] = 1 ,      lowerCAmelCase      :					Optional[Any] = "relu" ,      **lowerCAmelCase      :					Any					):
											super().__init__(**lowercase_					)
											lowercase       :    Union[str, Any]											=  in_channels != out_channels or stride != 1
											lowercase       :    List[str]											=  TFResNetConvLayer(lowercase_ ,      stride=lowercase_ ,      name='''layer.0'''					)
											lowercase       :    str											=  TFResNetConvLayer(lowercase_ ,      activation=lowercase_ ,      name='''layer.1'''					)
											lowercase       :    Tuple											=  (
											    TFResNetShortCut(lowercase_ ,      stride=lowercase_ ,      name='''shortcut'''					)
											    if should_apply_shortcut
											    else tf.keras.layers.Activation('''linear''' ,      name='''shortcut'''					)
											)
											lowercase       :    Tuple											=  ACTaFN[activation]




					def        _lowerCAmelCase	(			self      :					Optional[Any] ,      lowerCAmelCase      :					int ,      lowerCAmelCase      :					Tuple = False					):
											lowercase       :    List[str]											=  hidden_state
											lowercase       :    Tuple											=  self.conva(lowercase_ ,      training=lowercase_					)
											lowercase       :    Optional[Any]											=  self.conva(lowercase_ ,      training=lowercase_					)
											lowercase       :    Dict											=  self.shortcut(lowercase_ ,      training=lowercase_					)
											hidden_state += residual
											lowercase       :    Dict											=  self.activation(lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					str ,      lowerCAmelCase      :					Tuple ,      lowerCAmelCase      :					str ,      lowerCAmelCase      :					Union[str, Any] = 1 ,      lowerCAmelCase      :					Union[str, Any] = "relu" ,      lowerCAmelCase      :					List[Any] = 4 ,      **lowerCAmelCase      :					List[Any] ,      ):
											super().__init__(**lowercase_					)
											lowercase       :    List[str]											=  in_channels != out_channels or stride != 1
											lowercase       :    int											=  out_channels // reduction
											lowercase       :    List[Any]											=  TFResNetConvLayer(lowercase_ ,      kernel_size=1 ,      name='''layer.0'''					)
											lowercase       :    str											=  TFResNetConvLayer(lowercase_ ,      stride=lowercase_ ,      name='''layer.1'''					)
											lowercase       :    Optional[int]											=  TFResNetConvLayer(lowercase_ ,      kernel_size=1 ,      activation=lowercase_ ,      name='''layer.2'''					)
											lowercase       :    Optional[int]											=  (
											    TFResNetShortCut(lowercase_ ,      stride=lowercase_ ,      name='''shortcut'''					)
											    if should_apply_shortcut
											    else tf.keras.layers.Activation('''linear''' ,      name='''shortcut'''					)
											)
											lowercase       :    Union[str, Any]											=  ACTaFN[activation]




					def        _lowerCAmelCase	(			self      :					int ,      lowerCAmelCase      :					Optional[int] ,      lowerCAmelCase      :					List[str] = False					):
											lowercase       :    Any											=  hidden_state
											lowercase       :    Dict											=  self.conva(lowercase_ ,      training=lowercase_					)
											lowercase       :    List[str]											=  self.conva(lowercase_ ,      training=lowercase_					)
											lowercase       :    str											=  self.conva(lowercase_ ,      training=lowercase_					)
											lowercase       :    Dict											=  self.shortcut(lowercase_ ,      training=lowercase_					)
											hidden_state += residual
											lowercase       :    str											=  self.activation(lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					Optional[int] ,      lowerCAmelCase      :					Tuple ,      lowerCAmelCase      :					Tuple ,      lowerCAmelCase      :					Optional[int] ,      lowerCAmelCase      :					Tuple = 2 ,      lowerCAmelCase      :					Tuple = 2 ,      **lowerCAmelCase      :					Dict					):
											super().__init__(**lowercase_					)

											lowercase       :    List[str]											=  TFResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else TFResNetBasicLayer

											lowercase       :    int											=  [layer(lowercase_ ,      lowercase_ ,      stride=lowercase_ ,      activation=config.hidden_act ,      name='''layers.0'''					)]
											layers += [
											    layer(lowercase_ ,      lowercase_ ,      activation=config.hidden_act ,      name=f'''layers.{i + 1}'''					)
											    for i in range(depth - 1					)
											]
											lowercase       :    Tuple											=  layers




					def        _lowerCAmelCase	(			self      :					Tuple ,      lowerCAmelCase      :					Dict ,      lowerCAmelCase      :					int = False					):

											for layer in self.stage_layers:
																	lowercase       :    List[Any]											=  layer(lowercase_ ,      training=lowercase_					)
											return hidden_state







class 							UpperCAmelCase	(   tf.keras.layers.Layer					):

					def __init__(			self      :					str ,      lowerCAmelCase      :					Tuple ,      **lowerCAmelCase      :					str					):
											super().__init__(**lowercase_					)
											# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
											lowercase       :    Any											=  [
											    TFResNetStage(
											        lowercase_ ,      config.embedding_size ,      config.hidden_sizes[0] ,      stride=2 if config.downsample_in_first_stage else 1 ,      depth=config.depths[0] ,      name='''stages.0''' ,      )
											]
											for i, (in_channels, out_channels, depth) in enumerate(
											    zip(config.hidden_sizes ,      config.hidden_sizes[1:] ,      config.depths[1:]					)					):
																	self.stages.append(TFResNetStage(lowercase_ ,      lowercase_ ,      lowercase_ ,      depth=lowercase_ ,      name=f'''stages.{i + 1}'''					)					)




					def        _lowerCAmelCase	(			self      :					Any ,      lowerCAmelCase      :					Optional[int] ,      lowerCAmelCase      :					Any = False ,      lowerCAmelCase      :					Optional[int] = True ,      lowerCAmelCase      :					List[str] = False ,      ):
											lowercase       :    Any											=  () if output_hidden_states else None

											for stage_module in self.stages:
																	if output_hidden_states:
																							lowercase       :    Optional[int]											=  hidden_states + (hidden_state,)

																	lowercase       :    Dict											=  stage_module(lowercase_ ,      training=lowercase_					)

											if output_hidden_states:
																	lowercase       :    Tuple											=  hidden_states + (hidden_state,)

											if not return_dict:
																	return tuple(v for v in [hidden_state, hidden_states] if v is not None					)

											return TFBaseModelOutputWithNoAttention(last_hidden_state=lowercase_ ,      hidden_states=lowercase_					)







class 							UpperCAmelCase	(   __UpperCAmelCase					):
					a__: List[str]			  =				ResNetConfig
					a__: Union[str, Any]			  =				"""resnet"""
					a__: Optional[int]			  =				"""pixel_values"""

					@property
					def        _lowerCAmelCase	(			self      :					Optional[Any]					):
											return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) ,      dtype=tf.floataa					)}





snake_case__  							=							R"""\n    This model is a TensorFlow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n"""


snake_case__  							=							R"""\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"""







@keras_serializable
class 							UpperCAmelCase	(   tf.keras.layers.Layer					):
					a__: List[Any]			  =				ResNetConfig

					def __init__(			self      :					Dict ,      lowerCAmelCase      :					str ,      **lowerCAmelCase      :					List[Any]					):
											super().__init__(**lowercase_					)
											lowercase       :    Optional[int]											=  config
											lowercase       :    int											=  TFResNetEmbeddings(lowercase_ ,      name='''embedder'''					)
											lowercase       :    Union[str, Any]											=  TFResNetEncoder(lowercase_ ,      name='''encoder'''					)
											lowercase       :    str											=  tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowercase_					)




					@unpack_inputs
					def        _lowerCAmelCase	(			self      :					Dict ,      lowerCAmelCase      :					List[str] ,      lowerCAmelCase      :					Any = None ,      lowerCAmelCase      :					Tuple = None ,      lowerCAmelCase      :					Union[str, Any] = False ,      ):
											lowercase       :    Optional[Any]											=  (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowercase       :    str											=  return_dict if return_dict is not None else self.config.use_return_dict

											# TF 2.0 image layers can't use NCHW format when running on CPU.
											# We transpose to NHWC format and then transpose back after the full forward pass.
											# (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
											lowercase       :    List[Any]											=  tf.transpose(lowercase_ ,      perm=[0, 2, 3, 1]					)
											lowercase       :    Optional[Any]											=  self.embedder(lowercase_ ,      training=lowercase_					)

											lowercase       :    int											=  self.encoder(
											    lowercase_ ,      output_hidden_states=lowercase_ ,      return_dict=lowercase_ ,      training=lowercase_					)

											lowercase       :    Union[str, Any]											=  encoder_outputs[0]

											lowercase       :    str											=  self.pooler(lowercase_					)

											# Transpose all the outputs to the NCHW format
											# (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
											lowercase       :    Optional[Any]											=  tf.transpose(lowercase_ ,      (0, 3, 1, 2)					)
											lowercase       :    Tuple											=  tf.transpose(lowercase_ ,      (0, 3, 1, 2)					)
											lowercase       :    Dict											=  ()
											for hidden_state in encoder_outputs[1:]:
																	lowercase       :    Any											=  hidden_states + tuple(tf.transpose(lowercase_ ,      (0, 3, 1, 2)					) for h in hidden_state					)

											if not return_dict:
																	return (last_hidden_state, pooled_output) + hidden_states

											lowercase       :    Tuple											=  hidden_states if output_hidden_states else None

											return TFBaseModelOutputWithPoolingAndNoAttention(
											    last_hidden_state=lowercase_ ,      pooler_output=lowercase_ ,      hidden_states=lowercase_ ,      )







@add_start_docstrings(
    """The bare ResNet model outputting raw features without any specific head on top."""						, __UpperCAmelCase						, )
class 							UpperCAmelCase	(   __UpperCAmelCase					):

					def __init__(			self      :					List[str] ,      lowerCAmelCase      :					int ,      **lowerCAmelCase      :					Tuple					):
											super().__init__(lowercase_ ,      **lowercase_					)
											lowercase       :    str											=  TFResNetMainLayer(config=lowercase_ ,      name='''resnet'''					)




					@add_start_docstrings_to_model_forward(lowercase_					)
					@add_code_sample_docstrings(
					    checkpoint=_CHECKPOINT_FOR_DOC ,      output_type=lowercase_ ,      config_class=_CONFIG_FOR_DOC ,      modality='''vision''' ,      expected_output=_EXPECTED_OUTPUT_SHAPE ,      )
					@unpack_inputs
					def        _lowerCAmelCase	(			self      :					Dict ,      lowerCAmelCase      :					Union[str, Any] ,      lowerCAmelCase      :					Optional[int] = None ,      lowerCAmelCase      :					List[str] = None ,      lowerCAmelCase      :					Dict = False ,      ):
											lowercase       :    Dict											=  (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowercase       :    List[Any]											=  return_dict if return_dict is not None else self.config.use_return_dict

											lowercase       :    Union[str, Any]											=  self.resnet(
											    pixel_values=lowercase_ ,      output_hidden_states=lowercase_ ,      return_dict=lowercase_ ,      training=lowercase_ ,      )
											return resnet_outputs







@add_start_docstrings(
    """
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """						, __UpperCAmelCase						, )
class 							UpperCAmelCase	(   __UpperCAmelCase						, __UpperCAmelCase					):

					def __init__(			self      :					Optional[Any] ,      lowerCAmelCase      :					Any ,      **lowerCAmelCase      :					Optional[Any]					):
											super().__init__(lowercase_ ,      **lowercase_					)
											lowercase       :    Optional[int]											=  config.num_labels
											lowercase       :    Optional[Any]											=  TFResNetMainLayer(lowercase_ ,      name='''resnet'''					)
											# classification head
											lowercase       :    Dict											=  (
											    tf.keras.layers.Dense(config.num_labels ,      name='''classifier.1'''					)
											    if config.num_labels > 0
											    else tf.keras.layers.Activation('''linear''' ,      name='''classifier.1'''					)
											)

					def        _lowerCAmelCase	(			self      :					Tuple ,      lowerCAmelCase      :					Tuple					):
											lowercase       :    Tuple											=  tf.keras.layers.Flatten()(lowercase_					)
											lowercase       :    int											=  self.classifier_layer(lowercase_					)
											return logits




					@add_start_docstrings_to_model_forward(lowercase_					)
					@add_code_sample_docstrings(
					    checkpoint=_IMAGE_CLASS_CHECKPOINT ,      output_type=lowercase_ ,      config_class=_CONFIG_FOR_DOC ,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,      )
					@unpack_inputs
					def        _lowerCAmelCase	(			self      :					List[str] ,      lowerCAmelCase      :					Dict = None ,      lowerCAmelCase      :					Tuple = None ,      lowerCAmelCase      :					Union[str, Any] = None ,      lowerCAmelCase      :					str = None ,      lowerCAmelCase      :					Tuple = False ,      ):
											lowercase       :    Any											=  return_dict if return_dict is not None else self.config.use_return_dict

											lowercase       :    Tuple											=  self.resnet(
											    lowercase_ ,      output_hidden_states=lowercase_ ,      return_dict=lowercase_ ,      training=lowercase_					)

											lowercase       :    Tuple											=  outputs.pooler_output if return_dict else outputs[1]

											lowercase       :    List[str]											=  self.classifier(lowercase_					)

											lowercase       :    Tuple											=  None if labels is None else self.hf_compute_loss(lowercase_ ,      lowercase_					)

											if not return_dict:
																	lowercase       :    Optional[int]											=  (logits,) + outputs[2:]
																	return (loss,) + output if loss is not None else output

											return TFImageClassifierOutputWithNoAttention(loss=lowercase_ ,      logits=lowercase_ ,      hidden_states=outputs.hidden_states					)




import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig

def        lowerCamelCase_      (			UpperCAmelCase_							:				List[str]							,			UpperCAmelCase_							:				Optional[Any]							,			UpperCAmelCase_							:				int=0       ):
						# Format the message.
						if name is None:
												lowercase       :    List[str]											=  None
						else:
												lowercase       :    str											=  '''.''' * max(0							,			spaces - 2       ) + '''# {:''' + str(50 - spaces       ) + '''s}'''
												lowercase       :    List[str]											=  fmt.format(UpperCAmelCase_       )

						# Print and recurse (if needed).
						if isinstance(UpperCAmelCase_							,			UpperCAmelCase_       ):
												if msg is not None:
																		print(UpperCAmelCase_       )
												for k in val.keys():
																		recursive_print(UpperCAmelCase_							,			val[k]							,			spaces + 2       )
						elif isinstance(UpperCAmelCase_							,			torch.Tensor       ):
												print(UpperCAmelCase_							,			''':'''							,			val.size()       )
						else:
												print(UpperCAmelCase_							,			''':'''							,			UpperCAmelCase_       )

def        lowerCamelCase_      (			UpperCAmelCase_							:				Dict							,			UpperCAmelCase_							:				Dict							,			UpperCAmelCase_							:				Tuple							,			UpperCAmelCase_							:				Tuple       ):
						# Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :]
						# for compatibility with later versions of NVIDIA Megatron-LM.
						# The inverse operation is performed inside Megatron-LM to read checkpoints:
						# https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
						# If param is the weight tensor of the self-attention block, the returned tensor
						# will have to be transposed one more time to be read by HuggingFace GPT2.
						lowercase       :    Optional[Any]											=  param.size()
						# other versions store [num_heads * num_splits * hidden_size, :]
						lowercase       :    Any											=  (num_heads, num_splits, hidden_size) + input_shape[1:]
						lowercase       :    Optional[int]											=  param.view(*UpperCAmelCase_       )
						lowercase       :    List[Any]											=  param.transpose(0							,			1       ).contiguous()
						lowercase       :    int											=  param.view(*UpperCAmelCase_       )
						return param

def        lowerCamelCase_      (			UpperCAmelCase_							:				List[str]							,			UpperCAmelCase_							:				Union[str, Any]       ):
						lowercase       :    str											=  config.n_positions
						lowercase       :    Union[str, Any]											=  config.n_layer
						lowercase       :    Optional[int]											=  config.vocab_size
						lowercase       :    Union[str, Any]											=  config.n_head
						lowercase       :    int											=  config.n_embd // config.n_head

						lowercase       :    Optional[Any]											=  sd_megatron['''model.language_model.embedding.word_embeddings.weight'''][:vocab_size, :]
						lowercase       :    Optional[int]											=  {
						    '''transformer.wte.weight''': word_embeddings,
						    '''transformer.wpe.weight''': sd_megatron['''model.language_model.embedding.position_embeddings.weight'''],
						    '''transformer.ln_f.weight''': sd_megatron['''model.language_model.encoder.final_layernorm.weight'''],
						    '''transformer.ln_f.bias''': sd_megatron['''model.language_model.encoder.final_layernorm.bias'''],
						}

						lowercase       :    Dict											=  '''model.language_model.encoder.layers.'''
						for i in range(UpperCAmelCase_       ):
												lowercase       :    List[str]											=  torch.tril(torch.ones((n_positions, n_positions)							,			dtype=torch.bool       )       )
												lowercase       :    List[str]											=  causal_mask.view(1							,			1							,			UpperCAmelCase_							,			UpperCAmelCase_       )
												lowercase       :    List[str]											=  causal_mask
												lowercase       :    Optional[int]											=  torch.tensor(-1E4							,			dtype=torch.bfloataa       )

												lowercase       :    List[str]											=  sd_megatron[f'''{pf}{i}.input_layernorm.weight''']
												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.input_layernorm.bias''']

												lowercase       :    Any											=  sd_megatron[f'''{pf}{i}.self_attention.query_key_value.weight''']
												lowercase       :    Optional[int]											=  fix_query_key_value_ordering(UpperCAmelCase_							,			3							,			UpperCAmelCase_							,			UpperCAmelCase_       )
												lowercase       :    Tuple											=  vala.transpose(0							,			1       ).contiguous()

												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.self_attention.query_key_value.bias''']
												lowercase       :    Any											=  fix_query_key_value_ordering(UpperCAmelCase_							,			3							,			UpperCAmelCase_							,			UpperCAmelCase_       )
												lowercase       :    int											=  vala

												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.self_attention.dense.weight'''].transpose(
												    0							,			1       )
												lowercase       :    Optional[int]											=  sd_megatron[f'''{pf}{i}.self_attention.dense.bias''']
												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.post_attention_layernorm.weight''']
												lowercase       :    Union[str, Any]											=  sd_megatron[f'''{pf}{i}.post_attention_layernorm.bias''']
												lowercase       :    Optional[Any]											=  sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.weight'''].transpose(0							,			1       )
												lowercase       :    List[Any]											=  sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.bias''']
												lowercase       :    Dict											=  sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.weight'''].transpose(
												    0							,			1       )
												lowercase       :    str											=  sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.bias''']

						# For LM head, transformers' wants the matrix to weight embeddings.
						lowercase       :    int											=  word_embeddings

						return sd_hf

def        lowerCamelCase_      (			UpperCAmelCase_							:				str							,			UpperCAmelCase_							:				str       ):
						lowercase       :    str											=  6_40_00
						lowercase       :    Union[str, Any]											=  config_megatron['''encoder_seq_length''']
						lowercase       :    Union[str, Any]											=  config_megatron['''hidden_size''']
						lowercase       :    Optional[Any]											=  config_megatron['''num_layers''']
						lowercase       :    int											=  config_megatron['''num_attention_heads''']
						lowercase       :    str											=  config_megatron['''ffn_hidden_size''']
						lowercase       :    Union[str, Any]											=  '''gelu'''
						lowercase       :    Tuple											=  0.1
						lowercase       :    str											=  0.1
						lowercase       :    str											=  0.1
						lowercase       :    Dict											=  config_megatron['''layernorm_epsilon''']  # 1e-5
						lowercase       :    str											=  config_megatron['''init_method_std''']  # 0.02
						lowercase       :    Optional[int]											=  config_megatron['''apply_query_key_layer_scaling''']  # True
						lowercase       :    Union[str, Any]											=  True
						lowercase       :    int											=  True

						# This identifies the 6.7B (7B) model which uses a different tokenizer
						if config_megatron["hidden_size"] == 40_96:
												lowercase       :    Dict											=  1  # <|endoftext|>
												lowercase       :    str											=  1  # <|endoftext|>
												lowercase       :    Dict											=  0  # <unk>
						else:
												lowercase       :    List[Any]											=  2  # <s>
												lowercase       :    List[str]											=  3  # <|endoftext|>
												lowercase       :    Optional[Any]											=  0  # <pad>

						return config_hf

def        lowerCamelCase_      (			UpperCAmelCase_							:				Tuple       ):
						print(UpperCAmelCase_       )

						lowercase       :    List[Any]											=  args.checkpoint_path
						lowercase       :    Dict											=  args.save_path
						if isfile(UpperCAmelCase_       ):
												raise FileNotFoundError(f'''ERROR! could not find file {checkpoint_path}'''       )

						# Load the model.
						lowercase       :    Optional[int]											=  torch.load(UpperCAmelCase_							,			map_location='''cpu'''       )

						# Load the config.
						lowercase       :    Any											=  checkpoint['''hyper_parameters''']['''cfg''']
						lowercase       :    Dict											=  GPTaConfig()
						lowercase       :    Dict											=  copy_config(config_hf=UpperCAmelCase_							,			config_megatron=UpperCAmelCase_       )
						lowercase       :    Any											=  ['''GPT2LMHeadModel''']

						lowercase       :    List[Any]											=  checkpoint['''state_dict''']

						# Convert.
						print('''Converting'''       )
						lowercase       :    Dict											=  convert_megatron_checkpoint(UpperCAmelCase_							,			UpperCAmelCase_       )

						# Print the structure of converted state dict.
						if args.print_checkpoint_structure:
												recursive_print(UpperCAmelCase_							,			UpperCAmelCase_       )

						lowercase       :    List[Any]											=  '''GPTSw3Tokenizer'''

						# Store the config to file.
						print('''Saving config'''       )
						config_hf.save_pretrained(UpperCAmelCase_       )

						# Store the state_dict to file.
						lowercase       :    Union[str, Any]											=  os.path.join(UpperCAmelCase_							,			'''pytorch_model.bin'''       )
						print(f'''Saving checkpoint to "{output_checkpoint_file}"'''       )
						torch.save(UpperCAmelCase_							,			UpperCAmelCase_       )


if __name__ == "__main__":
				snake_case__  							=							argparse.ArgumentParser()
				parser.add_argument(
				    """--checkpoint_path""",
				    type=str,
				    required=True,
				    help="""e.g. megatron_gpt--val_loss=2.42-step=38000-consumed_samples=54720000""",
				)
				parser.add_argument("""--save_path""", type=str, required=True, help="""e.g. /home/user/gpt-sw3/hf""")
				parser.add_argument("""--print-checkpoint-structure""", action="""store_true""")
				snake_case__  							=							parser.parse_args()
				main(_args)


