# Host build of the Layer 1 core.
#
#   make          build build/host_probe
#   make models   regenerate models/default.m8 and models/moe.bin
#   make run      build, regenerate the models, run the regression
#   make clean
#
# The host uses the published engine config (DUAL_CORE 1 through the pthread
# platform backend). Only the sanity fingerprint is skipped: it is a CRC over
# the float bits of the top-k logits, which is target-specific. The regression
# compares the 24 greedy ids instead.

CC ?= cc
CFLAGS ?= -O2 -std=gnu11 -ffp-contract=off -Wall -Wextra
CPPFLAGS += -DRT_HOST_BUILD=1 -DRT_SKIP_SANITY=1 -I../src -I../src/core -I../src/platform
LDLIBS += -lm -lpthread

# Local research tree; override if it lives elsewhere.
TRANSFORMER ?= ../../esp32s3-int8-transformer

BUILD := build
MODELS := models
MODEL := $(MODELS)/default.m8
MOE := $(MODELS)/moe.bin

CORE := ../src/core/llm.c ../src/core/model_lib.c ../src/core/moe.c \
        ../src/core/tokenizer.c ../src/rt_core.c
HOST := host_probe.c dot_s8_host.c rt_platform_posix.c

.PHONY: all models run check-backend check-affinity clean

all: $(BUILD)/host_probe

check-backend: all
	./check_backend.sh

check-affinity: all
	./check_affinity.sh

$(BUILD)/host_probe: $(HOST) $(CORE) $(wildcard ../src/core/*.h) \
                     $(wildcard ../src/platform/*.h)
	@mkdir -p $(BUILD)
	$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $(HOST) $(CORE) $(LDLIBS)

models:
	@mkdir -p $(MODELS)
	python3 $(TRANSFORMER)/tools/pack_model_m8.py \
	  --model $(TRANSFORMER)/model/stories260K.bin \
	  --tokenizer $(TRANSFORMER)/model/tok512.bin \
	  --out $(MODEL) --name "stories260k-q8" \
	  --sanity-dump $(TRANSFORMER)/logs/golden-logits-2026-11-25.log \
	  --sanity-label int8 --sanity-step 0
	cp $(TRANSFORMER)/runs/moe4-stageB-crc.moe $(MOE)
	@sha256sum $(MODEL) $(MOE)

run: all models
	./$(BUILD)/host_probe $(MODEL) $(MOE)

clean:
	rm -rf $(BUILD)
