#!/usr/bin/env python3
"""toy_echo48s: high-resolution input readout.

Same 1-hot echo as toy_echo48 but the weights are 0.01 * 1-hot, so the output
value equals 0.01 * (value the NPU read at the selected indices).  The output
quantisation range is then tiny and fine-grained: board_output * 100 reveals
exactly which values the NPU sees.

Usage: /root/mmpose-venv/bin/python make_echo48s_toy.py
"""

from __future__ import annotations

from pathlib import Path

import numpy as np
import onnx
from onnx import TensorProto, helper

WORK = Path("/root/handwash-st-gcn-rknn")
OUT = WORK / "output/toys2"
K = 4608
IDX = [i * 658 + 300 for i in range(7)]


def main() -> None:
    pick = np.zeros((K, 7), dtype=np.float32)
    for j, i in enumerate(IDX):
        pick[i, j] = 0.01
    graph = helper.make_graph(
        [helper.make_node("Reshape", ["input", "shape"], ["flat"]),
         helper.make_node("MatMul", ["flat", "P"], ["logits"])],
        "toy_echo48s",
        [helper.make_tensor_value_info("input", TensorProto.FLOAT, [1, 3, 32, 48])],
        [helper.make_tensor_value_info("logits", TensorProto.FLOAT, [1, 7])],
        initializer=[
            helper.make_tensor("shape", TensorProto.INT64, [2], [1, K]),
            helper.make_tensor("P", TensorProto.FLOAT, [K, 7], pick.flatten()),
        ],
    )
    model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 12)])
    model.ir_version = 8
    onnx.checker.check_model(model)
    onnx.save(model, str(OUT / "toy_echo48s.onnx"))

    from rknn.api import RKNN
    rknn = RKNN(verbose=False)
    try:
        assert rknn.config(target_platform="rv1106", mean_values=[[0, 0, 0]],
                           std_values=[[1, 1, 1]],
                           quantized_dtype="asymmetric_quantized-8",
                           optimization_level=3) == 0
        assert rknn.load_onnx(model=str(OUT / "toy_echo48s.onnx")) == 0
        assert rknn.build(do_quantization=True,
                          dataset=str(WORK / "calibration/toy_t1/list.txt")) == 0
        assert rknn.export_rknn(str(OUT / "toy_echo48s_rv1106.rknn")) == 0
    finally:
        rknn.release()
    dest = OUT / "toy_echo48s_rv1106.rknn"
    print(f"    -> {dest.name} ({dest.stat().st_size/1024:.1f} KB)")
    print("板端输出 * 100 = NPU 实际读到的输入值; 期望读值 [-3 -2 -1 0 1 2 3]")


if __name__ == "__main__":
    main()
