# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/models/models.ccpm.ipynb (unless otherwise specified).

__all__ = ['CCPM']

# Cell
import torch
from torch import nn

from .layers.embedding import EmbeddingLayer
from .layers.common import KMaxPooling

from .bases.ctr import CTRModel

# Internal Cell
def get_activation(activation):
    if isinstance(activation, str):
        if activation.lower() == "relu":
            return nn.ReLU()
        elif activation.lower() == "sigmoid":
            return nn.Sigmoid()
        elif activation.lower() == "tanh":
            return nn.Tanh()
        else:
            return getattr(nn, activation)()
    else:
        return activation

# Internal Cell
class CCPM_ConvLayer(nn.Module):
    """
    Input X: tensor of shape (batch_size, 1, num_fields, embedding_dim)
    """
    def __init__(self, num_fields, channels=[3], kernel_heights=[3], activation="Tanh"):
        super(CCPM_ConvLayer, self).__init__()
        if not isinstance(kernel_heights, list):
            kernel_heights = [kernel_heights] * len(channels)
        elif len(kernel_heights) != len(channels):
            raise ValueError("channels={} and kernel_heights={} should have the same length."\
                             .format(channels, kernel_heights))
        module_list = []
        self.channels = [1] + channels
        layers = len(kernel_heights)
        for i in range(1, len(self.channels)):
            in_channels = self.channels[i - 1]
            out_channels = self.channels[i]
            kernel_height = kernel_heights[i - 1]
            module_list.append(nn.ZeroPad2d((0, 0, kernel_height - 1, kernel_height - 1)))
            module_list.append(nn.Conv2d(in_channels, out_channels, kernel_size=(kernel_height, 1)))
            if i < layers:
                k = max(3, int((1 - pow(float(i) / layers, layers - i)) * num_fields))
            else:
                k = 3
            module_list.append(KMaxPooling(k, dim=2))
            module_list.append(get_activation(activation))
        self.conv_layer = nn.Sequential(*module_list)

    def forward(self, X):
        return self.conv_layer(X)

# Cell
class CCPM(CTRModel):
    def __init__(self,
                 feature_map,
                 model_id="CCPM",
                 task="binary_classification",
                 learning_rate=1e-3,
                 embedding_initializer="torch.nn.init.normal_(std=1e-4)",
                 embedding_dim=10,
                 channels=[4, 4, 2],
                 kernel_heights=[6, 5, 3],
                 activation="Tanh",
                 **kwargs):
        super(CCPM, self).__init__(feature_map,
                                           model_id=model_id,
                                           **kwargs)
        self.embedding_layer = EmbeddingLayer(feature_map, embedding_dim)
        self.conv_layer = CCPM_ConvLayer(feature_map.num_fields,
                                         channels=channels,
                                         kernel_heights=kernel_heights,
                                         activation=activation)
        conv_out_dim = 3 * embedding_dim * channels[-1] # 3 is k-max-pooling size of the last layer
        self.fc = nn.Linear(conv_out_dim, 1)
        self.output_activation = self.get_final_activation(task)
        self.init_weights(embedding_initializer=embedding_initializer)

    def forward(self, inputs):
        feature_emb = self.embedding_layer(inputs)
        conv_in = torch.unsqueeze(feature_emb, 1) # shape (bs, 1, field, emb)
        conv_out = self.conv_layer(conv_in)
        flatten_out = torch.flatten(conv_out, start_dim=1)
        y_pred = self.fc(flatten_out)
        if self.output_activation is not None:
            y_pred = self.output_activation(y_pred)
        return y_pred