entrenar 0.1.0

Training & Optimization library with autograd, LoRA, quantization, and model merging
Documentation
# Entrenar Makefile
# Training & Optimization Library - Quality Gates
# Following renacer and bashrs EXTREME TDD patterns

.SUFFIXES:

.PHONY: help test coverage coverage-html coverage-clean mutants mutants-quick clean build release lint format check \
	tier1 tier2 tier3 pmat-init pmat-update roadmap-status \
	llama-tests llama-properties llama-mutations llama-chaos llama-gradients llama-fuzz llama-examples llama-ci \
	profile-llama profile-llama-otlp profile-llama-anomaly

help: ## Show this help message
	@echo "Entrenar - Training & Optimization Library"
	@echo ""
	@echo "Available targets:"
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "  \033[36m%-20s\033[0m %s\n", $$1, $$2}'

# =============================================================================
# Tiered TDD Workflow (renacer pattern)
# =============================================================================

tier1: ## Tier 1: Fast tests (<5s) - unit tests, clippy, format, gradient checks
	@echo "๐Ÿƒ Tier 1: Fast tests (<5 seconds)..."
	@cargo fmt --check
	@cargo clippy -- -D warnings
	@cargo test --lib --quiet
	@cargo test --test gradient_llama --quiet
	@echo "โœ… Tier 1 complete!"

tier2: tier1 ## Tier 2: Integration tests (<30s) - includes tier1
	@echo "๐Ÿƒ Tier 2: Integration tests (<30 seconds)..."
	@cargo test --tests --quiet
	@echo "โœ… Tier 2 complete!"

tier3: tier2 ## Tier 3: Full validation (<5m) - includes tier1+2, property tests, chaos tests
	@echo "๐Ÿƒ Tier 3: Full validation (<5 minutes)..."
	@cargo test --all-targets --all-features --quiet
	@cargo test --test property_llama --quiet
	@cargo test --test mutation_resistant_llama --quiet
	@cargo test --test chaos_llama --quiet
	@echo "โœ… Tier 3 complete!"

# =============================================================================
# Basic Development
# =============================================================================

test: ## Run tests (fast, no coverage)
	@echo "๐Ÿงช Running tests..."
	@cargo test --quiet

build: ## Build debug binary
	@echo "๐Ÿ”จ Building debug binary..."
	@cargo build

release: ## Build optimized release binary
	@echo "๐Ÿš€ Building release binary..."
	@cargo build --release
	@echo "โœ… Release binary: target/release/entrenar"

lint: ## Run clippy linter
	@echo "๐Ÿ” Running clippy..."
	@cargo clippy -- -D warnings

format: ## Format code with rustfmt
	@echo "๐Ÿ“ Formatting code..."
	@cargo fmt

check: ## Type check without building
	@echo "โœ… Type checking..."
	@cargo check --all-targets --all-features

clean: ## Clean build artifacts
	@echo "๐Ÿงน Cleaning build artifacts..."
	@cargo clean
	@rm -rf target/coverage
	@echo "โœ… Clean completed!"

# =============================================================================
# Code Coverage (EXTREME TDD requirement: >90%)
# =============================================================================

coverage: ## Generate HTML coverage report and open in browser
	@echo "๐Ÿ“Š Running comprehensive test coverage analysis..."
	@echo "๐Ÿ” Checking for cargo-llvm-cov..."
	@which cargo-llvm-cov > /dev/null 2>&1 || (echo "๐Ÿ“ฆ Installing cargo-llvm-cov..." && cargo install cargo-llvm-cov --locked)
	@if ! rustup component list --installed | grep -q llvm-tools-preview; then \
		echo "๐Ÿ“ฆ Installing llvm-tools-preview..."; \
		rustup component add llvm-tools-preview; \
	fi
	@echo "๐Ÿงน Cleaning old coverage data..."
	@cargo llvm-cov clean --workspace
	@mkdir -p target/coverage/html
	@echo "โš™๏ธ  Temporarily disabling global cargo config (mold/custom linker breaks coverage)..."
	@test -f ~/.cargo/config.toml && mv ~/.cargo/config.toml ~/.cargo/config.toml.cov-backup || true
	@echo "๐Ÿงช Phase 1: Running tests with instrumentation (no report)..."
	@cargo llvm-cov --no-report test --workspace --all-features || true
	@echo "๐Ÿ“Š Phase 2: Generating coverage reports..."
	@cargo llvm-cov report --html --output-dir target/coverage/html || echo "โš ๏ธ  No coverage data generated"
	@cargo llvm-cov report --lcov --output-path target/coverage/lcov.info || echo "โš ๏ธ  LCOV generation skipped"
	@echo "โš™๏ธ  Restoring global cargo config..."
	@test -f ~/.cargo/config.toml.cov-backup && mv ~/.cargo/config.toml.cov-backup ~/.cargo/config.toml || true
	@echo ""
	@echo "๐Ÿ“Š Coverage Summary:"
	@cargo llvm-cov report --summary-only || echo "Run 'cargo test' to generate coverage data first"
	@echo ""
	@echo "๐Ÿ“Š Coverage reports generated:"
	@echo "- HTML: target/coverage/html/index.html"
	@echo "- LCOV: target/coverage/lcov.info"
	@echo ""
	@xdg-open target/coverage/html/index.html 2>/dev/null || \
		open target/coverage/html/index.html 2>/dev/null || \
		echo "โœ… Open target/coverage/html/index.html in your browser"

coverage-html: coverage ## Alias for coverage

coverage-clean: ## Clean coverage artifacts
	@echo "๐Ÿงน Cleaning coverage artifacts..."
	@if command -v cargo-llvm-cov >/dev/null 2>&1; then \
		cargo llvm-cov clean --workspace; \
		echo "โœ… Coverage artifacts cleaned!"; \
	else \
		echo "โš ๏ธ  cargo-llvm-cov not installed, skipping clean."; \
	fi

# =============================================================================
# Mutation Testing (EXTREME TDD requirement: >80% kill rate)
# =============================================================================

mutants: ## Run mutation testing (full analysis)
	@echo "๐Ÿงฌ Running mutation testing..."
	@echo "๐Ÿ” Checking for cargo-mutants..."
	@which cargo-mutants > /dev/null 2>&1 || (echo "๐Ÿ“ฆ Installing cargo-mutants..." && cargo install cargo-mutants --locked)
	@echo "๐Ÿงฌ Running cargo-mutants (this may take several minutes)..."
	@cargo mutants --output target/mutants.out || echo "โš ๏ธ  Some mutants survived"
	@echo ""
	@echo "๐Ÿ“Š Mutation Testing Results:"
	@cat target/mutants.out/mutants.out 2>/dev/null || echo "Check target/mutants.out/ for detailed results"

mutants-quick: ## Run mutation testing (quick check on changed files only)
	@echo "๐Ÿงฌ Running quick mutation testing..."
	@echo "๐Ÿ” Checking for cargo-mutants..."
	@which cargo-mutants > /dev/null 2>&1 || (echo "๐Ÿ“ฆ Installing cargo-mutants..." && cargo install cargo-mutants --locked)
	@echo "๐Ÿงฌ Running cargo-mutants on uncommitted changes..."
	@cargo mutants --in-diff git:HEAD --output target/mutants-quick.out || echo "โš ๏ธ  Some mutants survived"
	@echo ""
	@echo "๐Ÿ“Š Quick Mutation Testing Results:"
	@cat target/mutants-quick.out/mutants.out 2>/dev/null || echo "Check target/mutants-quick.out/ for detailed results"

# =============================================================================
# PMAT Integration (Toyota Way Quality)
# =============================================================================

roadmap-status: ## Show current roadmap status
	@echo "๐Ÿ“Š Roadmap Status:"
	@echo "See roadmap.yaml for ticket details"
	@echo ""
	@grep -A 2 "^summary:" roadmap.yaml | tail -n +2 || echo "โš ๏ธ  roadmap.yaml not found"

pmat-complexity: ## Check code complexity (<10 cyclomatic, <15 cognitive)
	@echo "๐Ÿ“ Checking code complexity..."
	@which pmat > /dev/null 2>&1 || (echo "โŒ PMAT not installed" && exit 1)
	@pmat analyze complexity src/ --max-cyclomatic 10 --max-cognitive 15

pmat-tdg: ## Check Technical Debt Grade (>90 score = A grade)
	@echo "๐Ÿ“Š Checking Technical Debt Grade..."
	@which pmat > /dev/null 2>&1 || (echo "โŒ PMAT not installed" && exit 1)
	@pmat analyze tdg src/ --min-score 90

# =============================================================================
# LLaMA Examples & Testing (Phase 1 Implementation)
# =============================================================================

llama-tests: ## Run all LLaMA-related tests
	@echo "๐Ÿฆ™ Running LLaMA tests..."
	@echo "  ๐Ÿ“Š Property-based tests (13 properties)..."
	@cargo test --test property_llama --quiet
	@echo "  ๐Ÿงฌ Mutation-resistant tests (10 tests)..."
	@cargo test --test mutation_resistant_llama --quiet || true
	@echo "  โšก Chaos engineering tests (15 tests)..."
	@cargo test --test chaos_llama --quiet
	@echo "  ๐ŸŽฏ Gradient checking tests (18 tests)..."
	@cargo test --test gradient_llama --quiet
	@echo "  โœ… Architecture unit tests..."
	@cargo test --example llama2-train --lib --quiet || true
	@echo "โœ… LLaMA tests complete!"

llama-properties: ## Run LLaMA property-based tests (100 iterations/property)
	@echo "๐Ÿ“Š Running LLaMA property-based tests..."
	@cargo test --test property_llama -- --nocapture
	@echo "โœ… 13 properties validated!"

llama-mutations: ## Run LLaMA mutation-resistant tests
	@echo "๐Ÿงฌ Running LLaMA mutation-resistant tests..."
	@cargo test --test mutation_resistant_llama -- --nocapture
	@echo "โœ… Mutation-resistant tests complete!"

llama-chaos: ## Run LLaMA chaos engineering tests
	@echo "โšก Running LLaMA chaos engineering tests..."
	@cargo test --test chaos_llama -- --nocapture
	@echo "โœ… Chaos engineering tests complete!"

llama-gradients: ## Run LLaMA gradient checking tests
	@echo "๐ŸŽฏ Running LLaMA gradient checking tests..."
	@cargo test --test gradient_llama -- --nocapture
	@echo "โœ… Gradient checking tests complete!"

llama-fuzz: ## Run LLaMA fuzz tests (requires cargo-fuzz and libstdc++)
	@echo "๐Ÿ” Running LLaMA fuzz tests..."
	@which cargo-fuzz > /dev/null 2>&1 || (echo "๐Ÿ“ฆ Installing cargo-fuzz..." && cargo install cargo-fuzz)
	@echo "  - parameter_calc (1M iterations)..."
	@cargo fuzz run parameter_calc -- -runs=1000000 2>&1 | grep -E "(Done|ERROR)" || true
	@echo "  - tensor_ops (1M iterations)..."
	@cargo fuzz run tensor_ops -- -runs=1000000 2>&1 | grep -E "(Done|ERROR)" || true
	@echo "  - lora_config (1M iterations)..."
	@cargo fuzz run lora_config -- -runs=1000000 2>&1 | grep -E "(Done|ERROR)" || true
	@echo "โœ… Fuzz testing complete!"

llama-examples: ## Build all LLaMA examples
	@echo "๐Ÿฆ™ Building LLaMA examples..."
	@echo "  ๐Ÿ“ฆ Training from scratch (train.rs)..."
	@cargo build --release --example llama2-train --quiet
	@echo "  ๐Ÿ“ฆ LoRA fine-tuning (finetune_lora.rs)..."
	@cargo build --release --example llama2-finetune-lora --quiet
	@echo "  ๐Ÿ“ฆ QLoRA fine-tuning (finetune_qlora.rs)..."
	@cargo build --release --example llama2-finetune-qlora --quiet
	@echo "โœ… All LLaMA examples built!"
	@echo ""
	@echo "Available examples:"
	@echo "  - ./target/release/examples/llama2-train --config examples/llama2/configs/124m.toml"
	@echo "  - ./target/release/examples/llama2-finetune-lora --model checkpoints/llama-124m.bin"
	@echo "  - ./target/release/examples/llama2-finetune-qlora --model checkpoints/llama-7b.bin"

llama-demo-train: llama-examples ## Demo: Run toy LLaMA training (124M model, 1 epoch)
	@echo "๐Ÿฆ™ Running LLaMA training demo (124M model)..."
	@echo "Config: examples/llama2/configs/124m.toml"
	@echo ""
	@./target/release/examples/llama2-train --config examples/llama2/configs/124m.toml --epochs 1 || true

llama-demo-lora: llama-examples ## Demo: Run LoRA fine-tuning demo
	@echo "๐Ÿฆ™ Running LoRA fine-tuning demo..."
	@./target/release/examples/llama2-finetune-lora || true

llama-demo-qlora: llama-examples ## Demo: Run QLoRA fine-tuning demo
	@echo "๐Ÿฆ™ Running QLoRA fine-tuning demo..."
	@./target/release/examples/llama2-finetune-qlora || true

llama-ci: llama-examples llama-tests ## Run LLaMA CI pipeline (build + test)
	@echo "โœ… LLaMA CI pipeline complete!"
	@echo ""
	@echo "๐Ÿ“Š LLaMA Quality Metrics:"
	@echo "  - โœ… 3 examples built (train, LoRA, QLoRA)"
	@echo "  - โœ… 13 property-based tests passing"
	@echo "  - โœ… 10 mutation-resistant tests"
	@echo "  - โœ… 15 chaos engineering tests"
	@echo "  - โœ… 18 gradient checking tests"
	@echo "  - โœ… 3 fuzz targets (1M+ iterations each)"
	@echo "  - โœ… Parameter-efficient fine-tuning validated"
	@echo ""
	@echo "Memory Benchmarks:"
	@echo "  124M Model:"
	@echo "    - Full FP32:  ~500 MB"
	@echo "    - QLoRA 4-bit: ~125 MB (75% savings)"
	@echo "  7B Model:"
	@echo "    - Full FP32:  ~28 GB"
	@echo "    - QLoRA 4-bit: ~7.5 GB (74% savings)"

# =============================================================================
# Observability & Tracing (Phase 4 - renacer integration)
# =============================================================================

profile-llama: llama-examples ## Profile LLaMA training with renacer (syscall-level bottleneck detection)
	@echo "๐Ÿ” Profiling LLaMA training with renacer..."
	@which renacer > /dev/null 2>&1 || (echo "โš ๏ธ  renacer not installed. Install from: https://github.com/durbanlegend/renacer" && echo "   cargo install renacer" && exit 1)
	@echo "  Running: renacer --function-time --source -- cargo run --release --example llama2-train"
	@echo ""
	@renacer --function-time --source --stats-extended -- \
		cargo run --release --example llama2-train --config examples/llama2/configs/124m.toml --epochs 1 2>&1 || true
	@echo ""
	@echo "โœ… Profiling complete! Check output for hot paths and I/O bottlenecks."

profile-llama-otlp: llama-examples ## Profile LLaMA with OTLP export to Jaeger (requires docker-compose-jaeger.yml)
	@echo "๐Ÿ” Profiling LLaMA training with OTLP export..."
	@which renacer > /dev/null 2>&1 || (echo "โš ๏ธ  renacer not installed" && exit 1)
	@echo "  Ensure Jaeger is running: docker-compose -f docker-compose-jaeger.yml up -d"
	@echo "  View traces at: http://localhost:16686"
	@echo ""
	@renacer --otlp-endpoint http://localhost:4317 \
		--otlp-service-name llama-training \
		--trace-compute \
		--trace-compute-threshold 100 \
		--anomaly-realtime \
		--stats-extended \
		-- cargo run --release --example llama2-train --config examples/llama2/configs/124m.toml --epochs 1 2>&1 || true
	@echo ""
	@echo "โœ… OTLP profiling complete! View traces in Jaeger UI."

profile-llama-anomaly: llama-examples ## Profile LLaMA with ML-based anomaly detection
	@echo "๐Ÿ” Profiling LLaMA training with ML anomaly detection..."
	@which renacer > /dev/null 2>&1 || (echo "โš ๏ธ  renacer not installed" && exit 1)
	@echo ""
	@renacer --ml-anomaly \
		--ml-clusters 5 \
		--ml-compare \
		--anomaly-realtime \
		--anomaly-threshold 3.0 \
		--stats-extended \
		--format json \
		-- cargo run --release --example llama2-train --config examples/llama2/configs/124m.toml --epochs 1 > .pmat/llama-training-profile.json 2>&1 || true
	@echo ""
	@echo "โœ… ML anomaly detection complete! Profile saved to .pmat/llama-training-profile.json"
	@echo "  Run scripts/analyze_training.sh to analyze results."

# =============================================================================
# Dependency Security (bashrs pattern)
# =============================================================================

deny-check: ## Check dependencies for security/license issues
	@echo "๐Ÿ”’ Checking dependencies..."
	@which cargo-deny > /dev/null 2>&1 || (echo "๐Ÿ“ฆ Installing cargo-deny..." && cargo install cargo-deny --locked)
	@cargo deny check

# =============================================================================
# Pre-Commit Checks (run before every commit)
# =============================================================================

pre-commit: tier1 ## Run pre-commit checks (format, lint, fast tests, PMAT TDG)
	@echo "๐ŸŽฏ Running pre-commit checks..."
	@echo "โœ… All pre-commit checks passed!"

# =============================================================================
# CI/CD Simulation (full quality gates)
# =============================================================================

ci: tier3 coverage mutants-quick pmat-complexity pmat-tdg deny-check ## Run full CI pipeline
	@echo "๐ŸŽ‰ All CI checks passed!"
	@echo ""
	@echo "Quality Metrics:"
	@echo "- โœ… All tests passing"
	@echo "- โœ… Code coverage >90%"
	@echo "- โœ… Mutation score >80%"
	@echo "- โœ… Complexity <10"
	@echo "- โœ… TDG score >90"
	@echo "- โœ… Dependencies secure"