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

class VRPModel(nn.Module):

    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params

        self.encoder = VRP_Encoder(**model_params)
        self.decoder = Decoder(**model_params)
        self.encoded_nodes = None
        self.partition = ParNet(50, 4)
        self.partition_training = model_params["train_partition"]
        # shape: (batch, problem+1, EMBEDDING_DIM)

    def gen_cos_sim_matrix(self, shift_coors):
        dot_products = torch.matmul(shift_coors, shift_coors.transpose(1, 2))
        magnitudes = torch.sqrt(torch.sum(shift_coors ** 2, dim=1)).unsqueeze(1)
        magnitude_matrix = torch.matmul(magnitudes, magnitudes.transpose(1, 2)) + 1e-10
        cosine_similarity_matrix = dot_products / magnitude_matrix
        return cosine_similarity_matrix

    def get_expand_prob(self, state):

        encoded_last_node = _get_encoding(self.encoded_nodes, state.current_node)
        # shape: (batch, beam_width, embedding)
        heatmap = _get_encoding3(self.heatmap, state.current_node)
        probs = self.decoder(encoded_last_node, state.load, state.time, state.length, state.route_open,
                                 ninf_mask=state.ninf_mask, heatmap=heatmap)
        # shape: (batch, beam_width, problem+1)

        return probs

    def pre_forward(self, reset_state):
        # depot_xy = reset_state.depot_xy
        depot_xy = reset_state.x_depot
        # shape: (batch, 1, 2)
        # node_xy = reset_state.node_xy
        node_xy_demand = reset_state.x_node
        # shape: (batch, problem, 2)
        # node_demand = reset_state.node_demand
        # shape: (batch, problem)
        node_earlyTW = reset_state.node_earlyTW
        # shape: (batch, problem)
        node_lateTW = reset_state.node_lateTW
        node_service_time = reset_state.node_service_time
        # shape: (batch, problem)
        # node_xy_demand = torch.cat((node_xy, node_demand[:, :, None]), dim=2)
        # shape: (batch, problem, 3)
        node_service_time_TW = torch.cat((node_service_time[:,:,None], node_earlyTW[:, :, None], node_lateTW[:, :, None]), dim=2)
        # shape: (batch, problem, 2)
        node_xy_demand_service_TW = torch.cat((node_xy_demand, node_service_time_TW), dim=2)
        # shape: (batch, problem, 5)
        distances = reset_state.distances
        buckets = reset_state.buckets
        sorted_indices = reset_state.sorted_indices
        if self.model_params["heatmap"]:
            shift_coors = reset_state.shift_coors
            k_sparse = 50
            cos_mat = self.gen_cos_sim_matrix(shift_coors)
            cos_mat = (cos_mat + cos_mat.min()) / cos_mat.max()
            euc_mat = distances
            euc_aff = 1 + euc_mat
            topk_values, topk_indices = torch.topk(cos_mat,
                                                   k=k_sparse,
                                                   dim=2, largest=True)

            B, N, K = topk_indices.shape
            device = topk_indices.device
            batch_idx = torch.arange(B, device=device).view(B, 1, 1).expand(B, N, K).flatten()
            src_idx = torch.arange(N, device=device).view(1, N, 1).expand(B, N, K).flatten()
            tgt_idx = topk_indices.flatten()
            edge_index = torch.stack([batch_idx, src_idx, tgt_idx], dim=0)
            edge_attr1 = euc_aff[edge_index[0], edge_index[1], edge_index[2]]
            edge_attr2 = cos_mat[edge_index[0], edge_index[1], edge_index[2]]
            edge_attr = torch.cat((edge_attr1.unsqueeze(-1), edge_attr2.unsqueeze(-1)), -1)
        else:
            topk_indices = None
            edge_index = None
            edge_attr = None

        self.encoded_nodes, self.encoded_edges = self.encoder(depot_xy, node_xy_demand_service_TW, buckets, sorted_indices,
                                                              edge_attr,
                                                              edge_index)
        if self.model_params["heatmap"]:
            # encoded_nodes = self.encoder_partitioner(x_depot, x_node, buckets, sorted_indices)
            self.heatmap = self.partition(self.encoded_edges, distances, topk_indices)
        else:
            self.heatmap = None
        # shape: (batch, problem+1, embedding)
        self.decoder.set_kv(self.encoded_nodes)

    def forward(self, state):
        batch_size = state.BATCH_IDX.size(0)
        pomo_size = state.BATCH_IDX.size(1)

        if state.selected_count == 0:  # First Move, depot
            selected = torch.zeros(size=(batch_size, pomo_size), dtype=torch.long)
            prob = torch.ones(size=(batch_size, pomo_size))

            # # Use Averaged encoded nodes for decoder input_1
            # encoded_nodes_mean = self.encoded_nodes.mean(dim=1, keepdim=True)
            # # shape: (batch, 1, embedding)
            # self.decoder.set_q1(encoded_nodes_mean)

            # # Use encoded_depot for decoder input_2
            # encoded_first_node = self.encoded_nodes[:, [0], :]
            # # shape: (batch, 1, embedding)
            # self.decoder.set_q2(encoded_first_node)

        elif state.selected_count == 1:  # Second Move, POMO
            encoded_last_node = _get_encoding(self.encoded_nodes, state.current_node)
            if self.model_params["heatmap"]:
                heatmap = _get_encoding3(self.heatmap, state.current_node)
            else:
                heatmap = None

            probs = self.decoder(encoded_last_node, state.load, state.time, state.length, state.route_open,
                                 ninf_mask=state.ninf_mask, heatmap=heatmap)
            topk_value, topk_indices = torch.topk(probs[:, 0, 1:], pomo_size)

            # selected = torch.arange(start=1, end=pomo_size + 1)[None, :].expand(batch_size, pomo_size)
            selected = topk_indices
            prob = torch.ones(size=(batch_size, pomo_size))

        else:
            encoded_last_node = _get_encoding(self.encoded_nodes, state.current_node)
            if self.model_params["heatmap"]:
                heatmap = _get_encoding3(self.heatmap, state.current_node)
            else:
                heatmap = None

            probs = self.decoder(encoded_last_node, state.load, state.time, state.length, state.route_open,
                                 ninf_mask=state.ninf_mask, heatmap=heatmap)
            # shape: (batch, pomo, problem+1)
            # print(probs.shape)

            if self.training or  self.partition_training or self.model_params['eval_type'] == 'softmax':
                while True:  # to fix pytorch.multinomial bug on selecting 0 probability elements
                    with torch.no_grad():
                        # print(probs.reshape(batch_size * pomo_size, -1))
                        # print("current time = ",state.time," mask= ",state.ninf_mask)
                        selected = probs.reshape(batch_size * pomo_size, -1).multinomial(1) \
                            .squeeze(dim=1).reshape(batch_size, pomo_size)
                    # shape: (batch, pomo)
                    prob = probs[state.BATCH_IDX, state.POMO_IDX, selected].reshape(batch_size, pomo_size)
                    # shape: (batch, pomo)
                    if (prob != 0).all():
                        break

            else:
                selected = probs.argmax(dim=2)
                # shape: (batch, pomo)
                prob = None  # value not needed. Can be anything.

        return selected, prob


def _get_encoding(encoded_nodes, node_index_to_pick):
    # encoded_nodes.shape: (batch, problem, embedding)
    # node_index_to_pick.shape: (batch, pomo)

    batch_size = node_index_to_pick.size(0)
    pomo_size = node_index_to_pick.size(1)
    embedding_dim = encoded_nodes.size(2)

    gathering_index = node_index_to_pick[:, :, None].expand(batch_size, pomo_size, embedding_dim)
    # shape: (batch, pomo, embedding)

    picked_nodes = encoded_nodes.gather(dim=1, index=gathering_index)
    # shape: (batch, pomo, embedding)

    return picked_nodes


########################################
# ENCODER
########################################

class VRP_Encoder(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        embedding_dim = self.model_params['embedding_dim']
        encoder_layer_num = self.model_params['encoder_layer_num']

        self.embedding_depot = nn.Linear(3, embedding_dim)
        self.embedding_node = nn.Linear(6, embedding_dim)
        self.edge_embedding = nn.Linear(2, 32)

        # self.layers = nn.ModuleList([EncoderLayer(**model_params) for _ in range(encoder_layer_num)])
        self.layers = nn.ModuleList([SparseEncoderLayer(**model_params) for _ in range(encoder_layer_num)])

    def forward(self, depot_xy, node_xy_demand_TW, buckets, sorted_indices, edge_attr, edge_index):
        # depot_xy.shape: (batch, 1, 2)
        # node_xy_demand.shape: (batch, problem, 3)

        embedded_depot = self.embedding_depot(depot_xy)
        # shape: (batch, 1, embedding)
        embedded_node = self.embedding_node(node_xy_demand_TW)
        # input shape: (batch, problem, 5)
        # 5 features are: x_coord, y_coord, demands, earlyTW, lateTW
        # embedded_node shape: (batch, problem, embedding)
        if self.model_params["heatmap"]:
            edge_embedding = self.edge_embedding(edge_attr)
        else:
            edge_embedding = None

        embedded_node = torch.cat((embedded_depot, embedded_node), dim=1)
        # shape: (batch, problem+1, embedding)

        for layer in self.layers:
            embedded_node, edge_embedding = layer(embedded_node, buckets, sorted_indices, edge_embedding, edge_index)

        return embedded_node, edge_embedding
        # shape: (batch, problem+1, embedding)


class EncoderLayer(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        embedding_dim = self.model_params['embedding_dim']
        head_num = self.model_params['head_num']
        qkv_dim = self.model_params['qkv_dim']

        self.Wq = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wk = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wv = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.attention = FlashAttention(dim=128, heads=8, dim_head=16)
        self.multi_head_combine = nn.Linear(head_num * qkv_dim, embedding_dim)

        # self.add_n_normalization_1 = AddAndInstanceNormalization(**model_params)
        # self.feed_forward = FeedForward(**model_params)
        # self.add_n_normalization_2 = AddAndInstanceNormalization(**model_params)

    def forward(self, input1):
        # input1.shape: (batch, problem+1, embedding)
        head_num = self.model_params['head_num']

        q = reshape_by_heads(self.Wq(input1), head_num=head_num)
        k = reshape_by_heads(self.Wk(input1), head_num=head_num)
        v = reshape_by_heads(self.Wv(input1), head_num=head_num)
        # qkv shape: (batch, head_num, problem, qkv_dim)

        out_concat = multi_head_attention(q, k, v)
        # shape: (batch, problem, head_num*qkv_dim)

        multi_head_out = self.multi_head_combine(out_concat)
        # shape: (batch, problem, embedding)

        # out1 = self.add_n_normalization_1(input1, multi_head_out)
        # out2 = self.feed_forward(out1)
        # out3 = self.add_n_normalization_2(out1, out2)
        out3 = multi_head_out
        return out3
        # shape: (batch, problem, embedding)


class SparseEncoderLayer(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        self.node_encoder = EncoderLayer(**model_params)
        self.edge_encoder = EdgeEncoderLayer(**model_params)
        self.add_n_normalization_1 = AddAndInstanceNormalization(**model_params)
        self.add_n_normalization_2 = AddAndInstanceNormalization(**model_params)
        self.feed_forward = FeedForward(**model_params)

    def forward(self, node_embed, buckets, sorted_indices, edge_embedding, edge_index):
        # input1.shape: (batch, problem+1, embedding)
        b, h, u, s = buckets.size()
        _, n, d = node_embed.size()
        my_buckets = buckets.unsqueeze(-1).expand(b, h, u, s, d)
        embedded_node2 = node_embed[:, None, None, :, :].expand(b, h, u, n, d)
        bucket_embedded_node = torch.gather(embedded_node2, 3, my_buckets)
        bucket_embedded_node = bucket_embedded_node.reshape(-1, s, d)

        node_embed1 = self.node_encoder(bucket_embedded_node)
        node_embed1 = node_embed1.reshape(b, h, u, s, d)
        depot = torch.sum(torch.mean(node_embed1[..., 0:1, :], dim=2), dim=1)
        other_nodes = node_embed1[..., 1:, :].reshape(b, h, u * (s - 1), d)
        a_idx = sorted_indices.unsqueeze(-1).expand(-1, -1, -1, 128)
        # gathered = other_nodes.gather(dim=2, index=a_idx)  # → shape (2, 8, 100, 128)
        gathered = torch.zeros_like(other_nodes)
        gathered.scatter_(dim=2, index=a_idx, src=other_nodes)
        # Step 3: Sum over the “8” dimension (dim=1)
        nodes = gathered.sum(dim=1)
        # nodes = gathered[:,0, ...]
        node_embed2 = torch.cat((depot, nodes), dim=1)
        if self.model_params["heatmap"]:
            edge_embedding = self.edge_encoder(node_embed, edge_embedding, edge_index)
        else:
            edge_embedding = None

        out1 = self.add_n_normalization_1(node_embed, node_embed2)
        out2 = self.feed_forward(out1)
        node_embed = self.add_n_normalization_2(out1, out2)

        return node_embed, edge_embedding
        # shape: (batch, problem, embedding)


class EdgeEncoderLayer(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        self.edge_reduce_embed = FeedForward3(128, 64, 32)
        self.W2 = nn.Linear(32, 32)
        self.W3 = nn.Linear(32, 32)
        self.W1 = nn.Linear(32, 32)
        self.e_bns = nn.Linear(32, 32)
        self.act_fn = getattr(F, "silu")

    def forward(self, node_embed, edge_embedding, edge_index):
        reduced_node = self.edge_reduce_embed(node_embed)
        edge_embedding = edge_embedding + self.act_fn(self.e_bns(
            self.W1(edge_embedding) + self.W2(reduced_node[edge_index[0], edge_index[1]]) + self.W3(reduced_node[
                                                                                                        edge_index[0],
                                                                                                        edge_index[
                                                                                                            2]])))

        return edge_embedding


########################################
# DECODER
########################################
class Decoder(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        # self.decoder = CVRP_Decoder(**model_params)
        self.decoder = VRP_Decoder(**model_params)
        self.logit_clipping = self.model_params['logit_clipping']

    def set_kv(self, encoded_nodes):
        self.decoder.set_kv(encoded_nodes)

    def forward(self, encoded_last_node, load, time, length, route_open, ninf_mask, heatmap=None):
        if self.model_params["train_partition"]:
            with torch.no_grad():
                score_scaled = self.decoder(encoded_last_node, load, time, ninf_mask)
        else:
            score_scaled = self.decoder(encoded_last_node, load, time, ninf_mask)

        if self.model_params['heatmap']:
            score_scaled += heatmap
            # score_scaled = heatmap

        score_clipped = self.logit_clipping * torch.tanh(score_scaled)

        score_masked = score_clipped + ninf_mask

        probs = F.softmax(score_masked, dim=2)
        return probs


class VRP_Decoder(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        embedding_dim = self.model_params['embedding_dim']
        head_num = self.model_params['head_num']
        qkv_dim = self.model_params['qkv_dim']

        # self.Wq_1 = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        # self.Wq_2 = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wq_last = nn.Linear(embedding_dim + 2, head_num * qkv_dim, bias=False)
        self.Wk = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wv = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.my_attention = FlashAttention(dim=128, heads=8, dim_head=16)
        self.multi_head_combine = nn.Linear(head_num * qkv_dim, embedding_dim)

        self.k = None  # saved key, for multi-head attention
        self.v = None  # saved value, for multi-head_attention
        self.single_head_key = None  # saved, for single-head attention
        # self.q1 = None  # saved q1, for multi-head attention
        # self.q2 = None  # saved q2, for multi-head attention

    def set_kv(self, encoded_nodes):
        # encoded_nodes.shape: (batch, problem+1, embedding)
        head_num = self.model_params['head_num']

        self.k = reshape_by_heads(self.Wk(encoded_nodes), head_num=head_num)
        self.v = reshape_by_heads(self.Wv(encoded_nodes), head_num=head_num)
        # shape: (batch, head_num, problem+1, qkv_dim)
        self.single_head_key = encoded_nodes.transpose(1, 2)
        # shape: (batch, embedding, problem+1)

    def set_q1(self, encoded_q1):
        # encoded_q.shape: (batch, n, embedding)  # n can be 1 or pomo
        head_num = self.model_params['head_num']
        self.q1 = reshape_by_heads(self.Wq_1(encoded_q1), head_num=head_num)
        # shape: (batch, head_num, n, qkv_dim)

    def set_q2(self, encoded_q2):
        # encoded_q.shape: (batch, n, embedding)  # n can be 1 or pomo
        head_num = self.model_params['head_num']
        self.q2 = reshape_by_heads(self.Wq_2(encoded_q2), head_num=head_num)
        # shape: (batch, head_num, n, qkv_dim)

    def forward(self, encoded_last_node, load, time, ninf_mask):
        # encoded_last_node.shape: (batch, pomo, embedding)
        # load.shape: (batch, pomo)
        # ninf_mask.shape: (batch, pomo, problem)

        head_num = self.model_params['head_num']

        #  Multi-Head Attention
        #######################################################
        input_cat = torch.cat(
            (encoded_last_node, load[:, :, None], time[:, :, None]), dim=2)
        # shape = (batch, group, EMBEDDING_DIM+3)

        q_last = reshape_by_heads(self.Wq_last(input_cat), head_num=head_num)
        # q_last shape: (batch, head_num, pomo, qkv_dim)

        # q = self.q1 + self.q2 + q_last
        # # shape: (batch, head_num, pomo, qkv_dim)
        # shape: (batch, head_num, pomo, qkv_dim)
        # print("ninf_mask",ninf_mask)
        my_mask = ninf_mask[:, None, :, :].expand(ninf_mask.size(0), head_num, ninf_mask.size(1), ninf_mask.size(-1))
        my_mask2 = torch.isneginf(my_mask)
        out_concat = self.my_attention(q_last, self.k, self.v, mask=my_mask2)
        # out_concat = multi_head_attention(q, self.k, self.v, rank3_ninf_mask=ninf_mask)
        # shape: (batch, pomo, head_num*qkv_dim)

        mh_atten_out = self.multi_head_combine(out_concat)
        # shape: (batch, pomo, embedding)

        #  Single-Head Attention, for probability calculation
        #######################################################
        score = torch.matmul(mh_atten_out, self.single_head_key)
        # shape: (batch, pomo, problem)
        # print("score",score)

        sqrt_embedding_dim = self.model_params['sqrt_embedding_dim']
        logit_clipping = self.model_params['logit_clipping']

        score_scaled = score / sqrt_embedding_dim
        return score_scaled


class VRP_Decoder2(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        self.model_params = model_params
        embedding_dim = self.model_params['embedding_dim']
        head_num = self.model_params['head_num']
        qkv_dim = self.model_params['qkv_dim']

        # self.Wq_1 = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        # self.Wq_2 = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wq_last = nn.Linear(embedding_dim + 4, head_num * qkv_dim, bias=False)
        self.Wk = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)
        self.Wv = nn.Linear(embedding_dim, head_num * qkv_dim, bias=False)

        self.multi_head_combine = nn.Linear(head_num * qkv_dim, embedding_dim)

        self.k = None  # saved key, for multi-head attention
        self.v = None  # saved value, for multi-head_attention
        self.single_head_key = None  # saved, for single-head attention
        # self.q1 = None  # saved q1, for multi-head attention
        # self.q2 = None  # saved q2, for multi-head attention

    def set_kv(self, encoded_nodes):
        # encoded_nodes.shape: (batch, problem+1, embedding)
        head_num = self.model_params['head_num']

        self.k = reshape_by_heads(self.Wk(encoded_nodes), head_num=head_num)
        self.v = reshape_by_heads(self.Wv(encoded_nodes), head_num=head_num)
        # shape: (batch, head_num, problem+1, qkv_dim)
        self.single_head_key = encoded_nodes.transpose(1, 2)
        # shape: (batch, embedding, problem+1)

    def set_q1(self, encoded_q1):
        # encoded_q.shape: (batch, n, embedding)  # n can be 1 or pomo
        head_num = self.model_params['head_num']
        self.q1 = reshape_by_heads(self.Wq_1(encoded_q1), head_num=head_num)
        # shape: (batch, head_num, n, qkv_dim)

    def set_q2(self, encoded_q2):
        # encoded_q.shape: (batch, n, embedding)  # n can be 1 or pomo
        head_num = self.model_params['head_num']
        self.q2 = reshape_by_heads(self.Wq_2(encoded_q2), head_num=head_num)
        # shape: (batch, head_num, n, qkv_dim)

    def forward(self, encoded_last_node, load, time, length, route_open, ninf_mask):
        # encoded_last_node.shape: (batch, pomo, embedding)
        # load.shape: (batch, pomo)
        # ninf_mask.shape: (batch, pomo, problem)

        head_num = self.model_params['head_num']

        #  Multi-Head Attention
        #######################################################
        input_cat = torch.cat(
            (encoded_last_node, load[:, :, None], time[:, :, None], length[:, :, None], route_open[:, :, None]), dim=2)
        # shape = (batch, group, EMBEDDING_DIM+3)

        q_last = reshape_by_heads(self.Wq_last(input_cat), head_num=head_num)
        # q_last shape: (batch, head_num, pomo, qkv_dim)

        # q = self.q1 + self.q2 + q_last
        # # shape: (batch, head_num, pomo, qkv_dim)
        q = q_last
        # shape: (batch, head_num, pomo, qkv_dim)
        # print("ninf_mask",ninf_mask)
        out_concat = multi_head_attention(q, self.k, self.v, rank3_ninf_mask=ninf_mask)
        # shape: (batch, pomo, head_num*qkv_dim)

        mh_atten_out = self.multi_head_combine(out_concat)
        # shape: (batch, pomo, embedding)

        #  Single-Head Attention, for probability calculation
        #######################################################
        score = torch.matmul(mh_atten_out, self.single_head_key)
        # shape: (batch, pomo, problem)
        # print("score",score)

        sqrt_embedding_dim = self.model_params['sqrt_embedding_dim']
        logit_clipping = self.model_params['logit_clipping']

        score_scaled = score / sqrt_embedding_dim
        # shape: (batch, pomo, problem)
        # print("score_scaled",score_scaled)

        score_clipped = logit_clipping * torch.tanh(score_scaled)

        score_masked = score_clipped + ninf_mask

        probs = F.softmax(score_masked, dim=2)
        # shape: (batch, pomo, problem)

        return probs


########################################
# NN SUB CLASS / FUNCTIONS
########################################

def reshape_by_heads(qkv, head_num):
    # q.shape: (batch, n, head_num*key_dim)   : n can be either 1 or PROBLEM_SIZE

    batch_s = qkv.size(0)
    n = qkv.size(1)

    q_reshaped = qkv.reshape(batch_s, n, head_num, -1)
    # shape: (batch, n, head_num, key_dim)

    q_transposed = q_reshaped.transpose(1, 2)
    # shape: (batch, head_num, n, key_dim)

    return q_transposed


def multi_head_attention(q, k, v, rank2_ninf_mask=None, rank3_ninf_mask=None):
    # q shape: (batch, head_num, n, key_dim)   : n can be either 1 or PROBLEM_SIZE
    # k,v shape: (batch, head_num, problem, key_dim)
    # rank2_ninf_mask.shape: (batch, problem)
    # rank3_ninf_mask.shape: (batch, group, problem)

    batch_s = q.size(0)
    head_num = q.size(1)
    n = q.size(2)
    key_dim = q.size(3)

    input_s = k.size(2)

    score = torch.matmul(q, k.transpose(2, 3))
    # shape: (batch, head_num, n, problem)

    score_scaled = score / torch.sqrt(torch.tensor(key_dim, dtype=torch.float))
    if rank2_ninf_mask is not None:
        score_scaled = score_scaled + rank2_ninf_mask[:, None, None, :].expand(batch_s, head_num, n, input_s)
    if rank3_ninf_mask is not None:
        score_scaled = score_scaled + rank3_ninf_mask[:, None, :, :].expand(batch_s, head_num, n, input_s)

    weights = nn.Softmax(dim=3)(score_scaled)
    # shape: (batch, head_num, n, problem)

    out = torch.matmul(weights, v)
    # shape: (batch, head_num, n, key_dim)

    out_transposed = out.transpose(1, 2)
    # shape: (batch, n, head_num, key_dim)

    out_concat = out_transposed.reshape(batch_s, n, head_num * key_dim)
    # shape: (batch, n, head_num*key_dim)

    return out_concat


class AddAndInstanceNormalization(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        embedding_dim = model_params['embedding_dim']
        self.norm = nn.InstanceNorm1d(embedding_dim, affine=True, track_running_stats=False)

    def forward(self, input1, input2):
        # input.shape: (batch, problem, embedding)

        added = input1 + input2
        # shape: (batch, problem, embedding)

        transposed = added.transpose(1, 2)
        # shape: (batch, embedding, problem)

        normalized = self.norm(transposed)
        # shape: (batch, embedding, problem)

        back_trans = normalized.transpose(1, 2)
        # shape: (batch, problem, embedding)

        return back_trans


class AddAndBatchNormalization(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        embedding_dim = model_params['embedding_dim']
        self.norm_by_EMB = nn.BatchNorm1d(embedding_dim, affine=True)
        # 'Funny' Batch_Norm, as it will normalized by EMB dim

    def forward(self, input1, input2):
        # input.shape: (batch, problem, embedding)

        batch_s = input1.size(0)
        problem_s = input1.size(1)
        embedding_dim = input1.size(2)

        added = input1 + input2
        normalized = self.norm_by_EMB(added.reshape(batch_s * problem_s, embedding_dim))
        back_trans = normalized.reshape(batch_s, problem_s, embedding_dim)

        return back_trans


class FeedForward(nn.Module):
    def __init__(self, **model_params):
        super().__init__()
        embedding_dim = model_params['embedding_dim']
        ff_hidden_dim = model_params['ff_hidden_dim']

        self.W1 = nn.Linear(embedding_dim, ff_hidden_dim)
        self.W2 = nn.Linear(ff_hidden_dim, embedding_dim)

    def forward(self, input1):
        # input.shape: (batch, problem, embedding)

        return self.W2(F.relu(self.W1(input1)))


class FeedForward3(nn.Module):
    def __init__(self, embed_dim1, embed_dim2, embed_dim3):
        super().__init__()

        self.W1 = nn.Linear(embed_dim1, embed_dim2)
        self.W2 = nn.Linear(embed_dim2, embed_dim3)

    def forward(self, input1):
        # input.shape: (batch, problem, embedding)

        return self.W2(F.relu(self.W1(input1)))


def _get_encoding3(heatmap, node_index_to_pick):
    # encoded_nodes.shape: (batch, problem, embedding)
    # node_index_to_pick.shape: (batch, pomo)

    batch_size = node_index_to_pick.size(0)
    pomo_size = node_index_to_pick.size(1)
    embedding_dim = heatmap.size(2)

    gathering_index = node_index_to_pick[:, :, None].expand(batch_size, pomo_size, embedding_dim)
    # shape: (batch, pomo, embedding)

    picked_nodes = heatmap.gather(dim=1, index=gathering_index)
    # shape: (batch, pomo, embedding)

    return picked_nodes


# general class for MLP
class MLP(nn.Module):
    @property
    def device(self):
        return self._dummy.device

    def __init__(self, units_list, act_fn):
        super().__init__()
        self._dummy = nn.Parameter(torch.empty(0), requires_grad=False)
        self.units_list = units_list
        self.depth = len(self.units_list) - 1
        self.act_fn = getattr(F, act_fn)
        self.lins = nn.ModuleList([nn.Linear(self.units_list[i], self.units_list[i + 1]) for i in range(self.depth)])

    def forward(self, x, k_sparse):
        for i in range(self.depth):
            x = self.lins[i](x)
            if i < self.depth - 1:
                x = self.act_fn(x)
            else:
                x = x.reshape(x.size(0), x.size(1), -1)
                x = torch.tanh(x)
        return x


# MLP for predicting parameterization theta
class ParNet(MLP):
    def __init__(self, k_sparse, depth=3, units=32, preds=1, act_fn='silu'):
        self.units = units
        self.preds = preds
        self.k_sparse = k_sparse
        unit_list = [self.units] * (depth - 2) + [int(self.units / 2)] + [int(self.units / 4)] + [self.preds]
        super().__init__(unit_list, act_fn)

    def forward(self, x, distances, topk_indices):
        B, N, N = distances.size()
        heatmap = super().forward(x, self.k_sparse).squeeze(dim=-1).reshape(B, N, self.k_sparse)
        full_heatmap = torch.full((B, N, N), -1.0, device=heatmap.device)

        # Fill in the top-k heatmap scores into the correct positions
        full_heatmap.scatter_(dim=2, index=topk_indices, src=heatmap)
        return full_heatmap
