
import json
import sys
sys.path.append('..')
from modeling import load_gptj, GPTJWrapper, load_gpt2xl, load_gpt2, GPT2Wrapper, load_bloom, BloomWrapper
from bigbench_tasks import load_bigbench_task, multiple_choice_query, PromptBuilder, DefaultOpenPrompter
from rich.progress import track
from console import console, timer
import numpy as np
from utils import get_probs_and_mrrs #model, logits, answer ; logits
import random
import gc
import torch
import argparse
from torch import nn


random.seed(42)
TOTAL_CORRECT =  0

class ColoredObjectsPrompter(DefaultOpenPrompter):
    def __init__(self, dataset, is_extractive):
        super(ColoredObjectsPrompter, self).__init__(dataset)
        self.is_extractive=is_extractive

    def build_open_prompt(self, index, include_answer=False):
        """
        nshots: int number of shots. 0 means just return dataset[index] prompt. 1 means 1 example and 1 test prompt
        dataset a bigbench dataset that can be indexed by index. dataset[index]
        index: the index of the test example. This method will use the [index-nshots, index) datapoints as the nshot examples, wrapping if necessary
        returns: a string prompt, the answer as a string
        """
        datapoint = self.dataset[index]
        inputs = datapoint['inputs']#, datapoint['multiple_choice_targets']
        if self.is_extractive:
            gt = datapoint['targets'][0].lower() #lowercase the first letter!
        else:
            gt = datapoint['targets'][0].title() #capitalize the first letter!
        #gt_idx = targets.index(gt)
        prompt = inputs
        if include_answer:
            prompt+=' '+gt
        return prompt, ' '+gt

    def get_mc_targets(self, idx):
        if self.is_extractive:
            return [' '+t.lower() for t in self.dataset[idx]['multiple_choice_targets']]
        else:
            return [' '+t.title() for t in self.dataset[idx]['multiple_choice_targets']]

def generate_ans(model, prompter, idx):
    global TOTAL_CORRECT
    #making the prompt
    prompt, gt = prompter.nshot_open_prompt(nshots, idx)
    targets = prompter.get_mc_targets(idx)
    gt_idx = targets.index(gt)

    #running prompt thru model
    prompt_ids = model.tokenize(prompt)
    logits = model.get_layers(prompt_ids)

    probs_results = {}
    rrs_results   = {}

    for i in range(len(targets)):
        tgt = targets[i]
        probs, rrs = get_probs_and_mrrs(model, logits, tgt)
        probs_results[i] = probs.tolist()
        rrs_results[i] = rrs.tolist()
        if i == gt_idx:
            #print(targets[i], rrs_results[i][-1])
            if rrs_results[i][-1] ==1:
                TOTAL_CORRECT+=1
                #console.print(targets[i], "ACC SO FAR:", TOTAL_CORRECT/(idx+1.))

    top10_per_layer = model.topk_per_layer(logits, 10)
    prompt_results = {'inputs':prompt, 'targets':targets, 'answer':gt, 'answer_idx':gt_idx, 'probs':probs_results, 'rrs':rrs_results, 'top10_per_layer':top10_per_layer}
    #Lastly, turn the logits into a bunch of prob distributions over the whole vocab. This will be stored separately
    return prompt_results

def get_open_generations(model, dataset, removed_layers):
    global TOTAL_CORRECT, extractive
    TOTAL_CORRECT =  0
    output = []
    prompter = ColoredObjectsPrompter(dataset, extractive)
    with torch.no_grad():
        for i in track(range(len(prompter)), description='iterating...'):
            json_out = generate_ans(model, prompter, i)
            output.append(json_out)

    if extractive:
        with open(f'{model_name}_{nshots}_open_cobjs_ext_rm_ffns_{removed_layers}.json', 'w') as fp:
            json.dump(output, fp, indent=4)
    elif not extractive:
        with open(f'{model_name}_{nshots}_open_cobjs_abs_rm_ffns_{removed_layers}.json', 'w') as fp:
            json.dump(output, fp, indent=4)


def rm_ffn_from_model(model, rm_layers_num):
    b4_params = sum([param.numel() for param in model.parameters() if param.requires_grad])
    layer_start = max(0, len(model.transformer.h)-rm_layers_num)
    console.print(f"REMOVING LAYERS STARTING AT {layer_start}")
    for i in range(layer_start,len(model.transformer.h)):
        model.transformer.h[i].mlp = nn.Identity()
    after_params = sum([param.numel() for param in model.parameters() if param.requires_grad])
    console.print(f"Original # of parameters {b4_params}. After Rm FFN: {after_params}")
    console.print(f"% params removed: {100*((b4_params-after_params)/b4_params)}")
    return model

class BloomIdentityLayer(nn.Module):
    def __init__(self):
        super(BloomIdentityLayer, self).__init__()
    def forward(self, x, y):
        return x+y #bloom expects the MLP to handle the residual connection

def bloom_ffn_from_model(model, rm_layers_num):
    b4_params = sum([param.numel() for param in model.parameters() if param.requires_grad])
    layer_start = max(0, len(model.transformer.h)-rm_layers_num)
    console.print(f"REMOVING LAYERS STARTING AT {layer_start}")
    for i in range(layer_start,len(model.transformer.h)):
        model.transformer.h[i].mlp = BloomIdentityLayer()#nn.Identity()
    after_params = sum([param.numel() for param in model.parameters() if param.requires_grad])
    console.print(f"Original # of parameters {b4_params}. After Rm FFN: {after_params}")
    console.print(f"% params removed: {100*((b4_params-after_params)/b4_params)}")
    return model

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("model_name", help="name of model to be used")
    parser.add_argument("nshots", type=str, help="number of shots to be used")
    parser.add_argument("--is_extractive", action='store_true', help="whether or not the task is extractive")
    parser.add_argument("--rm_ffn", default=0, type=int, help='how many layers to start removing from the top')
    args = parser.parse_args()
    model_name = args.model_name#sys.argv[1]
    nshots = args.nshots#sys.argv[2]
    extractive = args.is_extractive
    remove_ffn = args.rm_ffn
    console.print('extractive?', extractive, 'removing', remove_ffn, 'layers')
    console.print(model_name, nshots, 'shot(s)')

    dataset = load_bigbench_task('reasoning_about_colored_objects')['default']
    dataset = [dataset[i] for i in range(200)]#dataset = dataset[:200]

    timer_task = timer.add_task("Loading model")
    with timer:
        if 'gpt2' in model_name:#model_name == 'gpt2-xl':
            model, tokenizer = load_gpt2(model_name)
            model = GPT2Wrapper(model, tokenizer)#GPTJWrapper(gptj, tokenizer)
        elif 'gptj' == model_name:
            model, tokenizer = load_gptj()
            model = GPTJWrapper(model, tokenizer)
        elif 'bloom' in model_name:
            model, tokenizer = load_bloom(model_name)
            model = BloomWrapper(model, tokenizer)
            model_name = model_name.split('/')[-1]

    
    timer.stop_task(timer_task)
    timer.update(timer_task, visible=False)
    console.print(len(model.model.transformer.h), "LAYERS IN THE MODEL")
    for r in [0]:#[12,24,36,48,60,70]:
        if r>0:
            if 'bloom' in model_name:
                model.model = bloom_ffn_from_model(model.model, r)
            else:
                model.model = rm_ffn_from_model(model.model, r)

        if not torch.cuda.is_available():
            model.model = model.model.float()
     
        #get_mc_generations(model, dataset)
        if type(nshots)==str and ',' in nshots:
            rnshots = [int(n) for n in nshots.split(',')]
            for n in rnshots:
                console.print("NSHOTS", n)
                nshots = n
                get_open_generations(model, dataset)
                console.print("ACCURACY", (TOTAL_CORRECT/200)*100)
        else:
            nshots = int(nshots)
            get_open_generations(model, dataset, r)
            console.print(f"{r} layers removed ACCURACY", (TOTAL_CORRECT/200)*100)
