# =============================================================================
# Makefile for Stanford CS149 Lecture 9 demos (efficiently evaluating DNNs)
# =============================================================================
#
# [What this builds]
#   Two C++ programs that need macOS on Apple silicon: the matrix-multiply
#   ladder (NEON intrinsics + Apple's Accelerate library as the reference
#   "vendor library") and the softmax fusion demo (Accelerate's vectorized
#   exp). The two Python demos need numpy.
#
# [How to use]
#   make            # build
#   make run        # run all demos in lecture order (~10 s)
#   make clean
# -----------------------------------------------------------------------------

CXX      ?= c++
CXXFLAGS := -std=c++20 -O2 -g -Wall -Wextra -pthread
LDLIBS   := -framework Accelerate
PYTHON   ?= python3
HEADERS  := ../lecture01/cs149_timer.h ../lecture01/machine_info.h gemm_neon.h
BINS     := 02_gemm_ladder 03_softmax_fusion
OK_HOST  := $(and $(filter Darwin,$(shell uname -s)),$(filter arm64,$(shell uname -m)))

.PHONY: all run clean
ifeq ($(OK_HOST),)
all:
	@echo "The C++ demos of Lecture 9 need macOS on Apple silicon (NEON + Accelerate); skipping them."
else
all: $(BINS)
endif

$(BINS): %: %.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) -o $@ $< $(LDLIBS)

run: all
	@echo; $(PYTHON) 01_conv_as_gemm.py
	@if [ -x ./02_gemm_ladder ]; then echo; ./02_gemm_ladder; fi
	@if [ -x ./03_softmax_fusion ]; then echo; ./03_softmax_fusion; fi
	@echo; $(PYTHON) 04_flash_attention.py

clean:
	rm -f $(BINS)
	rm -rf *.dSYM __pycache__
