#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 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.

import argparse
import logging
import math
import os
import random
import shutil
import signal
import sys
from contextlib import nullcontext
from pathlib import Path

import accelerate
import datasets
import numpy as np
import torch
import torch.nn.functional as F
import torch.utils.checkpoint
import transformers
from accelerate.logging import get_logger
from datasets import load_dataset
from huggingface_hub import create_repo, upload_folder
from packaging import version
from torchvision import transforms
from tqdm.auto import tqdm
from transformers import CLIPTextModel, CLIPTokenizer
from transformers.utils import ContextManagers

import diffusers
from diffusers import AutoencoderKL, DDPMScheduler, StableDiffusionPipeline, UNet2DConditionModel
from diffusers.optimization import get_scheduler
from diffusers.training_utils import EMAModel, compute_dream_and_update_latents, compute_snr
from diffusers.utils import check_min_version, deprecate, is_wandb_available, make_image_grid
from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.torch_utils import is_compiled_module

# ---custom---
from dataset import UnlearnCanvasDataset_classifier_text_only
from constants.const import class_available,theme_available
from utils import AverageMeter, accuracy
from collections import defaultdict
import torch.nn as nn
import copy

if is_wandb_available():
    import wandb

def set_seed(seed: int = 1):
    """
    Fixes random seeds across libraries to ensure reproducibility.

    Args:
        seed (int): Seed value for random number generation. Default is 1.

    Affects:
        - Python's built-in `random` module
        - NumPy random generator
        - PyTorch CPU and GPU RNGs
        - PyTorch cuDNN backend (makes results deterministic)
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)  # if using GPU
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

set_seed(1)

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

logger = get_logger(__name__, log_level="INFO")

DATASET_NAME_MAPPING = {
    "nudity": ("image", "text"),
    "unlearncanvas": ("image", "text")
}

def save_model_card(
    args,
    repo_id: str,
    images: list = None,
    repo_folder: str = None,
):
    img_str = ""
    if len(images) > 0:
        image_grid = make_image_grid(images, 1, len(args.validation_prompts))
        image_grid.save(os.path.join(repo_folder, "val_imgs_grid.png"))
        img_str += "![val_imgs_grid](./val_imgs_grid.png)\n"

    model_description = f"""
# Text-to-image finetuning - {repo_id}

This pipeline was finetuned from **{args.pretrained_model_name_or_path}** on the **{args.dataset_name}** dataset. Below are some example images generated with the finetuned pipeline using the following prompts: {args.validation_prompts}: \n
{img_str}

## Pipeline usage

You can use the pipeline like so:

```python
from diffusers import DiffusionPipeline
import torch

pipeline = DiffusionPipeline.from_pretrained("{repo_id}", torch_dtype=torch.float16)
prompt = "{args.validation_prompts[0]}"
image = pipeline(prompt).images[0]
image.save("my_image.png")
```

## Training info

These are the key hyperparameters used during training:

* Epochs: {args.num_train_epochs}
* Learning rate: {args.learning_rate}
* Batch size: {args.train_batch_size}
* Gradient accumulation steps: {args.gradient_accumulation_steps}
* Image resolution: {args.resolution}
* Mixed-precision: {args.mixed_precision}

"""
    wandb_info = ""
    if is_wandb_available():
        wandb_run_url = None
        if wandb.run is not None:
            wandb_run_url = wandb.run.url

    if wandb_run_url is not None:
        wandb_info = f"""
More information on all the CLI arguments and the environment are available on your [`wandb` run page]({wandb_run_url}).
"""

    model_description += wandb_info

    model_card = load_or_create_model_card(
        repo_id_or_path=repo_id,
        from_training=True,
        license="creativeml-openrail-m",
        base_model=args.pretrained_model_name_or_path,
        model_description=model_description,
        inference=True,
    )

    tags = ["stable-diffusion", "stable-diffusion-diffusers", "text-to-image", "diffusers", "diffusers-training"]
    model_card = populate_model_card(model_card, tags=tags)

    model_card.save(os.path.join(repo_folder, "README.md"))


def log_validation(vae, text_encoder, tokenizer, unet, args, accelerator, weight_dtype, epoch):
    logger.info("Running validation... ")

    pipeline = StableDiffusionPipeline.from_pretrained(
        args.pretrained_model_name_or_path,
        vae=accelerator.unwrap_model(vae),
        text_encoder=accelerator.unwrap_model(text_encoder),
        tokenizer=tokenizer,
        unet=accelerator.unwrap_model(unet),
        safety_checker=None,
        revision=args.revision,
        variant=args.variant,
        torch_dtype=weight_dtype,
    )
    pipeline = pipeline.to(accelerator.device)
    pipeline.set_progress_bar_config(disable=True)

    if args.enable_xformers_memory_efficient_attention:
        pipeline.enable_xformers_memory_efficient_attention()

    if args.seed is None:
        generator = None
    else:
        generator = torch.Generator(device=accelerator.device).manual_seed(args.seed)

    images = []
    for i in range(len(args.validation_prompts)):
        if torch.backends.mps.is_available():
            autocast_ctx = nullcontext()
        else:
            autocast_ctx = torch.autocast(accelerator.device.type)

        with autocast_ctx:
            image = pipeline(args.validation_prompts[i], num_inference_steps=20, generator=generator).images[0]

        images.append(image)

    for tracker in accelerator.trackers:
        if tracker.name == "tensorboard":
            np_images = np.stack([np.asarray(img) for img in images])
            tracker.writer.add_images("validation", np_images, epoch, dataformats="NHWC")
        elif tracker.name == "wandb":
            tracker.log(
                {
                    "validation": [
                        wandb.Image(image, caption=f"{i}: {args.validation_prompts[i]}")
                        for i, image in enumerate(images)
                    ]
                }
            )
        else:
            logger.warning(f"image logging not implemented for {tracker.name}")

    del pipeline
    torch.cuda.empty_cache()

    return images


def parse_args():
    parser = argparse.ArgumentParser(description="Simple example of a training script.")
    parser.add_argument(
        "--input_perturbation", type=float, default=0, help="The scale of input perturbation. Recommended 0.1."
    )
    parser.add_argument(
        "--pretrained_model_name_or_path",
        type=str,
        default=None,
        required=True,
        help="Path to pretrained model or model identifier from huggingface.co/models.",
    )
    parser.add_argument(
        "--revision",
        type=str,
        default=None,
        required=False,
        help="Revision of pretrained model identifier from huggingface.co/models.",
    )
    parser.add_argument(
        "--variant",
        type=str,
        default=None,
        help="Variant of the model files of the pretrained model identifier from huggingface.co/models, 'e.g.' fp16",
    )
    parser.add_argument(
        "--dataset_name",
        type=str,
        default=None,
        help=(
            "The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private,"
            " dataset). It can also be a path pointing to a local copy of a dataset in your filesystem,"
            " or to a folder containing files that 🤗 Datasets can understand."
        ),
    )
    parser.add_argument(
        "--dataset_config_name",
        type=str,
        default=None,
        help="The config of the Dataset, leave as None if there's only one config.",
    )
    parser.add_argument(
        "--train_data_dir",
        type=str,
        default=None,
        help=(
            "A folder containing the training data. Folder contents must follow the structure described in"
            " https://huggingface.co/docs/datasets/image_dataset#imagefolder. In particular, a `metadata.jsonl` file"
            " must exist to provide the captions for the images. Ignored if `dataset_name` is specified."
        ),
    )
    parser.add_argument(
        "--image_column", type=str, default="image", help="The column of the dataset containing an image."
    )
    parser.add_argument(
        "--caption_column",
        type=str,
        default="text",
        help="The column of the dataset containing a caption or a list of captions.",
    )
    parser.add_argument(
        "--max_train_samples",
        type=int,
        default=None,
        help=(
            "For debugging purposes or quicker training, truncate the number of training examples to this "
            "value if set."
        ),
    )
    parser.add_argument(
        "--validation_prompts",
        type=str,
        default=None,
        nargs="+",
        help=("A set of prompts evaluated every `--validation_epochs` and logged to `--report_to`."),
    )
    parser.add_argument(
        "--output_dir",
        type=str,
        default="sd-model-finetuned",
        help="The output directory where the model predictions and checkpoints will be written.",
    )
    parser.add_argument(
        "--cache_dir",
        type=str,
        default=None,
        help="The directory where the downloaded models and datasets will be stored.",
    )
    parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
    parser.add_argument(
        "--resolution",
        type=int,
        default=512,
        help=(
            "The resolution for input images, all the images in the train/validation dataset will be resized to this"
            " resolution"
        ),
    )
    parser.add_argument(
        "--center_crop",
        default=False,
        action="store_true",
        help=(
            "Whether to center crop the input images to the resolution. If not set, the images will be randomly"
            " cropped. The images will be resized to the resolution first before cropping."
        ),
    )
    parser.add_argument(
        "--random_flip",
        action="store_true",
        help="whether to randomly flip images horizontally",
    )
    parser.add_argument(
        "--train_batch_size", type=int, default=16, help="Batch size (per device) for the training dataloader."
    )
    parser.add_argument("--num_train_epochs", type=int, default=100)
    parser.add_argument(
        "--max_train_steps",
        type=int,
        default=None,
        help="Total number of training steps to perform.  If provided, overrides num_train_epochs.",
    )
    parser.add_argument(
        "--gradient_accumulation_steps",
        type=int,
        default=1,
        help="Number of updates steps to accumulate before performing a backward/update pass.",
    )
    parser.add_argument(
        "--gradient_checkpointing",
        action="store_true",
        help="Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.",
    )
    parser.add_argument(
        "--learning_rate",
        type=float,
        default=1e-4,
        help="Initial learning rate (after the potential warmup period) to use.",
    )
    parser.add_argument(
        "--scale_lr",
        action="store_true",
        default=False,
        help="Scale the learning rate by the number of GPUs, gradient accumulation steps, and batch size.",
    )
    parser.add_argument(
        "--lr_scheduler",
        type=str,
        default="constant",
        help=(
            'The scheduler type to use. Choose between ["linear", "cosine", "cosine_with_restarts", "polynomial",'
            ' "constant", "constant_with_warmup"]'
        ),
    )
    parser.add_argument(
        "--lr_warmup_steps", type=int, default=500, help="Number of steps for the warmup in the lr scheduler."
    )
    parser.add_argument(
        "--snr_gamma",
        type=float,
        default=None,
        help="SNR weighting gamma to be used if rebalancing the loss. Recommended value is 5.0. "
        "More details here: https://huggingface.co/papers/2303.09556.",
    )
    parser.add_argument(
        "--dream_training",
        action="store_true",
        help=(
            "Use the DREAM training method, which makes training more efficient and accurate at the "
            "expense of doing an extra forward pass. See: https://huggingface.co/papers/2312.00210"
        ),
    )
    parser.add_argument(
        "--dream_detail_preservation",
        type=float,
        default=1.0,
        help="Dream detail preservation factor p (should be greater than 0; default=1.0, as suggested in the paper)",
    )
    parser.add_argument(
        "--use_8bit_adam", action="store_true", help="Whether or not to use 8-bit Adam from bitsandbytes."
    )
    parser.add_argument(
        "--allow_tf32",
        action="store_true",
        help=(
            "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
            " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
        ),
    )
    parser.add_argument("--use_ema", action="store_true", help="Whether to use EMA model.")
    parser.add_argument("--offload_ema", action="store_true", help="Offload EMA model to CPU during training step.")
    parser.add_argument("--foreach_ema", action="store_true", help="Use faster foreach implementation of EMAModel.")
    parser.add_argument(
        "--non_ema_revision",
        type=str,
        default=None,
        required=False,
        help=(
            "Revision of pretrained non-ema model identifier. Must be a branch, tag or git identifier of the local or"
            " remote repository specified with --pretrained_model_name_or_path."
        ),
    )
    parser.add_argument(
        "--dataloader_num_workers",
        type=int,
        default=0,
        help=(
            "Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
        ),
    )
    parser.add_argument("--adam_beta1", type=float, default=0.9, help="The beta1 parameter for the Adam optimizer.")
    parser.add_argument("--adam_beta2", type=float, default=0.999, help="The beta2 parameter for the Adam optimizer.")
    parser.add_argument("--adam_weight_decay", type=float, default=1e-2, help="Weight decay to use.")
    parser.add_argument("--adam_epsilon", type=float, default=1e-08, help="Epsilon value for the Adam optimizer")
    parser.add_argument("--max_grad_norm", default=1.0, type=float, help="Max gradient norm.")
    parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
    parser.add_argument("--hub_token", type=str, default=None, help="The token to use to push to the Model Hub.")
    parser.add_argument(
        "--prediction_type",
        type=str,
        default=None,
        help="The prediction_type that shall be used for training. Choose between 'epsilon' or 'v_prediction' or leave `None`. If left to `None` the default prediction type of the scheduler: `noise_scheduler.config.prediction_type` is chosen.",
    )
    parser.add_argument(
        "--hub_model_id",
        type=str,
        default=None,
        help="The name of the repository to keep in sync with the local `output_dir`.",
    )
    parser.add_argument(
        "--logging_dir",
        type=str,
        default="logs",
        help=(
            "[TensorBoard](https://www.tensorflow.org/tensorboard) log directory. Will default to"
            " *output_dir/runs/**CURRENT_DATETIME_HOSTNAME***."
        ),
    )
    parser.add_argument(
        "--mixed_precision",
        type=str,
        default=None,
        choices=["no", "fp16", "bf16"],
        help=(
            "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
            " 1.10.and an Nvidia Ampere GPU.  Default to the value of accelerate config of the current system or the"
            " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
        ),
    )
    parser.add_argument(
        "--report_to",
        type=str,
        default="tensorboard",
        help=(
            'The integration to report the results and logs to. Supported platforms are `"tensorboard"`'
            ' (default), `"wandb"` and `"comet_ml"`. Use `"all"` to report to all integrations.'
        ),
    )
    parser.add_argument("--local_rank", type=int, default=-1, help="For distributed training: local_rank")
    parser.add_argument(
        "--checkpointing_steps",
        type=int,
        default=500,
        help=(
            "Save a checkpoint of the training state every X updates. These checkpoints are only suitable for resuming"
            " training using `--resume_from_checkpoint`."
        ),
    )
    parser.add_argument(
        "--checkpoints_total_limit",
        type=int,
        default=None,
        help=("Max number of checkpoints to store."),
    )
    parser.add_argument(
        "--resume_from_checkpoint",
        type=str,
        default=None,
        help=(
            "Whether training should be resumed from a previous checkpoint. Use a path saved by"
            ' `--checkpointing_steps`, or `"latest"` to automatically select the last available checkpoint.'
        ),
    )
    parser.add_argument(
        "--enable_xformers_memory_efficient_attention", action="store_true", help="Whether or not to use xformers."
    )
    parser.add_argument("--noise_offset", type=float, default=0, help="The scale of noise offset.")
    parser.add_argument(
        "--validation_epochs",
        type=int,
        default=5,
        help="Run validation every X epochs.",
    )
    parser.add_argument(
        "--tracker_project_name",
        type=str,
        default="text2image-fine-tune",
        help=(
            "The `project_name` argument passed to Accelerator.init_trackers for"
            " more information see https://huggingface.co/docs/accelerate/v0.17.0/en/package_reference/accelerator#accelerate.Accelerator"
        ),
    )
    parser.add_argument(
        "--image_interpolation_mode",
        type=str,
        default="lanczos",
        choices=[
            f.lower() for f in dir(transforms.InterpolationMode) if not f.startswith("__") and not f.endswith("__")
        ],
        help="The image interpolation method to use for resizing images.",
    )
    parser.add_argument(
        "--theme",
        type=str,
        default='',
        choices=class_available+theme_available,
        help="The target theme that you want to unlearn",
    )
    args = parser.parse_args()
    env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
    if env_local_rank != -1 and env_local_rank != args.local_rank:
        args.local_rank = env_local_rank

    # # Sanity checks
    # if args.dataset_name is None and args.train_data_dir is None:
    #     raise ValueError("Need either a dataset name or a training folder.")

    # default to using the same revision for the non-ema model if not specified
    if args.non_ema_revision is None:
        args.non_ema_revision = args.revision

    return args


def main():

    
    args = parse_args()

    # if os.path.exists(os.path.join(args.output_dir,'model_index.json')) and not args.resume_from_checkpoint:
    #     print('model exists')
    #     exit(0)

    if args.report_to == "wandb" and args.hub_token is not None:
        raise ValueError(
            "You cannot use both --report_to=wandb and --hub_token due to a security risk of exposing your token."
            " Please use `huggingface-cli login` to authenticate with the Hub."
        )

    if args.non_ema_revision is not None:
        deprecate(
            "non_ema_revision!=None",
            "0.15.0",
            message=(
                "Downloading 'non_ema' weights from revision branches of the Hub is deprecated. Please make sure to"
                " use `--variant=non_ema` instead."
            ),
        )

    os.makedirs(args.output_dir,exist_ok=True)


    unlearn_type = 'style' if args.theme in theme_available else 'class'
    dataset, label = UnlearnCanvasDataset_classifier_text_only(
        image_dir="/workspace/unlearncanvas",
        unlearn_type=unlearn_type
    )   

    # Load tokenizer and models.
    tokenizer = CLIPTokenizer.from_pretrained(
        args.pretrained_model_name_or_path, subfolder="tokenizer", revision=args.revision
    )
    
    pretrained_text_encoder = CLIPTextModel.from_pretrained(
        args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision, variant=args.variant
    )

    pretrained_text_encoder.requires_grad_(True)
    pretrained_text_encoder.to('cuda:0')
    # Preprocessing the datasets.
    # We need to tokenize inputs and targets.

    image_column = 'image'
    caption_column = 'text'
    target_ind = label[args.theme]

    # Preprocessing the datasets.
    # We need to tokenize input captions and transform the images.
    def tokenize_captions(examples, is_train=True):
        captions = []
        for caption in examples[caption_column]:
            if isinstance(caption, str):
                captions.append(caption)
            elif isinstance(caption, (list, np.ndarray)):
                # take a random caption if there are multiple
                captions.append(random.choice(caption) if is_train else caption[0])
            else:
                raise ValueError(
                    f"Caption column `{caption_column}` should contain either strings or lists of strings."
                )
        inputs = tokenizer(
            captions, max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
        )
        return inputs.input_ids

    # Get the specified interpolation method from the args
    interpolation = transforms.InterpolationMode.LANCZOS

    # Raise an error if the interpolation method is invalid
    if interpolation is None:
        raise ValueError(f"Unsupported interpolation mode {'lanczos'}.")

    # Data preprocessing transformations
    train_transforms = transforms.Compose(
        [
            transforms.Resize(512, interpolation=interpolation),  # Use dynamic interpolation method
            transforms.CenterCrop(512),
            transforms.RandomHorizontalFlip(),
            transforms.ToTensor(),
            transforms.Normalize([0.5], [0.5]),
        ]
    )

    def preprocess_train(examples):
        # images = [image.convert("RGB") for image in examples[image_column]]
        # examples["pixel_values"] = [train_transforms(image) for image in images]
        examples["input_ids"] = tokenize_captions(examples)
        return examples

    dataset = dataset.with_transform(preprocess_train)

    def collate_fn(examples):
        pixel_values = torch.stack([example["pixel_values"] for example in examples])
        pixel_values = pixel_values.to(memory_format=torch.contiguous_format).float()
        input_ids = torch.stack([example["input_ids"] for example in examples])
        return {"pixel_values": pixel_values, "input_ids": input_ids, "dist": torch.tensor(examples['dist'])}

    def concat_collate_fn(examples):
        retain_batch = defaultdict(list)
        forget_batch = defaultdict(list)
        
        for example in examples:
            if example[f'{unlearn_type}_dist'] != target_ind:
                # retain_batch['pixel_values'].append(example["pixel_values"])
                retain_batch['input_ids'].append(example['input_ids'])
                retain_batch['class_dist'].append(example['class_dist'])
                retain_batch['style_dist'].append(example['style_dist'])

            else:
                # forget_batch['pixel_values'].append(example["pixel_values"])
                forget_batch['input_ids'].append(example['input_ids'])
                forget_batch['class_dist'].append(example['class_dist'])
                forget_batch['style_dist'].append(example['style_dist'])

        
        if retain_batch['input_ids']:
            # retain_batch['pixel_values'] = torch.stack(retain_batch['pixel_values'])
            # retain_batch['pixel_values'] = retain_batch['pixel_values'].to(memory_format=torch.contiguous_format).float()

            retain_batch['input_ids'] = torch.stack(retain_batch['input_ids'])
            retain_batch['class_dist'] = torch.tensor(retain_batch['class_dist'])
            retain_batch['style_dist'] = torch.tensor(retain_batch['style_dist'])

        else:
            retain_batch = None

        if forget_batch['input_ids']:
            # forget_batch['pixel_values'] = torch.stack(forget_batch['pixel_values'])
            # forget_batch['pixel_values'] = forget_batch['pixel_values'].to(memory_format=torch.contiguous_format).float()

            forget_batch['input_ids'] = torch.stack(forget_batch['input_ids'])
            forget_batch['class_dist'] = torch.tensor(forget_batch['class_dist'])
            forget_batch['style_dist'] = torch.tensor(forget_batch['style_dist'])

        else:   
            forget_batch = None
        
        return (retain_batch, forget_batch)    


    print("***** Loading Auxilary Layer *****")
    style_model = nn.Linear(pretrained_text_encoder.config.hidden_size,51)
    style_state_dict = torch.load(f'/workspace/sd_opc/text_encoder_only/unlearncanvas/style.pt')
    style_state_dict = style_state_dict['state_dict']
    style_model.load_state_dict(style_state_dict)
    style_model.requires_grad_(True if unlearn_type == 'style' else False)
    style_model.to('cuda:0')
    style_model.train()

    class_model = nn.Linear(pretrained_text_encoder.config.hidden_size,20)
    class_state_dict = torch.load(f'/workspace/sd_opc/text_encoder_only/unlearncanvas/class.pt')
    class_state_dict = class_state_dict['state_dict']
    class_model.load_state_dict(class_state_dict)
    class_model.requires_grad_(True if unlearn_type == 'class' else False)
    class_model.to('cuda:0')
    class_model.train()

    criteria = torch.nn.CrossEntropyLoss()

    train_dataloader = torch.utils.data.DataLoader(
        dataset,
        shuffle=True,
        collate_fn=concat_collate_fn,
        batch_size=args.train_batch_size,
        num_workers=args.dataloader_num_workers,
        pin_memory=True
    )

    pretrained_text_encoder.requires_grad_(True)
    pretrained_text_encoder.to('cuda:0')

    if unlearn_type == 'style':
        optimizer = torch.optim.AdamW(
            list(style_model.parameters())+ list(pretrained_text_encoder.parameters()),
            lr=args.learning_rate,
            betas=(0.9, 0.999),
            weight_decay=1e-2,
            eps=1e-08,
        )
    elif unlearn_type == 'class':
        optimizer = torch.optim.AdamW(
            list(class_model.parameters()) + list(pretrained_text_encoder.parameters()),
            lr=args.learning_rate,
            betas=(0.9, 0.999),
            weight_decay=1e-2,
            eps=1e-08,
        )
    # optimizer = torch.optim.AdamW(
    #     list(class_model.parameters())+list(style_model.parameters())+list(pretrained_text_encoder.parameters()),
    #     lr=args.learning_rate,
    #     betas=(0.9, 0.999),
    #     weight_decay=1e-2,
    #     eps=1e-08,
    # )

    criteria = torch.nn.CrossEntropyLoss()

    if args.max_train_steps is not None:
        args.num_train_epochs = math.ceil(args.max_train_steps / len(train_dataloader))

    print("***** Running Auxilary Layer & Text encoder Unlearning *****")
        
    # wandb 초기화 (main 함수 시작 부분에 추가)
    if is_wandb_available() and args.report_to == "wandb":
        wandb.init(project=args.tracker_project_name, name=args.theme)
    
    global_step = 0
    
    for i in range(args.num_train_epochs):
        pbar = tqdm(train_dataloader, desc=f"Epoch {i+1}/{args.num_train_epochs}")

        retain_losses = AverageMeter()
        forget_losses = AverageMeter()

        retain_accs = AverageMeter()
        forget_accs = AverageMeter()

        for step, (retain_batch, forget_batch) in enumerate(pbar):       
            loss = torch.tensor(0.0).to('cuda:0')
            if retain_batch is not None:
                retain_out = pretrained_text_encoder(retain_batch['input_ids'].to('cuda:0'),return_dict=False)[1]
                
                class_retain_logit = class_model(retain_out)
                class_retain_target = retain_batch['class_dist'].to('cuda:0')
                class_retain_loss = criteria(class_retain_logit,class_retain_target)

                style_retain_logit = style_model(retain_out)
                style_retain_target = retain_batch['style_dist'].to('cuda:0')
                style_retain_loss = criteria(style_retain_logit,style_retain_target)                    

                retain_loss = class_retain_loss + style_retain_loss
                
                loss += retain_loss
                class_retain_acc = accuracy(class_retain_logit.data,class_retain_target)[0]
                style_retain_acc = accuracy(style_retain_logit.data,style_retain_target)[0]
                retain_acc = (class_retain_acc.item()+ style_retain_acc.item())/2

                retain_losses.update(retain_loss.item(),class_retain_logit.size(0))
                retain_accs.update(retain_acc,class_retain_logit.size(0))
                
            if forget_batch is not None:
                forget_out = pretrained_text_encoder(forget_batch['input_ids'].to('cuda:0'),return_dict=False)[1]
                if unlearn_type == 'class':
                    class_forget_logit = class_model(forget_out)
                    class_forget_target = forget_batch['class_dist'].to('cuda:0')
                    forget_norm_loss = class_forget_logit.norm(p=2,dim=1).mean()
                    forget_acc = accuracy(class_forget_logit.data,class_forget_target)[0]

                    style_forget_logit = style_model(forget_out)
                    style_forget_target = forget_batch['style_dist'].to('cuda:0')
                    forget_loss_classifier = criteria(style_forget_logit,style_forget_target)    


                elif unlearn_type == 'style':
                    style_forget_logit = style_model(forget_out)
                    style_forget_target = forget_batch['style_dist'].to('cuda:0')
                    forget_norm_loss = style_forget_logit.norm(p=2,dim=1).mean()
                    forget_acc = accuracy(style_forget_logit.data,style_forget_target)[0]

                    class_forget_logit = class_model(forget_out)
                    class_forget_target = forget_batch['class_dist'].to('cuda:0')
                    forget_loss_classifier = criteria(class_forget_logit,class_forget_target) 


                forget_loss = forget_loss_classifier + forget_norm_loss
                loss += forget_loss

                forget_losses.update(forget_loss.item(),class_forget_logit.size(0))
                forget_accs.update(forget_acc.item(),class_forget_logit.size(0))

            # Update progress bar with current metrics
            pbar.set_postfix({
                'Retain Loss': f'{retain_losses.avg:.4f}',
                'Forget Loss': f'{forget_losses.avg:.4f}',
                'Retain Acc': f'{retain_accs.avg:.4f}',
                'Forget Acc': f'{forget_accs.avg:.4f}',
            })

            # wandb에 step별 메트릭 로깅
            if is_wandb_available() and args.report_to == "wandb":
                wandb.log({
                    "step/retain_loss": retain_losses.val if retain_batch is not None else 0,
                    "step/forget_loss": forget_losses.val if forget_batch is not None else 0,
                    "step/retain_acc": retain_accs.val if retain_batch is not None else 0,
                    "step/forget_acc": forget_accs.val if forget_batch is not None else 0,
                    "step/total_loss": loss.item(),
                    "step": global_step,
                    "epoch": i + 1
                })

            if args.max_train_steps is not None and global_step >= args.max_train_steps:
                break

            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
            
            global_step += 1

        # Epoch별 평균 메트릭 로깅
        if is_wandb_available() and args.report_to == "wandb":
            wandb.log({
                "epoch/retain_loss_avg": retain_losses.avg,
                "epoch/forget_loss_avg": forget_losses.avg,
                "epoch/retain_acc_avg": retain_accs.avg,
                "epoch/forget_acc_avg": forget_accs.avg,
                "epoch": i + 1
            })
        
        # # Save checkpoint every epoch
        # pipeline = StableDiffusionPipeline.from_pretrained(
        #                 args.pretrained_model_name_or_path,
        #                 text_encoder=pretrained_text_encoder,
        #                 revision=args.revision,
        #                 variant=args.variant,
        #             )
        # pipeline.save_pretrained(args.output_dir)

    # Save final model
    pipeline = StableDiffusionPipeline.from_pretrained(
        args.pretrained_model_name_or_path,
        text_encoder=pretrained_text_encoder,
        revision=args.revision,
        variant=args.variant,
    )
    pipeline.save_pretrained(args.output_dir)
    
    if unlearn_type == 'style':
        torch.save({'state_dict':style_model.state_dict()},os.path.join(args.output_dir,'unlearn_style.pt'))
    elif unlearn_type == 'class':
        torch.save({'state_dict':class_model.state_dict()},os.path.join(args.output_dir,'unlearn_class.pt'))
    print(f"Final model saved to {args.output_dir}")


    # Normal completion - run final evaluation
    print("***** Training completed normally. Running final evaluation *****")
    pretrained_text_encoder.requires_grad_(False)
    pretrained_text_encoder.eval()
    pbar = tqdm(train_dataloader, desc="Final Evaluation")

    retain_losses = AverageMeter()
    forget_losses = AverageMeter()

    retain_accs = AverageMeter()
    forget_accs = AverageMeter()

    for step, (retain_batch, forget_batch) in enumerate(pbar):
        with torch.no_grad():                
            if retain_batch is not None:
                retain_out = pretrained_text_encoder(retain_batch['input_ids'].to('cuda:0'),return_dict=False)[1]
                
                class_retain_logit = class_model(retain_out)
                class_retain_target = retain_batch['class_dist'].to('cuda:0')
                class_retain_loss = criteria(class_retain_logit,class_retain_target)

                style_retain_logit = style_model(retain_out)
                style_retain_target = retain_batch['style_dist'].to('cuda:0')
                style_retain_loss = criteria(style_retain_logit,style_retain_target)                    

                retain_loss = class_retain_loss + style_retain_loss
                
                class_retain_acc = accuracy(class_retain_logit.data,class_retain_target)[0]
                style_retain_acc = accuracy(style_retain_logit.data,style_retain_target)[0]
                retain_acc = (class_retain_acc.item()+ style_retain_acc.item())/2

                retain_losses.update(retain_loss.item(),class_retain_logit.size(0))
                retain_accs.update(retain_acc,class_retain_logit.size(0))
                
            if forget_batch is not None:
                forget_out = pretrained_text_encoder(forget_batch['input_ids'].to('cuda:0'),return_dict=False)[1]
                if unlearn_type == 'class':
                    class_forget_logit = class_model(forget_out)
                    class_forget_target = forget_batch['class_dist'].to('cuda:0')
                    forget_norm_loss = class_forget_logit.norm(p=2,dim=1).mean()
                    forget_acc = accuracy(class_forget_logit.data,class_forget_target)[0]

                    style_forget_logit = style_model(forget_out)
                    style_forget_target = forget_batch['style_dist'].to('cuda:0')
                    forget_loss_clssifier = criteria(style_forget_logit,style_forget_target) 

                elif unlearn_type == 'style':
                    style_forget_logit = style_model(forget_out)
                    style_forget_target = forget_batch['style_dist'].to('cuda:0')
                    forget_norm_loss = style_forget_logit.norm(p=2,dim=1).mean()
                    forget_acc = accuracy(style_forget_logit.data,style_forget_target)[0]

                    class_forget_logit = class_model(forget_out)
                    class_forget_target = forget_batch['class_dist'].to('cuda:0')
                    forget_loss_clssifier = criteria(class_forget_logit,class_forget_target)

                forget_loss = forget_loss_clssifier + forget_norm_loss

                forget_losses.update(forget_loss.item(),class_forget_logit.size(0))
                forget_accs.update(forget_acc.item(),class_forget_logit.size(0))


        # Update progress bar with current metrics
        pbar.set_postfix({
            'Retain Loss': f'{retain_losses.avg:.4f}',
            'Forget Loss': f'{forget_losses.avg:.4f}',
            'Retain Acc': f'{retain_accs.avg:.4f}',
            'Forget Acc': f'{forget_accs.avg:.4f}',
        })

    print(f"\n***** Final Evaluation Results *****")
    print(f"Retain Loss: {retain_losses.avg:.4f}")
    print(f"Forget Loss: {forget_losses.avg:.4f}")
    print(f"Retain Accuracy: {retain_accs.avg:.4f}")
    print(f"Forget Accuracy: {forget_accs.avg:.4f}")

    # Epoch별 평균 메트릭 로깅
    if is_wandb_available() and args.report_to == "wandb":
        wandb.run.summary.update({
            "retain_loss": retain_losses.avg,
            "forget_loss": forget_losses.avg,
            "retain_acc": retain_accs.avg,
            "forget_acc": forget_accs.avg,
        })

    original_text_encoder = CLIPTextModel.from_pretrained(
        args.pretrained_model_name_or_path,
        subfolder = 'text_encoder',
        revision=args.revision,
        variant=args.variant,
    )
    original_text_encoder.requires_grad_(False)
    original_text_encoder.to('cuda:0')

    # Make retain feature map
    retain_prompts = []
    forget_prompts = []

    for test_theme in theme_available:
        for object_class in class_available:
            if test_theme != 'Seed_Image':
                prompt = f"A {object_class} image in {test_theme.replace('_',' ')} style"
            else:
                prompt = f"A {object_class} image in Photo style"

            if args.theme not in [test_theme, object_class]:
                retain_prompts.append(prompt)
            else:
                forget_prompts.append(prompt)


    original_embedding = []
    unlearn_embedding = []
    with torch.no_grad():
        for text in retain_prompts:
            inputs = tokenizer(
                [text], max_length=tokenizer.model_max_length, padding="max_length", truncation=True, return_tensors="pt"
            )
            original_text_embedding = original_text_encoder(inputs['input_ids'].to('cuda:0'),return_dict=False)[0]
            pretrained_text_embedding = pretrained_text_encoder(inputs['input_ids'].to('cuda:0'),return_dict=False)[0]
            
            original_embedding.append(original_text_embedding)
            unlearn_embedding.append(pretrained_text_embedding)

    X = torch.cat(unlearn_embedding,dim=0).to('cpu')
    Y = torch.cat(original_embedding,dim=0).to('cpu')

    X= X.reshape(-1,X.shape[-1])
    Y= Y.reshape(-1,Y.shape[-1])

    XTX = X.T @ X
    XTY = X.T @ Y

    M_T = torch.linalg.solve(XTX, XTY)
    M = M_T.T

    feature_map = nn.Linear(*M.shape)
    feature_map.weight.data = M
    torch.save({'state_dict':feature_map.state_dict()}, 
               os.path.join(args.output_dir,'feature_map.pt'))



if __name__ == "__main__":
    main()