# Copyright (c) 2024, NVIDIA CORPORATION.  All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto.  Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.

import os
import sys
import wandb

import fire
import torch
import transformers
from datasets import load_dataset
from typing import List, Optional, Union

from peft import (  # noqa: E402
    GroupLoraConfig,
    get_peft_model,
    get_peft_model_state_dict,
    prepare_model_for_kbit_training,
    PeftModel, TaskType,
)
from transformers import AutoModelForCausalLM, AutoTokenizer, LlamaTokenizer, AutoModel, AutoConfig  # noqa: F402
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR

os.environ["WANDB_MODE"] = "offline"

def train(
        deepspeed: Optional[str] = None,
        # model/data params
        base_model: str = "",  # the only required argument
        data_path: str = "",
        output_dir: str = "",
        load_8bit: bool = False,
        # training hyperparams
        per_device_train_batch_size: int = 2,
        gradient_accumulation_steps: int = 4,
        num_epochs: int = 3,
        learning_rate: float = 2e-4,
        weight_decay: float = 0.0,
        cutoff_len: int = 256,
        val_set_size: int = 2000,
        use_gradient_checkpointing: bool = True,
        logging_steps: int = 10,
        eval_step: int = 200,
        save_step: int = 200,
        # group_lora hyperparams
        group_size: int = 2,
        group_r: int = 32,
        group_alpha: int = 32,
        group_dropout: float = 0.05,
        target_modules: List[str] = None,
        # llm hyperparams
        load_best_model_at_end: bool = True,
        train_on_inputs: bool = True,  # if False, masks out inputs in loss
        group_by_length: bool = False,  # faster, but produces an odd training loss curve
):
    print(
        f"Finetuning model with params:\n"
        f"base_model: {base_model}\n"
        f"data_path: {data_path}\n"
        f"output_dir: {output_dir}\n"
        f"per_device_train_batch_size: {per_device_train_batch_size}\n"
        f"gradient_accumulation_steps: {gradient_accumulation_steps}\n"
        f"num_epochs: {num_epochs}\n"
        f"learning_rate: {learning_rate}\n"
        f"weight_decay: {weight_decay}\n"
        f"cutoff_len: {cutoff_len}\n"
        f"val_set_size: {val_set_size}\n"
        f"use_gradient_checkpointing: {use_gradient_checkpointing}\n"
        f"group_size: {group_size}\n"
        f"group_r: {group_r}\n"
        f"group_alpha: {group_alpha}\n"
        f"group_dropout: {group_dropout}\n"
        f"target_modules: {target_modules}\n"
        f"load_best_model_at_end: {load_best_model_at_end}\n"
    )

    # wandb
    wandb.init(
        project="commonsense_170k",
        name=f"group{group_size}_r{group_r}",
    )

    assert (
        base_model
    ), "Please specify a --base_model, e.g. --base_model='decapoda-research/llama-7b-hf'"

    device_map = "auto"
    world_size = int(os.environ.get("WORLD_SIZE", 1))
    ddp = world_size != 1
    if ddp:
        device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}

    if load_8bit:
        model = AutoModelForCausalLM.from_pretrained(
            base_model,
            load_in_8bit=load_8bit,
            torch_dtype=torch.float16,
            device_map=device_map,
            trust_remote_code=True,
        )
    else:
        model = AutoModelForCausalLM.from_pretrained(
            base_model,
            load_in_8bit=False,
            torch_dtype=torch.float16,
            device_map={"": int(os.environ.get("LOCAL_RANK") or 0)},
            trust_remote_code=True,
        )

    if model.config.model_type == "llama":
        # Due to the name of transformers' LlamaTokenizer, we have to do this
        # need to handle llama 3 separately
        if "Llama-3" in base_model:
            print("load llama-3 tokenizer")
            tokenizer = AutoTokenizer.from_pretrained(base_model)
        else:
            tokenizer = LlamaTokenizer.from_pretrained(base_model)
    else:
        tokenizer = AutoTokenizer.from_pretrained(base_model, trust_remote_code=True)

    tokenizer.pad_token_id = (
        0  # unk. we want this to be different from the eos token
    )
    tokenizer.padding_side = "left"  # Allow batched inference

    def tokenize(prompt, add_eos_token=True):
        # there's probably a way to do this with the tokenizer settings
        # but again, gotta move fast
        result = tokenizer(
            prompt,
            truncation=True,
            max_length=cutoff_len,
            padding=False,
            return_tensors=None,
        )
        if (
                result["input_ids"][-1] != tokenizer.eos_token_id
                and len(result["input_ids"]) < cutoff_len
                and add_eos_token
        ):
            result["input_ids"].append(tokenizer.eos_token_id)
            if "chatglm" not in base_model:
                result["attention_mask"].append(1)

        result["labels"] = result["input_ids"].copy()

        if "chatglm" in base_model:
            return {"input_ids": result["input_ids"], "labels": result["labels"]}
        else:
            return result

    def generate_and_tokenize_prompt(data_point):
        full_prompt = generate_prompt(data_point)
        tokenized_full_prompt = tokenize(full_prompt)
        if not train_on_inputs:
            user_prompt = generate_prompt({**data_point, "output": ""})
            tokenized_user_prompt = tokenize(user_prompt, add_eos_token=False)
            user_prompt_len = len(tokenized_user_prompt["input_ids"])

            tokenized_full_prompt["labels"] = [
                                                  -100
                                              ] * user_prompt_len + tokenized_full_prompt["labels"][
                                                                    user_prompt_len:
                                                                    ]  # could be sped up, probably
        return tokenized_full_prompt

    def get_last_checkpoint(checkpoint_dir):
        if os.path.isdir(checkpoint_dir):
            is_completed = os.path.exists(os.path.join(checkpoint_dir, 'completed'))
            if is_completed: return None  # already finished
            max_step = 0
            for filename in os.listdir(checkpoint_dir):
                if os.path.isdir(os.path.join(checkpoint_dir, filename)) and filename.startswith(PREFIX_CHECKPOINT_DIR):
                    max_step = max(max_step, int(filename.replace(PREFIX_CHECKPOINT_DIR + '-', '')))
            if max_step == 0: return None
            latest_ckpt_dir = os.path.join(checkpoint_dir, f'{PREFIX_CHECKPOINT_DIR}-{max_step}')
            print(f"Found a previous checkpoint at: {checkpoint_dir}")
            return latest_ckpt_dir
        return None  # first training

    def get_model_num_layers(model_name_or_path):
        """
        Get the total number of layers for a Hugging Face model (supports mainstream models like GPT, BERT, LLaMA, DeepSeek, etc.).
        """
        config = AutoConfig.from_pretrained(model_name_or_path)

        if hasattr(config, "num_hidden_layers"):  # BERT, RoBERTa, etc.
            return config.num_hidden_layers
        elif hasattr(config, "n_layer"):  # GPT etc.
            return config.n_layer
        elif hasattr(config, "num_layers"):  # T5, BART, etc.
            return config.num_layers
        elif hasattr(config, "n_layers"):  # LLaMA etc.
            return config.n_layers
        elif hasattr(config, "num_transformer_layers"):  # DeepSeek, etc.
            return config.num_transformer_layers
        else:
            raise ValueError(
                "Unable to determine the number of layers from the model configuration. "
                "Please check the model's config file or documentation. "
                "If you are using a custom model, you may need to modify the code "
                "to extract the number of layers based on the `base_model`."
            )

    model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=use_gradient_checkpointing)
    print(model)

    resume_from_checkpoint = get_last_checkpoint(output_dir)
    if resume_from_checkpoint is not None:
        print(f"Loading adapters from {resume_from_checkpoint}.")
        model = PeftModel.from_pretrained(model, resume_from_checkpoint, is_trainable=True)
    else:
        print(f'Init GroupLoRA modules...')
        num_layers = get_model_num_layers(base_model)
        print(f"Total number of layers: {num_layers}")
        config = GroupLoraConfig(
            task_type=TaskType.CAUSAL_LM,
            target_modules=target_modules,
            inference_mode=False,
            num_layers=num_layers,
            group_size=group_size,
            r=group_r,
            alpha=group_alpha,
            dropout=group_dropout,
        )
        model = get_peft_model(model, config)

    model.print_trainable_parameters()

    if data_path.endswith(".json"):  # todo: support jsonl
        data = load_dataset("json", data_files=data_path)
    else:
        data = load_dataset(data_path)
    if val_set_size > 0:
        train_val = data["train"].train_test_split(
            test_size=val_set_size, shuffle=True, seed=42
        )
        train_data = (
            train_val["train"].shuffle().map(generate_and_tokenize_prompt, num_proc=32)
        )
        val_data = (
            train_val["test"].shuffle().map(generate_and_tokenize_prompt, num_proc=32)
        )
    else:
        train_data = data["train"].shuffle().map(generate_and_tokenize_prompt, num_proc=32)
        val_data = None

    if not ddp and torch.cuda.device_count() > 1:
        # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
        model.is_parallelizable = True
        model.model_parallel = True

    trainer = transformers.Trainer(
        model=model,
        train_dataset=train_data,
        eval_dataset=val_data,
        args=transformers.TrainingArguments(
            deepspeed=deepspeed,
            per_device_train_batch_size=per_device_train_batch_size,
            gradient_accumulation_steps=gradient_accumulation_steps,
            warmup_steps=1000,
            num_train_epochs=num_epochs,
            learning_rate=learning_rate,
            weight_decay=weight_decay,
            fp16=True,
            logging_steps=logging_steps,
            optim="adamw_torch",
            evaluation_strategy="steps" if val_set_size > 0 else "no",
            save_strategy="steps",
            eval_steps=eval_step if val_set_size > 0 else None,
            save_steps=save_step,
            output_dir=output_dir,
            save_total_limit=1,
            load_best_model_at_end=load_best_model_at_end,
            ddp_find_unused_parameters=False if ddp else None,
            group_by_length=group_by_length,
            report_to="wandb",
        ),
        data_collator=transformers.DataCollatorForSeq2Seq(
            tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding=True
        ),
    )
    model.config.use_cache = False

    old_state_dict = model.state_dict
    model.state_dict = (
        lambda self, *_, **__: get_peft_model_state_dict(
            self, old_state_dict()
        )
    ).__get__(model, type(model))

    if torch.__version__ >= "2" and sys.platform != "win32":
        model = torch.compile(model)

    trainer.train(resume_from_checkpoint=resume_from_checkpoint)
    model = model.merge_and_unload()
    model.save_pretrained(output_dir)
    tokenizer.save_pretrained(output_dir)

    # wandb.finish()


def generate_prompt(data_point):
    # sorry about the formatting disaster gotta move fast
    if data_point["input"]:
        return f"""Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request. 

                ### Instruction:
                {data_point["instruction"]}

                ### Input:
                {data_point["input"]}

                ### Response:
                {data_point["output"]}"""  # noqa: E501
    else:
        return f"""Below is an instruction that describes a task. Write a response that appropriately completes the request.  

                ### Instruction:
                {data_point["instruction"]}

                ### Response:
                {data_point["output"]}"""  # noqa: E501


if __name__ == "__main__":
    fire.Fire(train)