from transformers import AutoTokenizer, AutoModelForMaskedLM, RobertaForMaskedLM, RobertaConfig
from lm_seqs_dataset import LmSeqsDataset
from distiller import Distiller
import numpy as np
import torch

import argparse
import pickle
import shutil
import json
import sys
import os


def sanity_checks(args):
    assert args.mlm and args.alpha_mlm > 0.0
    assert os.path.isfile(args.token_counts)

    assert os.path.isfile(args.student_config)
    if args.student_pretrained_weights is not None:
        assert os.path.isfile(args.student_pretrained_weights)

    if args.freeze_token_type_embds:
        assert args.student_type in ["roberta"]

    assert args.alpha_ce >= 0.0
    assert args.alpha_mlm >= 0.0
    assert args.alpha_mse >= 0.0
    assert args.alpha_cos >= 0.0
    assert args.alpha_ce + args.alpha_mlm + args.alpha_mse + args.alpha_cos > 0.0


def set_seed(args):
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.cuda.manual_seed_all(args.seed)


def assign_special_tokens(args):
    tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path)
    special_tok_ids = {}
    for tok_name, tok_symbol in tokenizer.special_tokens_map.items():
        idx = tokenizer.all_special_tokens.index(tok_symbol)
        special_tok_ids[tok_name] = tokenizer.all_special_ids[idx]
    print(f"Special tokens {special_tok_ids}")
    args.special_tok_ids = special_tok_ids


def get_arguments():
    parser = argparse.ArgumentParser(description="Training")
    parser.add_argument("--force", action="store_true", help="Overwrite output_path if it already exists.")

    parser.add_argument(
        "--output_path", type=str, required=True, help="The output directory (log, checkpoints, parameters, etc.)"
    )
    parser.add_argument(
        "--data_file",
        type=str,
        required=True,
        help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence.",
    )

    parser.add_argument(
        "--student_type",
        type=str,
        choices=["distilbert", "roberta"],
        required=True,
        help="The student type (DistilBERT, RoBERTa).",
    )
    parser.add_argument("--student_config", type=str, required=True, help="Path to the student configuration.")
    parser.add_argument(
        "--student_init_weights", default=None, type=str, help="Load student initialization checkpoint."
    )

    parser.add_argument(
        "--teacher_names", type=str, required=True, help="Names of teacher models."
    )

    parser.add_argument(
        "--tokenizer_name_or_path", type=str, required=True, help="Name or path to tokenizer."
    )

    parser.add_argument("--temperature", default=2.0, type=float, help="Value for the softmax temperature.")
    parser.add_argument(
        "--alpha_ce", default=0.5, type=float, help="Linear weight for the distillation loss. Must be >=0."
    )
    parser.add_argument(
        "--alpha_mlm",
        default=0.0,
        type=float,
        help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag.",
    )
    parser.add_argument("--alpha_mse", default=0.0, type=float, help="Linear weight of the MSE loss. Must be >=0.")
    parser.add_argument(
        "--alpha_cos", default=0.0, type=float, help="Linear weight of the cosine embedding loss. Must be >=0."
    )

    parser.add_argument(
        "--mlm_mask_prop",
        default=0.15,
        type=float,
        help="Proportion of tokens for which we need to make a prediction.",
    )
    parser.add_argument("--word_mask", default=0.8, type=float, help="Proportion of tokens to mask out.")
    parser.add_argument("--word_keep", default=0.1, type=float, help="Proportion of tokens to keep.")
    parser.add_argument("--word_rand", default=0.1, type=float, help="Proportion of tokens to randomly replace.")
    parser.add_argument(
        "--mlm_smoothing",
        default=0.7,
        type=float,
        help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec).",
    )
    parser.add_argument("--token_counts", type=str, help="The token counts in the data_file for MLM.")

    parser.add_argument(
        "--restrict_ce_to_mask",
        action="store_true",
        help="If true, compute the distillation loss only the [MLM] prediction distribution.",
    )
    parser.add_argument(
        "--freeze_pos_embs",
        action="store_true",
        help="Freeze positional embeddings during distillation. For student_type in ['roberta'] only.",
    )
    parser.add_argument(
        "--freeze_token_type_embds",
        action="store_true",
        help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only.",
    )

    parser.add_argument("--n_epoch", type=int, default=3, help="Number of pass on the whole dataset.")
    parser.add_argument("--batch_size", type=int, default=10, help="Batch size (for each process).")
    parser.add_argument(
        "--group_by_size",
        action="store_false",
        help="If true, group sequences that have similar length into the same batch. Default is true.",
    )

    parser.add_argument(
        "--gradient_accumulation_steps",
        type=int,
        default=50,
        help="Gradient accumulation for larger training batches.",
    )
    parser.add_argument("--warmup_prop", default=0.05, type=float, help="Linear warmup proportion.")
    parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
    parser.add_argument("--learning_rate", default=5e-4, type=float, help="The initial learning rate for Adam.")
    parser.add_argument("--adam_epsilon", default=1e-6, type=float, help="Epsilon for Adam optimizer.")
    parser.add_argument("--max_grad_norm", default=5.0, type=float, help="Max gradient norm.")
    parser.add_argument("--initializer_range", default=0.02, type=float, help="Random initialization range.")

    parser.add_argument("--seed", type=int, default=56, help="Random seed")

    parser.add_argument("--log_interval", type=int, default=500, help="Tensorboard logging interval.")
    parser.add_argument("--checkpoint_interval", type=int, default=4000, help="Checkpoint interval.")

    return parser.parse_args()


def setup_output_directory(args):
    if os.path.exists(args.output_path):
        if not args.force:
            raise ValueError(
                f"Serialization dir {args.output_path} already exists, but you have not precised wheter to overwrite it"
                "Use `--force` if you want to overwrite it"
            )
        else:
            shutil.rmtree(args.output_path)

    if not os.path.exists(args.output_path):
        os.makedirs(args.output_path)
    print(f"Outputs of the experiment will be in {args.output_path}")

    print(f"Param: {args}")
    with open(os.path.join(args.output_path, "parameters.json"), "w") as f:
        json.dump(vars(args), f, indent=4)


def load_dataset(args):
    print(f"Loading data from {args.data_file}")
    with open(args.data_file, "rb") as fp:
        data = pickle.load(fp)
    train_lm_seq_dataset = LmSeqsDataset(params=args, data=data)
    print("Data loader created.")
    return train_lm_seq_dataset


def get_token_counts_and_probabilities(args):
    print(f"Loading token counts from {args.token_counts} (already pre-computed)")
    with open(args.token_counts, "rb") as fp:
        counts = pickle.load(fp)

    token_probs = np.maximum(counts, 1) ** -args.mlm_smoothing
    for idx in args.special_tok_ids.values():
        token_probs[idx] = 0.0
    token_probs = torch.from_numpy(token_probs)
    return counts, token_probs


def load_student(args):
    print(f"Loading student config from {args.student_config}")
    student_architecture_config = RobertaConfig.from_pretrained(args.student_config)
    student_architecture_config.output_hidden_states = True

    if args.student_init_weights is not None:
        print(f"Loading pretrained weights from {args.student_init_weights}")
        student = RobertaForMaskedLM.from_pretrained(args.student_init_weights,
                                                     config=student_architecture_config)
    else:
        student = RobertaForMaskedLM(student_architecture_config)

    student.to(device='cuda')
    print("Student loaded.")
    return student


def parse_teachers(args):
    teacher_names = args.teacher_names.split(';')
    teachers = []
    for t in teacher_names:
        tt = AutoModelForMaskedLM.from_pretrained(t)
        tt.to(device='cuda')
        teachers.append(tt)
    return teachers


def load_teachers(args):
    teachers = []
    for teacher in parse_teachers(args):
        teachers.append(teacher)
    print(f"Teachers loaded.")
    return teachers


def main():
    args = get_arguments()
    setup_output_directory(args)

    assign_special_tokens(args)
    token_counts, token_probs = get_token_counts_and_probabilities(args)
    args.max_model_input_size = 512

    train_lm_seq_dataset = load_dataset(args)

    student = load_student(args)
    teachers = load_teachers(args)

    if args.freeze_pos_embs:
        student.roberta.embeddings.position_embeddings.weight.requires_grad = False
    if args.freeze_token_type_embds:
        student.roberta.embeddings.token_type_embeddings.weight.requires_grad = False

    torch.cuda.empty_cache()
    distiller = Distiller(
        params=args, dataset=train_lm_seq_dataset, token_probs=token_probs, student=student, teachers=teachers
    )
    distiller.train()
    print(f"Done. Output saved to {args.output_path}")


if __name__ == '__main__':
    main()
