# Copyright (c) 2024, Alibaba Group;
# 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 os
from typing import Dict

import torch
from torch import nn

from tzrec.acc.export_utils import export_pm


def export_model_aot(
    model: nn.Module, data: Dict[str, torch.Tensor], save_dir: str
) -> str:
    """Export AOTInductor model.

    Args:
        model (nn.Module): the model
        data (Dict[str, torch.Tensor]): the test data
        save_dir (str): model save dir
    """
    exported_pg, data = export_pm(model, data, save_dir)

    # AsserScalar codegen is not correct.
    with torch._inductor.config.patch({"scalar_asserts": False}):
        package_path = torch._inductor.aoti_compile_and_package(
            exported_pg,
            package_path=os.path.join(save_dir, "aoti_model.pt2"),
        )
    return package_path
