"""
python examples/scripts/sft.py \
    --model_name_or_path="facebook/...-350m" \
    --report_to="wandb" \
    --learning_rate=1.41e-5 \
    --per_device_train_batch_size=64 \
    --gradient_accumulation_steps=16 \
    --output_dir="sft_openassistant-guanaco" \
    --logging_steps=1 \
    --num_train_epochs=3 \
    --max_steps=-1 \
    --push_to_hub \
    --gradient_checkpointing

python examples/scripts/sft.py \
    --model_name_or_path="facebook/...-350m" \
    --report_to="wandb" \
    --learning_rate=1.41e-5 \
    --per_device_train_batch_size=64 \
    --gradient_accumulation_steps=16 \
    --output_dir="sft_openassistant-guanaco" \
    --logging_steps=1 \
    --num_train_epochs=3 \
    --max_steps=-1 \
    --push_to_hub \
    --gradient_checkpointing \
    --use_peft \
    --lora_r=64 \
    --lora_alpha=16
"""

import logging
import multiprocessing
import os
from contextlib import nullcontext

from trl.commands.cli_utils import init_zero_verbose, SFTScriptArguments, TrlParser
from trl.env_utils import strtobool

TRL_USE_RICH = strtobool(os.getenv("TRL_USE_RICH", "0"))

if TRL_USE_RICH:
    init_zero_verbose()
    FORMAT = "%(message)s"

    from rich.console import Console
    from rich.logging import RichHandler

import torch
from datasets import load_dataset
from transformers import AutoModelForCausalLM, AutoTokenizer
from tqdm.rich import tqdm
from trl import (
    SFTConfig,
    SFTTrainer,
    ModelConfig,
    RichProgressCallback,
    get_kbit_device_map,
    get_peft_config,
    get_quantization_config,
    get_kbit_device_map
)

import tempfile
import os
from fastchat.train.my_hdfs_io import hcopy, hmkdir
def load_hdfs_path(ckpt_path):
    if ckpt_path.startswith("hdfs"):
        tmp_dir = os.path.join(
            tempfile.gettempdir(), os.path.basename(ckpt_path)
        )
        local_dir = tmp_dir
        hcopy(ckpt_path, local_dir)
    else:
        local_dir = ckpt_path
    return local_dir


local_rank = None

tqdm.pandas()
if TRL_USE_RICH:
    logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()], level=logging.INFO)

def rank0_init_wandb(task_name = "tinyllama-code-sft"):
    if local_rank == 0:
        import wandb
        wandb.init(project="....fschat.sft", name=task_name, notes=task_name)



from dataclasses import dataclass, field
@dataclass
class CustomArguments(SFTScriptArguments):
    my_task_name: str = field(default="tinyllama-code-sft", metadata={"help": "Description of my task name for wandb"})
    save_hdfs_path: str = field(default="....../home/.../.../user/.../metadata/generate/tmp", metadata={"help": "save hdfs path"})
    max_length: int = field(default = -1, metadata={"help": "from dpo_config, will be replaced as max_seq_length"})
    max_prompt_length: int = field(default = -1, metadata={"help": "from dpo_config, will not be used"})
    load_lora_local_path: str = field(default="", metadata={"help": "no use"})


if __name__ == "__main__":
    parser = TrlParser((CustomArguments, SFTConfig, ModelConfig))
    args, training_args, model_config = parser.parse_args_and_config()
    model_config.model_name_or_path = load_hdfs_path(model_config.model_name_or_path)
    args.dataset_name = load_hdfs_path(args.dataset_name)
    if args.max_length != -1 and not training_args.max_seq_length:
        print("CMD: ", "args.max_length: ", str(args.max_length), " training_args.max_seq_length: ", str(training_args.max_seq_length))
        training_args.max_seq_length = args.max_length
        print("SFTConfig use `max_seq_length` instead of `max_length`, will use the `max_length` to replace `max_seq_length`")
        print("args.max_seq_length:", str(training_args.max_seq_length))
    if args.max_prompt_length != -1:
        print("SFTConfig do not use `max_prompt_length`!")
    training_args.remove_unused_columns = True
    print("Set remove_unused_columns to True.")



    print("args:", args)
    print("training_args:", training_args)
    print("model_config:", model_config)

    local_rank = training_args.local_rank
    rank0_init_wandb(args.my_task_name)

    if TRL_USE_RICH:
        training_args.disable_tqdm = True
        console = Console()

    torch_dtype = (
        model_config.torch_dtype
        if model_config.torch_dtype in ["auto", None]
        else getattr(torch, model_config.torch_dtype)
    )
    quantization_config = get_quantization_config(model_config)
    model_kwargs = dict(
        revision=model_config.model_revision,
        trust_remote_code=model_config.trust_remote_code,
        attn_implementation=model_config.attn_implementation,
        torch_dtype=torch_dtype,
        use_cache=False if training_args.gradient_checkpointing else True,
        device_map=get_kbit_device_map() if quantization_config is not None else None,
        quantization_config=quantization_config,
    )
    model = AutoModelForCausalLM.from_pretrained(model_config.model_name_or_path, **model_kwargs)
    model_config.lora_target_modules=[
            "q_proj",
            "o_proj",
            "k_proj",
            "v_proj",
            "gate_proj",
            "up_proj",
            "down_proj",
        ]
    peft_config = get_peft_config(model_config)
    if peft_config is None:
        model_ref = AutoModelForCausalLM.from_pretrained(model_config.model_name_or_path, **model_kwargs)
    else:
        model_ref = None
    tokenizer = AutoTokenizer.from_pretrained(model_config.model_name_or_path)
    if tokenizer.pad_token is None:
        tokenizer.pad_token = tokenizer.eos_token
    if tokenizer.chat_template is None:
        tokenizer.chat_template = "{% for message in messages %}{{message['role'] + ': ' + message['content'] + '\n\n'}}{% endfor %}{{ eos_token }}"

    init_context = nullcontext() if not TRL_USE_RICH else console.status("[bold green]Initializing the SFTTrainer...")
    save_context = (
        nullcontext()
        if not TRL_USE_RICH
        else console.status(f"[bold green]Training completed! Saving the model to {training_args.output_dir}")
    )

    import json
    ds = load_dataset("json",data_files=args.dataset_name)['train']
    def process(row):
        row['prompt'] = row['prompt']
        row['chosen'] = row['ranked_code'][0]
        row['rejected'] = row['ranked_code'][-1]
        return row

    def formatting_prompts_func(example):
        output_texts = []
        for i in range(len(example['prompt'])):
            text = f"{example['prompt'][i]}{example['chosen'][i]}"
            output_texts.append(text)
        return output_texts

    ds = ds.map(
        process,
        num_proc=multiprocessing.cpu_count(),
        load_from_cache_file=False
    )

    ds = ds.train_test_split(test_size=0.01)
    train_dataset = ds['train']
    eval_dataset = ds['test']

    with init_context:
        trainer = SFTTrainer(
            model=model_config.model_name_or_path,
            model_init_kwargs=model_kwargs,
            args=training_args,
            train_dataset=train_dataset,
            eval_dataset=eval_dataset,
            tokenizer=tokenizer,
            peft_config=get_peft_config(model_config),
            callbacks=[RichProgressCallback] if TRL_USE_RICH else None,
            formatting_func=formatting_prompts_func
        )

    trainer.train()

    with save_context:
        trainer.save_model(training_args.output_dir)

    if local_rank == 0:
        hmkdir_rst = hmkdir(args.save_hdfs_path)
        hcopy_rst = hcopy(training_args.output_dir, args.save_hdfs_path)
        print("hmkdir: ", hmkdir_rst)
        print("hcopy: ", hcopy_rst)

