"""Masked softmax using a host-computed maximum of the already-masked scores."""

import os
from pathlib import Path

import torch

import legato
import legato.model.bertha as bertha

# Store compiler artifacts and optional simulator logs in a configurable directory.
OUTPUT = Path(os.environ.get("LEGATO_EXAMPLE_OUTPUT", "legato_example_output"))


@legato.compile(backend=lambda ctx: bertha.Bertha(ctx, "bertha"))
def masked_softmax(
    scores: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "shared_dram"),
    maximum: legato.get_model().tensor_type(legato.types.float("bfloat16"), (4, (1, 256)), "shared_dram"),
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [4, 256], "shared_dram"),
):
    """Consume already-masked scores and the maximum of each masked row."""
    device = legato.get_context().get_device()
    with device.get_top():
        legato.tensor.request_load(scores, device.get_core(0), "sram")
        legato.tensor.request_load(maximum, device.get_core(0), "sram")
    with device.get_core(0):
        x = legato.tensor.receive(scores, 0, "sram")
        m = legato.tensor.receive(maximum, 0, "sram")
        legato.tensor.memcpy(out, legato.math.softmax(x, -1, m))


def main():
    """Build the mask and maximum on the host, then verify the device normalization."""
    # Register the LPU PyTorch backend before allocating device tensors.
    import hart
    import torch_ha

    torch_ha._autoload()
    # HA_BACKEND=sim selects EVT0 Torch FSim; otherwise use the hardware runtime.
    if os.environ.get("HA_BACKEND") == "sim":
        OUTPUT.mkdir(parents=True, exist_ok=True)
        hart.set_fsim_env(
            hart.HaDeviceVersion.BERTHA_CLOUD_EVT0,
            hart.HaFSimComputeMode.TORCH,
            str(OUTPUT / "fsim.log"),
            "error",
        )
    hart.set_device(0)
    # Keep CPU inputs reproducible without initializing a device RNG.
    torch.random.default_generator.manual_seed(0)
    scores_cpu = torch.randn(4, 256, dtype=torch.bfloat16)
    positions = torch.arange(252, 256).unsqueeze(1)
    scores_cpu = scores_cpu.masked_fill(torch.arange(256).unsqueeze(0) > positions, -30.0)
    max_host = torch.zeros(4, 256, dtype=torch.bfloat16)
    max_host[:, :1] = scores_cpu.max(-1, keepdim=True).values
    # Allocate the physical layout expected by the kernel and copy contiguous host data.
    maximum_storage = torch.ops.lpu.empty_with_kind(
        list(max_host.shape), "dram_word_interleaved", dtype=max_host.dtype, device="lpu:0"
    )
    maximum_storage.copy_(max_host.contiguous())
    maximum = maximum_storage[:, :1]
    out_cpu = torch.zeros_like(scores_cpu)
    # Allocate the physical layout expected by the kernel and copy contiguous host data.
    out = torch.ops.lpu.empty_with_kind(
        list(out_cpu.shape), "dram_word_interleaved", dtype=out_cpu.dtype, device="lpu:0"
    )
    out.copy_(out_cpu.contiguous())
    # Allocate the physical layout expected by the kernel and copy contiguous host data.
    scores = torch.ops.lpu.empty_with_kind(
        list(scores_cpu.shape), "dram_word_interleaved", dtype=scores_cpu.dtype, device="lpu:0"
    )
    scores.copy_(scores_cpu.contiguous())
    # Compile a binary and launch it on the selected device.
    with legato.session(output_type=legato.OutputType.BINARY, output_path=str(OUTPUT), launch=True):
        masked_softmax(scores, maximum, out)
    # Surface asynchronous execution errors before reading the result.
    hart.stream_synchronize()
    # Read back the synchronized result and compare every element with the CPU reference.
    actual = out.cpu().float()
    assert torch.isfinite(actual).all(), "Non-finite device result"
    torch.testing.assert_close(actual, (torch.softmax(scores_cpu.float(), -1)).float(), atol=0.001, rtol=0.05)


if __name__ == "__main__":
    main()
