# https://github.com/kzl/decision-transformer

"""
The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

"""
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
    - each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
    - all blocks feed into a central residual pathway similar to resnets
- the final decoder is a linear projection into a vanilla Softmax classifier
"""

import torch
import torch.nn as nn
from torch.nn import functional as F

from utils import misc, logs_handler

from models import SwinTransformer3D, GPT2
from models.modules import SequenceEmbedding
from learn import losses

logger = logs_handler.get_logger(__name__)

class TokensEmbeddings(nn.Module):
    def __init__(self, num_tokens, dim, discrete):
        super(TokensEmbeddings, self).__init__()
        self.num_tokens = num_tokens
        self.dim = dim
        self.discrete = discrete        
        if discrete:
            num_tokens += 1
        self.embeddings =\
            nn.Sequential(SequenceEmbedding(num_tokens, dim, discrete), 
                                            nn.Tanh())
                    
    def forward(self, tokens):
        tokens_embeds = self.embeddings(tokens)
        return tokens_embeds

class StateEncoder(nn.Module): 

    def __init__(self, encoder_type, embed_dim=96, num_channels=1, temporal_window=4, spatial_window=(7, 7), temporal_patches=4, 
                 patch_size=(4, 4), pool_size=(None, 1, 1), num_heads=None, depths=None, qkv_bias=True, drop_path_rate=0.1, causal=False):
        super(StateEncoder, self).__init__()
        assert encoder_type in {'conv', 'transformer'}, '...'
        self.encoder_type = encoder_type
        
        patch_size = (temporal_patches, *patch_size)
        window_size = (temporal_window, *spatial_window)
        self.state_dim = None
        self.encoder = None
        if self.encoder_type == 'transformer':
            self.encoder =\
                SwinTransformer3D(patch_size=patch_size,
                                  window_size=window_size,
                                  embed_dim=embed_dim,
                                  num_heads=num_heads,
                                  depths=depths,
                                  num_channels=num_channels,
                                  drop_path_rate=drop_path_rate,
                                  qkv_bias=qkv_bias,
                                  pool_size=pool_size,
                                  causal=causal)
                        
            logger.info(f'StateEncoder > swin/embed_dim: {embed_dim}')
            self.state_dim = self.encoder.out_features

        elif self.encoder_type == 'conv':
            self.encoder = nn.Sequential(nn.Conv2d(4, 32, 8, stride=4, padding=0), nn.ReLU(),
                                 nn.Conv2d(32, 64, 4, stride=2, padding=0), nn.ReLU(),
                                 nn.Conv2d(64, 64, 3, stride=1, padding=0), nn.ReLU(),
                                 nn.Flatten(), nn.Linear(3136, embed_dim), nn.Tanh())          
            self.state_dim = embed_dim
        
        logger.info(f'StateEncoder > state_dim: {self.state_dim}')
                
    def forward(self, states):
        if self.encoder_type == 'transformer':
            return self.encoder(states).get('outputs')
        else:
            return self.encoder(states)

class GELU(nn.Module):
    def forward(self, input):
        return F.gelu(input)

class DTConfig:
    """ base GPT config, params common to all GPT versions """
    embd_pdrop = 0.1
    resid_pdrop = 0.1
    attn_pdrop = 0.1
    
    def __init__(self, vocab_size, block_size, state_encoder_cfg, num_channels, 
                 state_encoder_type='conv', **kwargs):
        self.vocab_size = vocab_size
        self.block_size = block_size
        self.state_encoder_cfg = state_encoder_cfg
        self.state_encoder_type = state_encoder_type
        self.num_channels = num_channels
        for k,v in kwargs.items():
            setattr(self, k, v)

class DecisionTransformer(nn.Module):
    """  the full GPT language model, with a context size of block_size """

    def __init__(self, config):
        super().__init__()
        self.stages = {'train', 'inference'}
        self.config = config
        self.num_channels = config.num_channels
        assert config.state_encoder_type in {'conv', 'transformer'}, '...'
        self.state_encoder_type = config.state_encoder_type
        self.state_encoder_cfg = config.state_encoder_cfg
        self.action_discrete = config.action_discrete
        self.model_type = config.model_type

        # self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
        self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size + 1, config.n_embd))
        # self.global_pos_emb = nn.Parameter(torch.zeros(1, config.max_timestep+1, config.n_embd))
        self.drop = nn.Dropout(config.embd_pdrop)

        # transformer
        self.blocks = GPT2(config.n_layer, config.n_embd, config.n_head, 
                           attn_drop=config.attn_pdrop, resid_pdrop=config.resid_pdrop, 
                           mlp_ratio=4.0)
        
        # decoder head
        self.ln_f = nn.LayerNorm(config.n_embd)
        self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)

        self.block_size = config.block_size
        self.apply(self._init_weights)

        self.state_encoder = StateEncoder(
            encoder_type=self.state_encoder_type, 
            num_channels=config.num_channels, 
            **self.state_encoder_cfg)
        self.ret_emb = nn.Sequential(nn.Linear(1, config.n_embd), nn.Tanh())

        self.action_embeddings = TokensEmbeddings(config.vocab_size, config.n_embd, config.action_discrete)
        nn.init.normal_(self.action_embeddings.embeddings[0].embed.weight, mean=0.0, std=0.02)
        
    def get_block_size(self):
        return self.block_size

    def _init_weights(self, module):
        if isinstance(module, (nn.Linear, nn.Embedding)):
            module.weight.data.normal_(mean=0.0, std=0.02)
            if isinstance(module, nn.Linear) and module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.LayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)

    def process_transitions_stack(self, states):
        b, t, c, h, w = states.shape
        temporal_patches = self.state_encoder_cfg['temporal_patches']
        assert c == (temporal_patches*self.num_channels), '...'
        states = states.reshape(b, t, temporal_patches, self.num_channels, h, w)
        states = states.reshape(b, t*temporal_patches, self.num_channels, h, w)
        return states
    
    def values2actions(self, values, **kwargs):
        if self.config.action_discrete:
            y, certainty = misc.make_discrete_actions(values, **kwargs)
        else:
            y, certainty = misc.make_continuous_actions(values, **kwargs)
        return y, certainty

    # state, action, and return
    def forward(self, stage, states, actions, rtgs=None, **kwargs):
        # states: (batch, block_size, 4*84*84)
        # actions: (batch, block_size, 1)
        # targets: (batch, block_size, 1)
        # rtgs: (batch, block_size, 1)
        # timesteps: (batch, 1, 1)
        assert stage in self.stages
        if stage == 'train':
            targets = actions
            actions = misc.mask_tensor_causal(actions, self.config.unknown_action, forward=True, k=1)
        else:
            targets = None
        
        if self.state_encoder_type == 'transformer':
            flat_states = self.process_transitions_stack(states)
            state_embeddings = self.state_encoder(flat_states)
        else:
            state_embeddings = self.state_encoder(states.reshape(-1, 4, 84, 84).type(torch.float32).contiguous()) # (batch * block_size, n_embd)
            state_embeddings = state_embeddings.reshape(states.shape[0], states.shape[1], self.state_encoder.state_dim) # (batch, block_size, n_embd)
            
        if actions is not None and self.model_type == 'reward_conditioned': 
            rtg_embeddings = self.ret_emb(rtgs.type(torch.float32))
            action_embeddings = self.action_embeddings(actions) # (batch, block_size, n_embd)
            token_embeddings = torch.zeros((states.shape[0], states.shape[1]*3 - int(targets is None), self.config.n_embd), dtype=torch.float32, device=state_embeddings.device)
            token_embeddings[:,::3,:] = rtg_embeddings
            token_embeddings[:,1::3,:] = state_embeddings
            token_embeddings[:,2::3,:] = action_embeddings[:,-states.shape[1] + int(targets is None):,:]
        elif actions is None and self.model_type == 'reward_conditioned': # only happens at very first timestep of evaluation
            rtg_embeddings = self.ret_emb(rtgs.type(torch.float32))

            token_embeddings = torch.zeros((states.shape[0], states.shape[1]*2, self.config.n_embd), dtype=torch.float32, device=state_embeddings.device)
            token_embeddings[:,::2,:] = rtg_embeddings # really just [:,0,:]
            token_embeddings[:,1::2,:] = state_embeddings # really just [:,1,:]
        elif actions is not None and self.model_type == 'naive':
            action_embeddings = self.action_embeddings(actions) # (batch, block_size, n_embd)

            token_embeddings = torch.zeros((states.shape[0], states.shape[1]*2 - int(targets is None), self.config.n_embd), dtype=torch.float32, device=state_embeddings.device)
            token_embeddings[:,::2,:] = state_embeddings
            token_embeddings[:,1::2,:] = action_embeddings[:,-states.shape[1] + int(targets is None):,:]
        elif actions is None and self.model_type == 'naive': # only happens at very first timestep of evaluation
            token_embeddings = state_embeddings
        else:
            raise NotImplementedError()

        batch_size = states.shape[0]
        # all_global_pos_emb = torch.repeat_interleave(self.global_pos_emb, batch_size, dim=0) # batch_size, traj_length, n_embd

        # position_embeddings = torch.gather(all_global_pos_emb, 1, torch.repeat_interleave(timesteps, self.config.n_embd, dim=-1)) + self.pos_emb[:, :token_embeddings.shape[1], :]
        position_embeddings = self.pos_emb[:, :token_embeddings.shape[1], :]
        x = self.drop(token_embeddings + position_embeddings)
        x = self.blocks(x).get('outputs')
        x = self.ln_f(x)
        logits = self.head(x)
        
        if actions is not None and self.model_type == 'reward_conditioned':
            logits = logits[:, 1::3, :] # only keep predictions from state_embeddings
        elif actions is None and self.model_type == 'reward_conditioned':
            logits = logits[:, 1:, :]
        elif actions is not None and self.model_type == 'naive':
            logits = logits[:, ::2, :] # only keep predictions from state_embeddings
        elif actions is None and self.model_type == 'naive':
            logits = logits # for completeness
        else:
            raise NotImplementedError()
        
        # if we are given some desired targets also calculate the loss
        if stage == 'train':
            out = {
                'loss': losses.action_prediction_loss(logits, targets, self.config.unknown_action, 
                                                      self.config.action_discrete)
            }
        else:
            y, certainty = self.values2actions(logits, **kwargs)
            out = {'actions': y, 'certainty': certainty}
        return out

