"""Run with: NEURON_LOGICAL_NC_CONFIG=1 python all_reduce.py"""

# NKI_EXAMPLE_MULTI_RANK_ALL_REDUCE_BEGIN
import nki
import nki.collectives as nccl
import nki.isa as nisa
import nki.language as nl
import numpy as np


@nki.jit
def all_reduce_kernel(x, replica_group):
    src = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.private_hbm)
    out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=src, src=x)
    nccl.all_reduce(srcs=[src], dsts=[out], replica_group=replica_group, op=nl.add)
    return out


# NKI_EXAMPLE_MULTI_RANK_ALL_REDUCE_END


def run_simulation():
    # NKI_EXAMPLE_MULTI_RANK_SIMULATE_BEGIN
    # Rank r's input is filled with r.
    inputs = [np.full((128, 512), rank, dtype=np.float32) for rank in range(2)]
    replica_group = nccl.ReplicaGroup([[0, 1]])

    results = nki.multi_rank_simulate(
        all_reduce_kernel,
        world_size=2,
        per_rank_inputs=[((x,), {"replica_group": replica_group}) for x in inputs],
    )

    # Every rank returns the sum of all ranks' inputs.
    for out in results:
        np.testing.assert_allclose(out, inputs[0] + inputs[1])
    # NKI_EXAMPLE_MULTI_RANK_SIMULATE_END


def run_on_trainium():
    # NKI_EXAMPLE_MULTI_RANK_EXECUTE_BEGIN
    # Rank r's input is filled with r.
    inputs = [np.full((128, 512), rank, dtype=np.float32) for rank in range(2)]
    replica_group = nccl.ReplicaGroup([[0, 1]])

    results = nki.multi_rank_execute(
        all_reduce_kernel,
        world_size=2,
        per_rank_inputs=[((x,), {"replica_group": replica_group}) for x in inputs],
    )

    # Every rank returns the sum of all ranks' inputs.
    for out in results:
        np.testing.assert_allclose(out, inputs[0] + inputs[1])
    # NKI_EXAMPLE_MULTI_RANK_EXECUTE_END


if __name__ == "__main__":
    run_simulation()
