"""BF16 vector addition on one Bertha EVT0 core."""

import torch
import torch_ha  # Registers the LPU device and torch.ops.lpu operations.
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)
def vector_add(
    a: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 256], "shared_dram"),
    b: legato.get_model().tensor_type(legato.types.float("bfloat16"), [1, 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():
        legato.tensor.request_load(a, device.get_core(0), "sram")
        legato.tensor.request_load(b, device.get_core(0), "sram")
    with device.get_core(0):
        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 = [1, 256]
    a_cpu = ((torch.arange(256).reshape(shape) % 17 - 8) / 8).to(torch.bfloat16)
    b_cpu = ((torch.arange(256).reshape(shape) % 13 - 6) / 8).to(torch.bfloat16)
    a, b, out = [
        torch.ops.lpu.empty_with_kind(
            shape, "dram_word_interleaved", dtype=torch.bfloat16, device="lpu:0"
        )
        for _ in range(3)
    ]
    a.copy_(a_cpu)
    b.copy_(b_cpu)
    with legato.session(output_type=legato.OutputType.BINARY, output_path="vector_add"):
        vector_add(a, b, out)
    actual = out.cpu()  # Synchronous readback waits for the result.
    torch.testing.assert_close(actual, a_cpu + b_cpu, rtol=0, atol=0)
    print("PASS: vector_add [1, 256], BF16, core 0")


if __name__ == "__main__":
    main()
