"""Split BF16 addition into one row per Bertha EVT0 core."""

import torch
import torch_ha
import legato
import legato.model.bertha as bertha


def get_bertha(ctx):
    return bertha.Bertha(ctx, "bertha", num_cores=32)


@legato.compile(
    backend=get_bertha, param_kinds={"a": "top", "b": "top", "out": "core"}
)
def multi_core_add(
    a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [32, 256], "shared_dram"),
    b: legato.get_model().tensor_type(legato.types.float("bfloat16"), [32, 256], "shared_dram"),
    out: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 256], "shared_dram"),
):
    device = legato.get_context().get_device()
    with device.get_top():
        def load_row(i):
            region = (legato.range(i, i + 1), legato.range(0, 256))
            legato.tensor.request_load(legato.tensor.view(a, region), device.get_core(i), "sram")
            legato.tensor.request_load(legato.tensor.view(b, region), device.get_core(i), "sram")

        legato.static.for_each(legato.range(0, 32), load_row)
    with device.get_all_cores():
        tile_type = legato.types.tensor(legato.types.float("bfloat16"), [1, 256])
        x = legato.tensor.receive_type(tile_type, 0, None, "sram")
        y = legato.tensor.receive_type(tile_type, 1, None, "sram")
        legato.tensor.memcpy(out, x + y)


def main():
    shape = [32, 256]
    values = torch.arange(32 * 256).reshape(shape)
    a_cpu = ((values % 17 - 8) / 8).to(torch.bfloat16)
    b_cpu = ((values % 13 - 6) / 8).to(torch.bfloat16)
    a, b = [
        torch.ops.lpu.empty_with_kind(
            shape, "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0"
        )
        for _ in range(2)
    ]
    outputs = [
        torch.ops.lpu.empty_with_kind(
            [1, 256], "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0"
        )
        for _ in range(32)
    ]
    a.copy_(a_cpu)
    b.copy_(b_cpu)
    with legato.session(output_type=legato.OutputType.BINARY, output_path="multi_core_add"):
        multi_core_add(
            legato.Arg(a, bertha.top),
            legato.Arg(b, bertha.top),
            legato.Args(outputs, bertha.all_cores),
        )
    actual = torch.cat([out.cpu() for out in outputs], dim=0)
    torch.testing.assert_close(actual, a_cpu + b_cpu, rtol=0, atol=0)
    print("PASS: multi_core_add [32, 256], BF16, 32 cores")


if __name__ == "__main__":
    main()
