# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

####################################################################################################

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig


def       a__      (					a  ,   a  ,   a=0							)		->	List[Any]:
       # Format the message.
       if name is None:
              A_							:       Optional[Any]	      =				None
       else:
              A_							:       str	      =				'''.''' * max(0  ,   spaces - 2							) + '''# {:''' + str(5_0 - spaces							) + '''s}'''
              A_							:       str	      =				fmt.format(a							)

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


def       a__      (					a  ,   a  ,   a  ,   a  ,   a							)		->	Dict:
       # 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 BERT.
       A_							:       Union[str, Any]	      =				param.size()
       if checkpoint_version == 1.0:
              # version 1.0 stores [num_heads * hidden_size * num_splits, :]
              A_							:       Dict	      =				(num_heads, hidden_size, num_splits) + input_shape[1:]
              A_							:       Tuple	      =				param.view(*a							)
              A_							:       Union[str, Any]	      =				param.transpose(0  ,   2							)
              A_							:       List[Any]	      =				param.transpose(1  ,   2							).contiguous()
       elif checkpoint_version >= 2.0:
              # other versions store [num_heads * num_splits * hidden_size, :]
              A_							:       List[Any]	      =				(num_heads, num_splits, hidden_size) + input_shape[1:]
              A_							:       str	      =				param.view(*a							)
              A_							:       Dict	      =				param.transpose(0  ,   1							).contiguous()
       A_							:       List[str]	      =				param.view(*a							)
       return param


def       a__      (					a  ,   a  ,   a							)		->	int:
       # The converted output model.
       A_							:       Optional[int]	      =				{}

       # old versions did not store training args
       A_							:       List[str]	      =				input_state_dict.get('''args'''  ,   a							)
       if ds_args is not None:
              # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
              # from pprint import pprint
              # pprint(vars(ds_args))

              A_							:       Union[str, Any]	      =				ds_args.tokenizer_type
              A_							:       Tuple	      =				ds_args.padded_vocab_size
              A_							:       Tuple	      =				ds_args.max_position_embeddings
              A_							:       Any	      =				ds_args.hidden_size
              A_							:       List[str]	      =				ds_args.num_layers
              A_							:       str	      =				ds_args.num_attention_heads
              A_							:       Tuple	      =				ds_args.ffn_hidden_size if '''ffn_hidden_size''' in ds_args else 4 * ds_args.hidden_size
              # pprint(config)

       # The number of heads.
       A_							:       Optional[int]	      =				config.num_attention_heads
       # The hidden_size per head.
       A_							:       List[str]	      =				config.hidden_size // heads
       # Megatron-LM checkpoint version
       if "checkpoint_version" in input_state_dict.keys():
              A_							:       List[str]	      =				input_state_dict['''checkpoint_version''']
       else:
              A_							:       Tuple	      =				0.0

       # The model.
       A_							:       List[Any]	      =				input_state_dict['''model''']
       # The language model.
       A_							:       Union[str, Any]	      =				model['''language_model''']
       # The embeddings.
       A_							:       Any	      =				lm['''embedding''']

       # The word embeddings.
       A_							:       int	      =				embeddings['''word_embeddings''']['''weight''']
       # Truncate the embedding table to vocab_size rows.
       A_							:       Tuple	      =				word_embeddings[: config.vocab_size, :]
       # Store the word embeddings.
       A_							:       Dict	      =				word_embeddings

       # The position embeddings.
       A_							:       Dict	      =				embeddings['''position_embeddings''']['''weight''']
       assert pos_embeddings.size(0							) == config.max_position_embeddings and pos_embeddings.size(1							) == config.hidden_size
       # Store the position embeddings.
       A_							:       Dict	      =				pos_embeddings

       # The token-type embeddings.
       A_							:       List[str]	      =				embeddings['''tokentype_embeddings''']['''weight''']
       # Store the position embeddings.
       A_							:       Any	      =				tokentype_embeddings

       # The transformer.
       A_							:       int	      =				lm['''transformer'''] if '''transformer''' in lm.keys() else lm['''encoder''']

       # The regex to extract layer names.
       A_							:       List[str]	      =				re.compile(R'''layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)'''							)

       # The simple map of names for "automated" rules.
       A_							:       List[Any]	      =				{
           '''attention.dense''': '''.attention.output.dense.''',
           '''self_attention.dense''': '''.attention.output.dense.''',
           '''mlp.dense_h_to_4h''': '''.intermediate.dense.''',
           '''mlp.dense_4h_to_h''': '''.output.dense.''',
       }

       # Keep track of the attention/query/value tensor.
       A_							:       Optional[Any]	      =				None

       # Extract the layers.
       for key, val in transformer.items():
              # Match the name.
              A_							:       Any	      =				layer_re.match(a							)

              # Stop if that's not a layer
              if m is None:
                     break

              # The index of the layer.
              A_							:       List[Any]	      =				int(m.group(1							)							)
              # The name of the operation.
              A_							:       Tuple	      =				m.group(2							)
              # Is it a weight or a bias?
              A_							:       Union[str, Any]	      =				m.group(3							)

              # The name of the layer.
              A_							:       Dict	      =				f"""bert.encoder.layer.{layer_idx}"""

              # For layernorm(s), simply store the layer norm.
              if op_name.endswith('''layernorm'''							):
                     A_							:       List[Any]	      =				'''attention.ln''' if op_name.startswith('''input'''							) else '''ln'''
                     A_							:       Optional[int]	      =				val

              # Transpose the QKV matrix.
              elif (
                  op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
              ) and weight_or_bias == "weight":
                     # Make sure the QKV pointer is nil.
                     assert attention_qkv_weight is None, ""

                     A_							:       Optional[int]	      =				fix_query_key_value_ordering(a  ,   a  ,   3  ,   a  ,   a							)
                     # Store the tensor as we need the bias as well to interleave QKV and biases.
                     A_							:       Optional[int]	      =				out_val

              # Transpose the bias.
              elif (
                  op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
              ) and weight_or_bias == "bias":
                     # Make sure we read the weight tensor.
                     assert attention_qkv_weight is not None, ""

                     # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
                     A_							:       List[Any]	      =				attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
                     A_							:       Optional[Any]	      =				attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
                     A_							:       Any	      =				attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

                     A_							:       int	      =				fix_query_key_value_ordering(a  ,   a  ,   3  ,   a  ,   a							)
                     # Split the bias.
                     A_							:       Dict	      =				out_val[0 * config.hidden_size : 1 * config.hidden_size]
                     A_							:       List[str]	      =				out_val[1 * config.hidden_size : 2 * config.hidden_size]
                     A_							:       Union[str, Any]	      =				out_val[2 * config.hidden_size : 3 * config.hidden_size]

                     # Store.
                     A_							:       Dict	      =				q
                     A_							:       Dict	      =				q_bias
                     A_							:       str	      =				k
                     A_							:       Tuple	      =				k_bias
                     A_							:       List[Any]	      =				v
                     A_							:       List[str]	      =				v_bias

                     # Clear the stored tensor.
                     A_							:       List[Any]	      =				None

              # Copy weights and biases as is.
              elif weight_or_bias in ["weight", "bias"]:
                     A_							:       List[str]	      =				megatron_to_transformers[op_name]
                     A_							:       Dict	      =				val

    # The final layernorm.
       A_							:       List[Any]	      =				transformer['''final_layernorm.weight''']
       A_							:       Any	      =				transformer['''final_layernorm.bias''']

       # The pooler.
       A_							:       Dict	      =				lm['''pooler''']

       # Store the matrix and the bias.
       A_							:       Dict	      =				pooler['''dense.weight''']
       A_							:       Any	      =				pooler['''dense.bias''']

       # The LM head from Megatron (for RACE).
       A_							:       Dict	      =				model['''lm_head''']

       # The transform matrix.
       A_							:       Optional[Any]	      =				lm_head['''dense.weight''']
       A_							:       Dict	      =				lm_head['''dense.bias''']

       # The transform LN.
       A_							:       Tuple	      =				lm_head['''layernorm.weight''']
       A_							:       int	      =				lm_head['''layernorm.bias''']

       # For the decoder, we replicate the weights.
       A_							:       str	      =				word_embeddings
       A_							:       List[str]	      =				lm_head['''bias''']

       # The classifier from Megatron (for MLNI).
       A_							:       List[str]	      =				model['''binary_head''']

       # Store the classifier.
       A_							:       List[Any]	      =				binary_head['''weight''']
       A_							:       int	      =				binary_head['''bias''']

       # It should be done!
       return output_state_dict


def       a__      (					)		->	List[Any]:
       # Create the argument parser.
       A_							:       List[Any]	      =				argparse.ArgumentParser()
       parser.add_argument('''--print-checkpoint-structure'''  ,   action='''store_true'''							)
       parser.add_argument('''path_to_checkpoint'''  ,   type=a  ,   help='''Path to the ZIP file containing the checkpoint'''							)
       parser.add_argument(
           '''--config_file'''  ,   default=''''''  ,   type=a  ,   help='''An optional config json file describing the pre-trained model.'''  ,   )
       A_							:       Optional[int]	      =				parser.parse_args()

       # Extract the basename.
       A_							:       Dict	      =				os.path.dirname(args.path_to_checkpoint							)

       # Load the model.
       # the .zip is very optional, let's keep it for backward compatibility
       print(f"""Extracting PyTorch state dictionary from \"{args.path_to_checkpoint}\""""							)
       if args.path_to_checkpoint.endswith('''.zip'''							):
              with zipfile.ZipFile(args.path_to_checkpoint  ,   '''r'''							) as checkpoint:
                     with checkpoint.open('''release/mp_rank_00/model_optim_rng.pt'''							) as pytorch_dict:
                            A_							:       Tuple	      =				torch.load(a  ,   map_location='''cpu'''							)
       else:
              A_							:       Tuple	      =				torch.load(args.path_to_checkpoint  ,   map_location='''cpu'''							)

       if args.config_file == "":
              # Default config of megatron-bert 345m
              A_							:       List[str]	      =				MegatronBertConfig()

              # different megatron-bert-*-345m models have different vocab sizes, so override the default
              # config (which is for megatron-bert-cased-345m) with the actual vocab dimension
              A_							:       Tuple	      =				input_state_dict['''model''']['''lm_head''']['''bias'''].numel()
       else:
              A_							:       str	      =				MegatronBertConfig.from_json_file(args.config_file							)

       # Convert.
       print('''Converting'''							)
       A_							:       str	      =				convert_megatron_checkpoint(a  ,   a  ,   a							)

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

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

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


####################################################################################################

if __name__ == "__main__":
    main()

####################################################################################################



import gym
import numpy as np
import torch
from mujoco_py import GlfwContext

from transformers import DecisionTransformerModel


GlfwContext(offscreen=True)  # Create a window to init GLFW.


def       a__      (					a  ,   a  ,   a  ,   a  ,   a  ,   a							)		->	int:
       # we don't care about the past rewards in this model

       A_							:       Dict	      =				states.reshape(1  ,   -1  ,   model.config.state_dim							)
       A_							:       Dict	      =				actions.reshape(1  ,   -1  ,   model.config.act_dim							)
       A_							:       Dict	      =				returns_to_go.reshape(1  ,   -1  ,   1							)
       A_							:       Tuple	      =				timesteps.reshape(1  ,   -1							)

       if model.config.max_length is not None:
              A_							:       int	      =				states[:, -model.config.max_length :]
              A_							:       Optional[int]	      =				actions[:, -model.config.max_length :]
              A_							:       Any	      =				returns_to_go[:, -model.config.max_length :]
              A_							:       Tuple	      =				timesteps[:, -model.config.max_length :]

              # pad all tokens to sequence length
              A_							:       Optional[Any]	      =				torch.cat(
                  [torch.zeros(model.config.max_length - states.shape[1]							), torch.ones(states.shape[1]							)]							)
              A_							:       Optional[Any]	      =				attention_mask.to(dtype=torch.long  ,   device=states.device							).reshape(1  ,   -1							)
              A_							:       Union[str, Any]	      =				torch.cat(
                  [
                      torch.zeros(
                          (states.shape[0], model.config.max_length - states.shape[1], model.config.state_dim)  ,   device=states.device  ,   ),
                      states,
                  ]  ,   dim=1  ,   ).to(dtype=torch.floataa							)
              A_							:       Optional[Any]	      =				torch.cat(
                  [
                      torch.zeros(
                          (actions.shape[0], model.config.max_length - actions.shape[1], model.config.act_dim)  ,   device=actions.device  ,   ),
                      actions,
                  ]  ,   dim=1  ,   ).to(dtype=torch.floataa							)
              A_							:       Optional[Any]	      =				torch.cat(
                  [
                      torch.zeros(
                          (returns_to_go.shape[0], model.config.max_length - returns_to_go.shape[1], 1)  ,   device=returns_to_go.device  ,   ),
                      returns_to_go,
                  ]  ,   dim=1  ,   ).to(dtype=torch.floataa							)
              A_							:       List[str]	      =				torch.cat(
                  [
                      torch.zeros(
                          (timesteps.shape[0], model.config.max_length - timesteps.shape[1])  ,   device=timesteps.device							),
                      timesteps,
                  ]  ,   dim=1  ,   ).to(dtype=torch.long							)
       else:
              A_							:       str	      =				None

       A_      ,							A_      ,							A_							:       List[str]	      =				model(
           states=a  ,   actions=a  ,   rewards=a  ,   returns_to_go=a  ,   timesteps=a  ,   attention_mask=a  ,   return_dict=a  ,   )

       return action_preds[0, -1]


# build the environment

_lowerCAmelCase        =       gym.make('Hopper-v3')
_lowerCAmelCase        =       env.observation_space.shape[0]
_lowerCAmelCase        =       env.action_space.shape[0]
_lowerCAmelCase        =       1_0_0_0
_lowerCAmelCase        =       'cuda'
_lowerCAmelCase        =       1000.0  # normalization for rewards/returns
_lowerCAmelCase        =       3_6_0_0 / scale  # evaluation conditioning targets, 3600 is reasonable from the paper LINK
_lowerCAmelCase        =       np.array(
    [
        1.31_1279,
        -0.0846_9521,
        -0.538_2719,
        -0.0720_1576,
        0.0493_2366,
        2.106_6856,
        -0.1501_7354,
        0.0087_8345,
        -0.284_8186,
        -0.1854_0096,
        -0.2846_1286,
    ]
)
_lowerCAmelCase        =       np.array(
    [
        0.1779_0751,
        0.0544_4621,
        0.2129_7139,
        0.1453_0419,
        0.612_4444,
        0.8517_4465,
        1.451_5252,
        0.675_1696,
        1.53_6239,
        1.616_0746,
        5.607_2536,
    ]
)
_lowerCAmelCase        =       torch.from_numpy(state_mean).to(device=device)
_lowerCAmelCase        =       torch.from_numpy(state_std).to(device=device)

# Create the decision transformer model
_lowerCAmelCase        =       DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-medium')
_lowerCAmelCase        =       model.to(device)
model.eval()

for ep in range(1_0):
    _lowerCAmelCase  ,			_lowerCAmelCase        =       0, 0
    _lowerCAmelCase        =       env.reset()
    _lowerCAmelCase        =       torch.tensor(TARGET_RETURN, device=device, dtype=torch.floataa).reshape(1, 1)
    _lowerCAmelCase        =       torch.from_numpy(state).reshape(1, state_dim).to(device=device, dtype=torch.floataa)
    _lowerCAmelCase        =       torch.zeros((0, act_dim), device=device, dtype=torch.floataa)
    _lowerCAmelCase        =       torch.zeros(0, device=device, dtype=torch.floataa)

    _lowerCAmelCase        =       torch.tensor(0, device=device, dtype=torch.long).reshape(1, 1)
    for t in range(max_ep_len):
        env.render()
        # add padding
        _lowerCAmelCase        =       torch.cat([actions, torch.zeros((1, act_dim), device=device)], dim=0)
        _lowerCAmelCase        =       torch.cat([rewards, torch.zeros(1, device=device)])

        _lowerCAmelCase        =       get_action(
            model,
            (states.to(dtype=torch.floataa) - state_mean) / state_std,
            actions.to(dtype=torch.floataa),
            rewards.to(dtype=torch.floataa),
            target_return.to(dtype=torch.floataa),
            timesteps.to(dtype=torch.long),
        )
        _lowerCAmelCase        =       action
        _lowerCAmelCase        =       action.detach().cpu().numpy()

        _lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase        =       env.step(action)

        _lowerCAmelCase        =       torch.from_numpy(state).to(device=device).reshape(1, state_dim)
        _lowerCAmelCase        =       torch.cat([states, cur_state], dim=0)
        _lowerCAmelCase        =       reward

        _lowerCAmelCase        =       target_return[0, -1] - (reward / scale)
        _lowerCAmelCase        =       torch.cat([target_return, pred_return.reshape(1, 1)], dim=1)
        _lowerCAmelCase        =       torch.cat([timesteps, torch.ones((1, 1), device=device, dtype=torch.long) * (t + 1)], dim=1)

        episode_return += reward
        episode_length += 1

        if done:
            break


