#!/usr/bin/env python
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Finetuning the library models for sequence classification on GLUE."""
# You can also adapt this script on your own text classification task. Pointers for this are left as comments.

import logging
import os
import random
import sys
import torch
from dataclasses import dataclass, field
from typing import Optional
from copy import deepcopy
from betty.engine import Engine
from architecture import Architecture_o, Architecture_s, Architecture_n
from betty.configs import Config, EngineConfig
from betty.problems import ImplicitProblem
import numpy as np
from datasets import load_dataset, load_metric
from torch.utils.data.sampler import RandomSampler, SequentialSampler, Sampler
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from torch.utils.data.dataset import Dataset, random_split
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.dataloader import DataLoader
import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    PretrainedConfig,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from optimizer import (
    create_adam_optimizer, 
    create_optimizer_scheduler, 
    add_optimizer_params, 
    create_adam_optimizer_from_args,
    create_lora_adam_optimizer_from_args,
    create_arch_adam_optimizer_from_args
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process
from transformers.utils import check_min_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.4.0")

task_to_keys = {
    "cola": ("sentence", None),
    "mnli": ("premise", "hypothesis"),
    "mrpc": ("sentence1", "sentence2"),
    "qnli": ("question", "sentence"),
    "qqp": ("question1", "question2"),
    "rte": ("sentence1", "sentence2"),
    "sst2": ("sentence", None),
    "stsb": ("sentence1", "sentence2"),
    "wnli": ("sentence1", "sentence2"),
}

logger = logging.getLogger(__name__)


@dataclass
class DataTrainingArguments:
    """
    Arguments pertaining to what data we are going to input our model for training and eval.

    Using `HfArgumentParser` we can turn this class
    into argparse arguments to be able to specify them on
    the command line.
    """

    task_name: Optional[str] = field(
        default=None,
        metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())},
    )
    max_seq_length: int = field(
        default=128,
        metadata={
            "help": "The maximum total input sequence length after tokenization. Sequences longer "
            "than this will be truncated, sequences shorter will be padded."
        },
    )
    overwrite_cache: bool = field(
        default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."}
    )
    pad_to_max_length: bool = field(
        default=True,
        metadata={
            "help": "Whether to pad all samples to `max_seq_length`. "
            "If False, will pad the samples dynamically when batching to the maximum length in the batch."
        },
    )
    max_train_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": "For debugging purposes or quicker training, truncate the number of training examples to this "
            "value if set."
        },
    )
    max_val_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": "For debugging purposes or quicker training, truncate the number of validation examples to this "
            "value if set."
        },
    )
    max_test_samples: Optional[int] = field(
        default=None,
        metadata={
            "help": "For debugging purposes or quicker training, truncate the number of test examples to this "
            "value if set."
        },
    )
    train_file: Optional[str] = field(
        default=None, metadata={"help": "A csv or a json file containing the training data."}
    )
    validation_file: Optional[str] = field(
        default=None, metadata={"help": "A csv or a json file containing the validation data."}
    )
    test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."})
    inner_training_portion: Optional[float] = field(
        default=0.8,
        metadata={"help": "the trainingset portion of inner"},
    )
    def __post_init__(self):
        if self.task_name is not None:
            self.task_name = self.task_name.lower()
            if self.task_name not in task_to_keys.keys():
                raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys()))
        elif self.train_file is None or self.validation_file is None:
            raise ValueError("Need either a GLUE task or a training/validation file.")
        else:
            train_extension = self.train_file.split(".")[-1]
            assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
            validation_extension = self.validation_file.split(".")[-1]
            assert (
                validation_extension == train_extension
            ), "`validation_file` should have the same extension (csv or json) as `train_file`."


@dataclass
class ModelArguments:
    """
    Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
    """

    model_name_or_path: str = field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
    )
    config_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
    )
    tokenizer_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
    )
    cache_dir: Optional[str] = field(
        default=None,
        metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},
    )
    use_fast_tokenizer: bool = field(
        default=True,
        metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."},
    )
    model_revision: str = field(
        default="main",
        metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."},
    )
    use_auth_token: bool = field(
        default=False,
        metadata={
            "help": "Will use the token generated when running `transformers-cli login` (necessary to use this script "
            "with private models)."
        },
    )
    apply_lora: Optional[bool] = field(
        default=False,
        metadata={"help": "Whether to apply LoRA or not."},
    )
    lora_alpha: Optional[int] = field(
        default=None,
        metadata={"help": "LoRA alpha"},
    )
    lora_r: Optional[int] = field(
        default=None,
        metadata={"help": "LoRA r"},
    )
    lora_path: Optional[str] = field(
        default=None,
        metadata={"help": "The file path of LoRA parameters."},
    )
    apply_adapter: Optional[bool] = field(
        default=False,
        metadata={"help": "Whether to apply adapter or not."},
    )
    adapter_path: Optional[str] = field(
        default=None,
        metadata={"help": "The file path of adapter parameters."},
    )
    adapter_type: Optional[str] = field(
        default='houlsby',
        metadata={"help": "houlsby or pfeiffer"},
    )
    adapter_size: Optional[int] = field(
        default=64,
        metadata={"help": "8, 16, 32, 64"},
    )
    apply_bitfit: Optional[bool] = field(
        default=False,
        metadata={"help": "Whether to apply bitfit or not."},
    )
    reg_loss_wgt: Optional[float] = field(
        default=0.0,
        metadata={"help": "Regularization Loss Weight"},
    )
    masking_prob: Optional[float] = field(
        default=0.0,
        metadata={"help": "Token Masking Probability"},
    )
    arch_type: Optional[str] = field(
        default='softmax',
        metadata={"help": "type of architecture"},
    )
    arch_std: Optional[float] = field(
        default=0.0,
        metadata={"help": "init std for architecture"},
    )
    lamb: Optional[float] = field(
        default=1e-4,
        metadata={"help": "lambda for regularizer"},
    )
    cl_bottom: Optional[float] = field(
        default=1e-6,
        metadata={"help": "clamp bottom for architecture"},
    )

@dataclass    
class BilevelTrainingArguments:
    """
    Arguments pertaining to what data we are going to input our model for training and eval.

    Using `HfArgumentParser` we can turn this class
    into argparse arguments to be able to specify them on
    the command line.
    """
    train_batch_size: Optional[int] = field(
        default=16,
        metadata={"help": "train batch size"},
    )
    eval_batch_size: Optional[int] = field(
        default=16,
        metadata={"help": "train batch size"},
    )
    test_batch_size: Optional[int] = field(
        default=16,
        metadata={"help": "train batch size"},
    )
    seed: Optional[int] = field(
        default=0,
        metadata={"help": "random seed"},
    )
    lr: Optional[float] = field(
        default=4e-5,
        metadata={"help": "model learning rate"},
    )
    arch_lr: Optional[float] = field(
        default=4e-5,
        metadata={"help": "arch learning rate"},
    )
    weight_decay: Optional[float] = field(
        default=2e-2,
        metadata={"help": "model weight decay"},
    )
    arch_weight_decay: Optional[float] = field(
        default=2e-2,
        metadata={"help": "arch weight decay"},
    )
    correct_bias: Optional[bool] = field(
        default=True,
        metadata={"help": "correct bias"},
    )
    adam_epislon: Optional[float] = field(
        default=1e-6,
        metadata={"help": "adam epislon"},
    )
    no_decay_bias: Optional[bool] = field(
        default=False,
        metadata={"help": "no decay bias"},
    )
    adam_beta1: Optional[float] = field(
        default=0.9,
        metadata={"help": "adam beta 1"},
    )
    adam_beta2: Optional[float] = field(
        default=0.98,
        metadata={"help": "adam beta 2"},
    )
    scheduler: Optional[str] = field(
        default='linear',
        metadata={"help": "scheduler type"},
    )
    max_step: Optional[int] = field(
        default=5000,
        metadata={"help": "max learning steps"},
    )
    warmup_step: Optional[int] = field(
        default=300,
        metadata={"help": "warmup steps"},
    )
    i_steps: Optional[str] = field(
        default='0',
        metadata={"help": "interval_steps for cycle scheduler"},
    )
    i_lrs: Optional[str] = field(
        default='0.00025',
        metadata={"help": "interval_lrs for cycle scheduler"},
    )
    do_train: Optional[bool] = field(
        default=True,
        metadata={"help": "do training"},
    )
    do_test: Optional[bool] = field(
        default=True,
        metadata={"help": "do test"},
    )
    do_eval: Optional[bool] = field(
        default=True,
        metadata={"help": "do eval"},
    )
    do_predict: Optional[bool] = field(
        default=True, 
        metadata={"help": "do predict"}
    )
    use_deterministic_algorithms: Optional[bool] = field(
        default=False, 
        metadata={"help": "Whether or not to use deterministic algorithms."}
    )
    # output_dir: Optional[str] = field(
    #     default='./mnli/model', 
    #     metadata={"help": "output path"}
    # )
    overwrite_output_dir: Optional[bool] = field(
        default=True, 
        metadata={"help": "overwrite output path"}
    )
    fp16: Optional[bool] = field(
        default=False, 
        metadata={"help": "use fp16"}
    )
    n_gpu: Optional[int] = field(
        default=1, 
        metadata={"help": "num of gpus"}
    )
    local_rank: Optional[int] = field(
        default=-1, 
        metadata={"help": "local rank"}
    )
    cls_dropout: Optional[float] = field(
        default=0.0, 
        metadata={"help": "cls dropout"}
    )
    dataloader_num_workers: Optional[int] = field(
        default=0, 
        metadata={"help": "dataloader num workers"}
    )
    dataloader_drop_last: Optional[bool] = field(
        default=False, 
        metadata={"help": "drop last"}
    )
    dataloader_pin_memory: Optional[bool] = field(
        default=False, 
        metadata={"help": "pin memory"}
    )
    unroll_step: Optional[int] = field(
        default=5, 
        metadata={"help": "inner unroll step"}
    )
    train_iters: Optional[int] = field(
        default=50000, 
        metadata={"help": "train iters"}
    )
    valid_step: Optional[int] = field(
        default=5000, 
        metadata={"help": "valid interval"}
    )
    work_dir: Optional[str] = field(
        default="./checkpoint/roberta-base/", 
        metadata={"help": "work dir"}
    )
    model_init_checkpoint: Optional[str] = field(
        default=None, 
        metadata={"help": "model init checkpoint path"}
    )
    arch_init_checkpoint: Optional[str] = field(
        default=None, 
        metadata={"help": "arch init checkpoint path"}
    )
    reg_lam: Optional[float] = field(
        default=0.0, 
        metadata={"help": "reg lambda"}
    )
    save_step: Optional[int] = field(
        default=9800, 
        metadata={"help": "checkpoint save step"}
    )
class AverageMeter(object):
    """Computes and stores the average and current value
         Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262
    """
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count
        
def torch_pad_and_concatenate(tensor1, tensor2, padding_index=-100):
    """Concatenates `tensor1` and `tensor2` on first axis, applying padding on the second if necessary."""
    if len(tensor1.shape) == 1 or tensor1.shape[1] == tensor2.shape[1]:
        return torch.cat((tensor1, tensor2), dim=0)

    # Let's figure out the new shape
    new_shape = (tensor1.shape[0] + tensor2.shape[0], max(tensor1.shape[1], tensor2.shape[1])) + tensor1.shape[2:]

    # Now let's fill the result tensor
    result = tensor1.new_full(new_shape, padding_index)
    result[: tensor1.shape[0], : tensor1.shape[1]] = tensor1
    result[tensor1.shape[0] :, : tensor2.shape[1]] = tensor2
    return result

def numpy_pad_and_concatenate(array1, array2, padding_index=-100):
    """Concatenates `array1` and `array2` on first axis, applying padding on the second if necessary."""
    if len(array1.shape) == 1 or array1.shape[1] == array2.shape[1]:
        return np.concatenate((array1, array2), dim=0)

    # Let's figure out the new shape
    new_shape = (array1.shape[0] + array2.shape[0], max(array1.shape[1], array2.shape[1])) + array1.shape[2:]

    # Now let's fill the result tensor
    result = np.full_like(array1, padding_index, shape=new_shape)
    result[: array1.shape[0], : array1.shape[1]] = array1
    result[array1.shape[0] :, : array2.shape[1]] = array2
    return result

def nested_numpify(tensors):
    "Numpify `tensors` (even if it's a nested list/tuple of tensors)."
    if isinstance(tensors, (list, tuple)):
        return type(tensors)(nested_numpify(t) for t in tensors)
    return tensors.cpu().numpy()

def nested_concat(tensors, new_tensors, padding_index=-100):
    """
    Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or
    nested list/tuples of tensors.
    """
    assert type(tensors) == type(
        new_tensors
    ), f"Expected `tensors` and `new_tensors` to have the same type but found {type(tensors)} and {type(new_tensors)}."
    if isinstance(tensors, (list, tuple)):
        return type(tensors)(nested_concat(t, n, padding_index=padding_index) for t, n in zip(tensors, new_tensors))
    elif isinstance(tensors, torch.Tensor):
        return torch_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
    elif isinstance(tensors, np.ndarray):
        return numpy_pad_and_concatenate(tensors, new_tensors, padding_index=padding_index)
    else:
        raise TypeError(f"Unsupported type for concatenation: got {type(tensors)}")
    
def nested_truncate(tensors, limit):
    "Truncate `tensors` at `limit` (even if it's a nested list/tuple of tensors)."
    if isinstance(tensors, (list, tuple)):
        return type(tensors)(nested_truncate(t, limit) for t in tensors)
    return tensors[:limit]

def nested_detach(tensors):
        "Detach `tensors` (even if it's a nested list/tuple of tensors)."
        if isinstance(tensors, (list, tuple)):
            return type(tensors)(nested_detach(t) for t in tensors)
        return tensors.detach()

def model_state_dict_loader(model, init_checkpoint):
    loaded_paras = torch.load(init_checkpoint)
    loaded_paras = loaded_paras['model_state_dict']
    state_dict = deepcopy(model.state_dict())
    loaded_paras_names = list(loaded_paras.keys())
    model_paras_names = list(state_dict.keys())
    keys_model = [key for key in model_paras_names if "classifier" not in key]
    keys_dict = [key for key in loaded_paras_names if "classifier" not in key]
    for i in range(len(keys_dict)):
        state_dict[keys_model[i]] = loaded_paras[keys_dict[i]]
    model.load_state_dict(state_dict)
    
def arch_state_dict_loader1(arch, init_checkpoint):
    loaded_paras = torch.load(init_checkpoint)
    loaded_paras = loaded_paras['arch_state_dict']
    arch.load_state_dict(loaded_paras)
    
def arch_state_dict_loader(arch, init_checkpoint):
    loaded_paras = torch.load(init_checkpoint)
    loaded_paras = loaded_paras['arch_state_dict']
    state_dict = deepcopy(arch.state_dict())
    loaded_paras_names = list(loaded_paras.keys())
    model_paras_names = list(state_dict.keys())
    keys_model = [key for key in model_paras_names]
    keys_dict = [key for key in loaded_paras_names]
    for i in range(len(loaded_paras_names)):
        state_dict[keys_model[i]] = loaded_paras[keys_dict[i]]
    arch.load_state_dict(state_dict)
    
def compute_orth_regu(model, regu_weight=0.1):
    # The function to compute orthongonal regularization for SVDLinear in `model`. 
    regu_loss, num_param = 0., 0
    for n,p in model.named_parameters():
        if "lora_A" in n or "lora_B" in n:
            para_cov = p @ p.T if "lora_A" in n else p.T @ p 
            I = torch.eye(*para_cov.size(), out=torch.empty_like(para_cov))
            I.requires_grad = False
            regu_loss += torch.norm(para_cov-I, p="fro")
            num_param += 1
    return regu_weight*regu_loss/num_param

def main():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, BilevelTrainingArguments))
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        model_args, data_args, training_args = parser.parse_args_into_dataclasses()

    torch.use_deterministic_algorithms(training_args.use_deterministic_algorithms)
    logger.info("use_deterministic_algorithms: " + str(torch.are_deterministic_algorithms_enabled()))
    training_args.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')


    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s -   %(message)s",
        datefmt="%m/%d/%Y %H:%M:%S",
        handlers=[logging.StreamHandler(sys.stdout)],
    )
    logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)

    # Log on each process the small summary:
    logger.warning(
        f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
        + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}"
    )
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()
    logger.info(f"Training/evaluation parameters {training_args}")

    # Set seed before initializing model.
    set_seed(training_args.seed)

    # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
    # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
    #
    # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the
    # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named
    # label if at least two columns are provided.
    #
    # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
    # single column. You can easily tweak this behavior (see below)
    #
    # In distributed training, the load_dataset function guarantee that only one local process can concurrently
    # download the dataset.
    if data_args.task_name is not None:
        # Downloading and loading a dataset from the hub.
        datasets = load_dataset("glue", data_args.task_name)

    # Labels
    if data_args.task_name is not None:
        is_regression = data_args.task_name == "stsb"
        if not is_regression:
            label_list = datasets["train"].features["label"].names
            num_labels = len(label_list)
        else:
            num_labels = 1
    else:
        # Trying to have good defaults here, don't hesitate to tweak to your needs.
        is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"]
        if is_regression:
            num_labels = 1
        else:
            # A useful fast method:
            # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.unique
            label_list = datasets["train"].unique("label")
            label_list.sort()  # Let's sort it for determinism
            num_labels = len(label_list)

    # Load pretrained model and tokenizer
    #
    # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    config = AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path,
        num_labels=num_labels,
        finetuning_task=data_args.task_name,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
        cls_dropout=training_args.cls_dropout,
        apply_lora=model_args.apply_lora,
        lora_alpha=model_args.lora_alpha,
        lora_r=model_args.lora_r,
        apply_adapter=model_args.apply_adapter,
        adapter_type=model_args.adapter_type,
        adapter_size=model_args.adapter_size,
        reg_loss_wgt=model_args.reg_loss_wgt,
        masking_prob=model_args.masking_prob,
    )
    tokenizer = AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
        cache_dir=model_args.cache_dir,
        use_fast=model_args.use_fast_tokenizer,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    model = AutoModelForSequenceClassification.from_pretrained(
        model_args.model_name_or_path,
        from_tf=bool(".ckpt" in model_args.model_name_or_path),
        config=config,
        cache_dir=model_args.cache_dir,
        revision=model_args.model_revision,
        use_auth_token=True if model_args.use_auth_token else None,
    )
    
    if model_args.model_name_or_path == 'roberta-base' or model_args.model_name_or_path =='microsoft/deberta-v3-base':
        hidden_layers = 12
    elif model_args.model_name_or_path == 'roberta-large':
        hidden_layers = 24
    elif model_args.model_name_or_path == 'microsoft/deberta-v2-xxlarge':
        hidden_layers = 48
    if model_args.arch_type == 'softmax':
        arch = Architecture_s(hidden_layers, model_args)
    elif model_args.arch_type == 'binary':
        arch = Architecture_o(hidden_layers, model_args)
    elif model_args.arch_type == 'normal':
        arch = Architecture_n(hidden_layers, model_args)
    if data_args.task_name in ["mrpc", "rte", "stsb"]:
        model_state_dict_loader(model, training_args.model_init_checkpoint)
        arch_state_dict_loader(arch, training_args.arch_init_checkpoint)
    
    model_task_work_dir = os.path.join(training_args.work_dir, data_args.task_name)
    
    # Preprocessing the datasets
    if data_args.task_name is not None:
        sentence1_key, sentence2_key = task_to_keys[data_args.task_name]
    else:
        # Again, we try to have some nice defaults but don't hesitate to tweak to your use case.
        non_label_column_names = [name for name in datasets["train"].column_names if name != "label"]
        if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
            sentence1_key, sentence2_key = "sentence1", "sentence2"
        else:
            if len(non_label_column_names) >= 2:
                sentence1_key, sentence2_key = non_label_column_names[:2]
            else:
                sentence1_key, sentence2_key = non_label_column_names[0], None

    # Padding strategy
    if data_args.pad_to_max_length:
        padding = "max_length"
    else:
        # We will pad later, dynamically at batch creation, to the max sequence length in each batch
        padding = False

    # Some models have set the order of the labels to use, so let's make sure we do use it.
    label_to_id = None
    if (
        model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
        and data_args.task_name is not None
        and not is_regression
    ):
        # Some have all caps in their config, some don't.
        label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()}
        if list(sorted(label_name_to_id.keys())) == list(sorted(label_list)):
            label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)}
        else:
            logger.warn(
                "Your model seems to have been trained with labels, but they don't match the dataset: ",
                f"model labels: {list(sorted(label_name_to_id.keys()))}, dataset labels: {list(sorted(label_list))}."
                "\nIgnoring the model labels as a result.",
            )
    elif data_args.task_name is None and not is_regression:
        label_to_id = {v: i for i, v in enumerate(label_list)}

    if data_args.max_seq_length > tokenizer.model_max_length:
        logger.warn(
            f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
            f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
        )
    max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)

    def preprocess_function(examples):
        # Tokenize the texts
        args = (
            (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
        )
        result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)

        # Map labels to IDs (not necessary for GLUE tasks)
        if label_to_id is not None and "label" in examples:
            result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]]
        return result

    datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache)
    if training_args.do_train:
        if "train" not in datasets:
            raise ValueError("--do_train requires a train dataset")
        train_dataset = datasets["train"]
        if data_args.max_train_samples is not None:
            train_dataset = train_dataset.select(range(data_args.max_train_samples))

    if training_args.do_eval:
        if "validation" not in datasets and "validation_matched" not in datasets:
            raise ValueError("--do_eval requires a validation dataset")
        eval_dataset = datasets["validation_matched" if data_args.task_name == "mnli" else "validation"]
        eval_dataset_mm = datasets["validation_mismatched" if data_args.task_name == "mnli" else "validation"]
        if data_args.max_val_samples is not None:
            eval_dataset = eval_dataset.select(range(data_args.max_val_samples))

    # Log a few random samples from the training set:
    if training_args.do_train:
        for index in random.sample(range(len(train_dataset)), 3):
            logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")

    # Get the metric function
    if data_args.task_name is not None:
        metric = load_metric("glue", data_args.task_name)
    # TODO: When datasets metrics include regular accuracy, make an else here and remove special branch from
    # compute_metrics

    # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
    def compute_metrics(p: EvalPrediction):
        preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
        preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1)
        if data_args.task_name is not None:
            result = metric.compute(predictions=preds, references=p.label_ids)
            if len(result) > 1:
                result["combined_score"] = np.mean(list(result.values())).item()
            return result
        elif is_regression:
            return {"mse": ((preds - p.label_ids) ** 2).mean().item()}
        else:
            return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}
        
    
    
    
    # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
    if data_args.pad_to_max_length:
        data_collator = default_data_collator
    elif training_args.fp16:
        data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8)
    else:
        data_collator = None

    def seed_worker(worker_id):
            worker_seed = torch.initial_seed() % 2**32
            np.random.seed(worker_seed)
            random.seed(worker_seed)

    g = torch.Generator()
    g.manual_seed(training_args.seed)

    inner_portion = int(len(train_dataset) * data_args.inner_training_portion)
    outer_portion = len(train_dataset) - inner_portion
    train_dataset_inner, train_dataset_outer = random_split(train_dataset, [inner_portion, outer_portion], g)
    
    train_dataloader_inner = DataLoader(
        train_dataset_inner,
        batch_size=training_args.train_batch_size,
        collate_fn=data_collator,
        drop_last=training_args.dataloader_drop_last,
        num_workers=training_args.dataloader_num_workers,
        pin_memory=training_args.dataloader_pin_memory,
        worker_init_fn=seed_worker,
        generator=g,
        #sampler=torch.utils.data.distributed.DistributedSampler(train_dataset, seed=training_args.seed),
    )
    
    train_dataloader_outer = DataLoader(
        train_dataset_outer,
        batch_size=training_args.train_batch_size,
        collate_fn=data_collator,
        drop_last=training_args.dataloader_drop_last,
        num_workers=training_args.dataloader_num_workers,
        pin_memory=training_args.dataloader_pin_memory,
        worker_init_fn=seed_worker,
        generator=g,
        #sampler=torch.utils.data.distributed.DistributedSampler(train_dataset, seed=training_args.seed),
    )
    
    eval_dataloader = DataLoader(
        eval_dataset,
        batch_size=training_args.eval_batch_size,
        collate_fn=data_collator,
        drop_last=training_args.dataloader_drop_last,
        num_workers=training_args.dataloader_num_workers,
        pin_memory=training_args.dataloader_pin_memory,
        worker_init_fn=seed_worker,
        generator=g,
        #sampler=torch.utils.data.distributed.DistributedSampler(eval_dataset, seed=training_args.seed),
    )
    
    
    eval_dataloader_mm = DataLoader(
        eval_dataset_mm,
        batch_size=training_args.eval_batch_size,
        collate_fn=data_collator,
        drop_last=training_args.dataloader_drop_last,
        num_workers=training_args.dataloader_num_workers,
        pin_memory=training_args.dataloader_pin_memory,
        worker_init_fn=seed_worker,
        generator=g,
        #sampler=torch.utils.data.distributed.DistributedSampler(eval_dataset, seed=training_args.seed),
    )
    
    print(f"eval_num: {len(eval_dataset)}")
    print(f"eval_mm_num: {len(eval_dataset_mm)}")

    
    
    class Inner(ImplicitProblem):
        # def forward(self, batch_input, alphas, lm_labels, lm_mask, label_smooth):
        #     alphas = self.outer()
        #     return self.module(batch_input, alphas, lm_labels, lm_mask, None, None, label_smooth, False)
                
        def training_step(self, batch):       
            data = batch
            data = {key: value for key, value in data.items()}
            _input = data['input_ids'].to(training_args.device)
            _target = data['labels'].to(training_args.device)
            _msk = data['attention_mask'].to(training_args.device)
            alphas = self.outer()
            _lm_loss = self.module(alphas=alphas, input_ids=_input, attention_mask=_msk, labels=_target) 
            #print(_lm_loss)
            _lm_loss, output = _lm_loss
            reg = compute_orth_regu(self.module, training_args.reg_lam)
            _lm_loss += reg
            logits = output
            logits = nested_detach(logits)
            if data_args.task_name != 'stsb':
                preds = torch.argmax(logits, axis=1)
                # result = metric.compute(predictions=preds, references=_target.item())
                # if len(result) > 1:
                #     result['combined_score'] = torch.mean(list(result.values())).item()
                #     print(result)
                # else:
                inner_acc = torch.mean((preds == _target).to(torch.float)).item()
                #print(logits)
                #avg_lm_loss_inner.update(_lm_loss.item())
            return _lm_loss
        
        def configure_train_data_loader(self):
            return train_dataloader_inner

            
            
    #avg_lm_loss_outer = AverageMeter()
    class Outer(ImplicitProblem):
        def forward(self):
            return self.module()
        
        def training_step(self, batch):       
            data = batch
            data = {key: value for key, value in data.items()}
            _input = data['input_ids'].to(training_args.device)
            _target = data['labels'].to(training_args.device)
            _msk = data['attention_mask'].to(training_args.device)
            alphas = self.module()
            #print(alphas[0][0])
            _lm_loss = self.inner.module(alphas, input_ids=_input, attention_mask=_msk, labels=_target)
            _lm_loss, output = _lm_loss
            #_lm_loss += compute_orth_regu(model, regu_weight=0.1)
            logits = output
            logits = nested_detach(logits)
            if data_args.task_name != 'stsb':
                preds = torch.argmax(logits, axis=1)
                outer_acc = torch.mean((preds == _target).to(torch.float)).item()
                #print(logits)
                #avg_lm_loss_inner.update(_lm_loss.item())
            return _lm_loss
        
        def configure_train_data_loader(self):
            return train_dataloader_outer
        
    
    class LoraEngine(Engine):
        @torch.no_grad()
        def validation(self):
            avg_lm_loss = AverageMeter()
            avg_lm_acc = AverageMeter()
            samples_num = len(eval_dataloader.dataset)
            batch_num = len(eval_dataloader.dataset)//training_args.eval_batch_size
            left_over = samples_num - len(eval_dataloader.dataset)//training_args.eval_batch_size * training_args.eval_batch_size
            # samples_num_mm = len(eval_dataloader_mm.dataset)
            # batch_num_mm = len(eval_dataloader_mm.dataset)//training_args.eval_batch_size
            # left_over_mm = samples_num_mm - len(eval_dataloader_mm.dataset)//training_args.eval_batch_size * training_args.eval_batch_size
            with torch.no_grad():
                if data_args.task_name == "mnli":
                    losses_host: torch.Tensor = None
                    preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
                    labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
                    for eval_data in [eval_dataloader, eval_dataloader_mm]:
                        for idx, data in enumerate(eval_data):
                            data = {key: value for key, value in data.items()}

                            _input = data['input_ids'].to(training_args.device)
                            _target = data['labels'].to(training_args.device)
                            _msk = data['attention_mask'].to(training_args.device)
                            alphas = self.outer()
                            _loss = self.inner.module(alphas, input_ids=_input, attention_mask=_msk, labels=_target)
                            _loss, output = _loss
                            logits = output
                            logits = nested_detach(logits)
                            ax = 1
                            if data_args.task_name == 'stsb':
                                ax = 0
                            preds = torch.argmax(logits, axis=ax)
                            if _loss is not None:
                                losses = _loss.repeat(len(_target))
                                losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
                            if logits is not None:
                                preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
                            if _target is not None:
                                labels_host = _target if labels_host is None else nested_concat(labels_host, _target, padding_index=-100)
                            
                    losses_host = nested_numpify(losses_host)
                    preds_host = nested_numpify(preds_host)
                    labels_host = nested_numpify(labels_host)
                    samples = len(eval_dataloader.dataset) + len(eval_dataloader_mm.dataset)
                    eval_loss = nested_truncate(losses_host, samples)
                    preds = nested_truncate(preds_host, samples)
                    label_ids = nested_truncate(labels_host, samples) 
                    metrics = compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
                    print(metrics)
                else:
                    losses_host: torch.Tensor = None
                    preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
                    labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
                    for idx, data in enumerate(eval_dataloader):
                        data = {key: value for key, value in data.items()}

                        _input = data['input_ids'].to(training_args.device)
                        _target = data['labels'].to(training_args.device)
                        _msk = data['attention_mask'].to(training_args.device)
                        #print(idx, len(_input))
                        alphas = self.outer()
                        _loss = self.inner.module(alphas, input_ids=_input, attention_mask=_msk, labels=_target)
                        _loss, output = _loss
                        logits = output
                        logits = nested_detach(logits)
                        ax = 1
                        if data_args.task_name == 'stsb':
                            ax = 0
                        preds = torch.argmax(logits, axis=ax)
                        if _loss is not None:
                            losses = _loss.repeat(len(_target))
                            losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
                        if logits is not None:
                            preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
                        if _target is not None:
                            labels_host = _target if labels_host is None else nested_concat(labels_host, _target, padding_index=-100)
                        # samples = len(eval_dataloader.dataset)
                        # eval_loss = nested_truncate(losses_host, samples)
                        # preds = nested_truncate(preds_host, samples)
                        # label_ids = nested_truncate(labels_host, samples) 
                        _acc = torch.mean((preds == _target).to(torch.float)).item()
                        if idx == batch_num:
                            avg_lm_loss.update(_loss, left_over/training_args.eval_batch_size)
                            avg_lm_acc.update(_acc, left_over/training_args.eval_batch_size)
                        else:
                            avg_lm_loss.update(_loss)
                            avg_lm_acc.update(_acc)
                    #avg_lm_loss.update(loss.item())

                    # if idx % 100 == 0:
                    #     print('eval samples:', idx, 'loss:', loss.float())
                    print(avg_lm_acc.avg)
                    losses_host = nested_numpify(losses_host)
                    preds_host = nested_numpify(preds_host)
                    labels_host = nested_numpify(labels_host)
                    samples = len(eval_dataloader.dataset)
                    # print(samples)
                    # print(len(labels_host))
                    eval_loss = nested_truncate(losses_host, samples)
                    preds = nested_truncate(preds_host, samples)
                    label_ids = nested_truncate(labels_host, samples) 
                    metrics = compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
                    print(metrics)
                    
                #print('average loss', avg_lm_loss.avg)
            if self.inner.count == training_args.save_step and data_args.task_name == 'mnli':
                model_path = os.path.join(model_task_work_dir, f'model.{self.inner.count}.pt')
                print('saving checkpoint', model_path)
                torch.save({'model_state_dict': self.inner.module.state_dict()}, model_path)
                arch_path = os.path.join(model_task_work_dir, f'arch.{self.inner.count}.pt')
                print('saving checkpoint', arch_path)
                torch.save({'arch_state_dict': self.outer.module.state_dict()}, arch_path)
            return 
    inner_optimizer = create_lora_adam_optimizer_from_args(model, training_args)
    #lm_net, inner_optimizer = distributed_opt(args, lm_net, inner_optimizer, grad_acc=args.grad_acc)
    inner_scheduler = create_optimizer_scheduler(inner_optimizer, training_args)
    
    outer_optimizer = create_arch_adam_optimizer_from_args(arch, training_args, None)
    #arch, outer_optimizer = distributed_opt(args, arch, outer_optimizer, grad_acc=args.grad_acc)
    outer_scheduler = create_optimizer_scheduler(outer_optimizer, training_args)
    outer_config = Config(type="darts", retain_graph=True, gradient_accumulation=1)
    inner_config = Config(type="darts", unroll_steps=training_args.unroll_step, retain_graph=True, gradient_accumulation=1)
    engine_config = EngineConfig(train_iters=training_args.train_iters, valid_step=training_args.valid_step, roll_back=True)
    outer = Outer(name="outer", module=arch, optimizer=outer_optimizer, scheduler=outer_scheduler, config=outer_config)
    inner = Inner(name="inner", module=model, optimizer=inner_optimizer, scheduler=inner_scheduler, config=inner_config)
    problems = [outer, inner]
    l2u = {inner: [outer]}
    u2l = {outer: [inner]}
    dependencies = {"l2u": l2u, "u2l": u2l}
    engine = LoraEngine(config=engine_config, problems=problems, dependencies=dependencies)
    engine.run()

def _mp_fn(index):
    # For xla_spawn (TPUs)
    main()


if __name__ == "__main__":
    main()