Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
.git
.venv
venv
mlruns
data/external
data/processed
data/audit
**/__pycache__
**/*.pyc
.pytest_cache
.ruff_cache
notebooks
docs/reports
*.egg-info
5 changes: 5 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,8 @@ trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab
end_of_line = lf
insert_final_newline = true
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Makefile text eol=lf
.github/workflows/*.yml text eol=lf
23 changes: 23 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: CI

on:
push:
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
cache: pip
- name: Install
run: |
python -m pip install --upgrade pip
python -m pip install -e ".[dev]"
- name: Ruff
run: python -m ruff check src tests
- name: Pytest
run: python -m pytest -q
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ data/audit/*
# Experiment tracking
mlruns/

# Local model outputs
# Local model outputs (repo-root artifacts, not src/har/models/)
*.pkl
*.joblib
*.onnx
onnx/
/models/

# Packaging
*.egg-info/
Expand Down
32 changes: 32 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
PYTHON ?= python
CONFIG ?= configs/protocol_b_watch_stat_xgb.yaml
RAW_ROOT ?= data/external/wisdm-dataset
PROCESSED_DIR ?= data/processed
HOST ?= 0.0.0.0
PORT ?= 8000

.PHONY: install test audit prepare train eval figures serve

install:
$(PYTHON) -m pip install -e ".[dev]"

test:
$(PYTHON) -m pytest -q

audit:
$(PYTHON) -m har.data.audit --raw-root $(RAW_ROOT)

prepare:
$(PYTHON) -m har.data.repair --raw-root $(RAW_ROOT) --processed-dir $(PROCESSED_DIR)

train:
$(PYTHON) -m har.train --config $(CONFIG)

eval:
$(PYTHON) -m har.evaluate --from-reports docs/reports

figures:
$(PYTHON) -m har.eval.plots --from-reports docs/reports --out docs/figures --sync-mlflow

serve:
$(PYTHON) -m uvicorn har.serve.app:app --host $(HOST) --port $(PORT)
263 changes: 145 additions & 118 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion configs/protocol_a2_phone_raw_flat_xgb.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# protocol_a2_phone_raw_flat_xgb: session-safe 5 s windows + leaky split on repaired phone parquet.
# Same student XGBoost family as A1. Isolates subject/overlap leakage from an
# honest GroupKFold on the same features (Task 9), not parse bugs. The matrix
# honest GroupKFold on the same features, not parse bugs. The matrix
# is already aligned and resampled; full WISDM is an overnight run, not CI.
seed: 42
data:
Expand Down
2 changes: 1 addition & 1 deletion data/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ data/external/wisdm-dataset/
arffmagic-master/
```

Checksum of the zip is recorded in `configs/audit.yaml` as `data.zip_sha256` (null until the first scripted download).
Checksum of the zip is recorded in `configs/audit.yaml` as `data.zip_sha256`. It is null for a manual extract; this dump is identified by Weiss row counts in `docs/data_card.md` (15,630,426 total, exact match). Fill `zip_sha256` after a scripted download.

## Get the files

Expand Down
122 changes: 121 additions & 1 deletion docs/build-log.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build log (blog / video)

Source notes for public writing. Not a second spec. After each plan task, append a section. Commands are copy-pasteable.
Source notes for public writing. Commands are copy-pasteable.

---

Expand Down Expand Up @@ -387,3 +387,123 @@ python -c "import tomllib; from pathlib import Path; p=tomllib.loads(Path('pypro
test ! -e src/har/models/tcn.py && test ! -e configs/phone_tcn.yaml && echo skipped
# skipped
```

---

## Task 12: Export, API, Docker, calibration

**Commit:** pending (you add the commit)

**Story beat:** The product surface is a CPU FastAPI that scores one 5 s window. XGBoost trees ship as ONNX; features stay in Python.

**Shipped:**
- `src/har/models/export.py`: `ModelBundle`, joblib and ONNX (`onnxmltools` + sidecar JSON), `predict_window`, `export_from_config`, `python -m har.models.export`
- `src/har/serve/schema.py`, `src/har/serve/app.py`: `GET /health`, `GET /labels`, `POST /predict`
- `serving/Dockerfile`, `serving/README.md`, `.dockerignore`
- `tests/test_serve.py` (stub 422/happy path, device/hz/channel names, body cap, joblib and ONNX roundtrip, fixture export with YAML `cuda` forced to CPU, `HAR_MODEL_PATH` startup for both artifacts, 100-request p95 bound)
- `docs/model_card.md` (Task 11 skip paragraph plus serving contract and p95)
- `httpx==0.28.1` on the dev extra for FastAPI `TestClient`
- `onnx==1.22.0`, `onnxmltools==1.16.0`, `skl2onnx==1.20.0` on runtime deps (`onnx` 1.22 has a wheel; 1.17 did not)

**Decision:** Prefer ONNX for the served XGBoost head. `onnx==1.17.0` had no wheel and tried a source build; `onnx==1.22.0` is `cp312-abi3` and works on Python 3.13. `onnxmltools.convert_xgboost` matches sklearn `predict_proba` on a fixture. joblib remains for stubs. Abstain is `max(proba) < threshold` with default 0.0 (never abstain). The bundle to train for serving is watch statistical XGBoost (`configs/protocol_b_watch_stat_xgb.yaml`). Export refuses `data.device: both` and `hierarchical`. Export always fits with `device: cpu` even if the YAML says `cuda`. `activity_code` is argmax over the 18-way padded `proba`.

**Gotcha:**
- `POST /predict` `samples` length is `T=100` at 5 s / 20 Hz, not one row. A one-row JSON body is 422.
- GroupKFold metrics in the model card are not the export fit. Export refits on all windows (one subject held out only for early stopping).
- Wrong `T` or `C` is 422; so is `device` or `hz` mismatch. Do not send phone windows to a watch bundle.
- Module-level `har.serve.app:app` loads `HAR_MODEL_PATH` on startup. An `.onnx` path also needs the sidecar `.json`.
- joblib pickle must be exported with the same CPython minor as `serving/Dockerfile` (3.13). ONNX does not have that pickle constraint.
- Bodies over 1 MiB return 413. `samples` is capped at 512 rows.

**Demo clip:**
```bash
python -m pytest tests/test_serve.py -q
# 19 passed
python -c "from pathlib import Path; print(Path('docs/model_card.md').read_text().splitlines()[6][:80])"
# Trees on repaired session features were enough. Protocol B GroupKFold phone sta
python -m har.models.export --config configs/protocol_b_watch_stat_xgb.yaml --out models/watch_stat_xgb.onnx
# writes gitignored onnx + json; then:
# HAR_MODEL_PATH=models/watch_stat_xgb.onnx uvicorn har.serve.app:app --host 0.0.0.0 --port 8000
```

---

## Task 13: CI and Makefile

**Commit:** pending (you add the commit)

**Story beat:** An empty GitHub clone can lint and test without WISDM. Full data stays a local `make audit` / `make prepare` step.

**Shipped:**
- `.github/workflows/ci.yml`: checkout, Python 3.12, `pip install -e ".[dev]"`, `ruff check src tests`, `pytest -q`
- `Makefile` targets: `install`, `test`, `audit`, `prepare`, `train`, `eval`, `serve`
- `tests/fixtures/tiny_wisdm/`: subjects 1600 and 1601, activities A and B, phone accel+gyro, 20 Hz, 3 s per activity
- `tests/test_tiny_wisdm.py`, `tests/test_ci.py`
- `.gitattributes` keeps `Makefile` as LF so Windows checkout does not break GNU make

**Decision:** CI does not call `har.data.download` and does not read `data/external/`. Pytest uses committed fixtures and tmp_path trees. `make test` is pytest only; ruff lives in the workflow. `make serve` does not set `HAR_MODEL_PATH`; export it first as in `serving/README.md`. Default `CONFIG` is watch statistical XGBoost.

**Gotcha:** A CRLF `Makefile` on Linux is `missing separator`. Keep it LF. CI Python is 3.12; local and the serve image are 3.13. First GitHub run is the real empty-clone check. `make audit` / `make prepare` still need a local WISDM dump.

**Demo clip:**
```bash
python -m ruff check src tests
# All checks passed!
python -m pytest tests/test_tiny_wisdm.py tests/test_ci.py tests/test_download.py -q
# 12 passed
python -m pytest -q
# 138 passed
make -n test
# python -m pytest -q
```

---

## Case-study README and metric freeze

**Commit:** pending (you add the commit)

**Story beat:** The README now reads as a short paper. Lead with leaky 0.8925 vs grouped 0.2924 on the same phone flatten, then watch 0.7031 as the number to cite.

**Shipped:**
- `README.md` rewritten around protocol + config cells, audit highlights, method, failure cases, reproduce, API
- `docs/model_card.md`, `docs/data_card.md`, `docs/protocol.md`, `docs/limitations.md` as standalone cards (no work-tracker labels)
- `docs/reports/evaluation.txt` moved to `notebooks/archive/student_evaluation.txt`
- `src/har/data/audit.py` data-card limits name repair as shipped (`python -m har.data.repair`)
- `docs/reports/ablations.md` title and section headings without work-tracker labels

**Decision:** Public writing cites `configs/*.yaml` and `docs/reports/*.json`. The student 0.8559 accuracy stays in the archive next to the notebooks, not in `docs/reports/`. Concat stays labeled as stacked 6-channel windows. Watch sandwich (L) 0.2816 is the actual hard watch class; phone eating per-class F1 0.07-0.11 is worse than stairs/kicking.

**Gotcha:** `docs/data_card.md` is regenerated by `python -m har.data.audit`. Edit `write_data_card`, not only the markdown, or the next audit overwrites the limits paragraph.

**Demo clip:**
```bash
python -m pytest tests/test_audit.py tests/test_ci.py -q
python -c "from pathlib import Path; t=Path('README.md').read_text(); assert '0.8925' in t and '0.2924' in t and '0.7031' in t; print(t.splitlines()[2][:140])"
```

---

## Install pin and portable serve recipe

**Commit:** pending (you add the commit)

**Story beat:** `make install` and GitHub Actions can resolve. Docker no longer bind-mounts a path from this machine.

**Shipped:**
- `pyproject.toml` `pyarrow==19.0.1` so it sits under MLflow 2.22.5's `pyarrow<20`
- `serving/README.md` mounts `$PWD/models:/models`
- `serving/Dockerfile` comment: inference-only image, not a pin workaround
- `.github/workflows/ci.yml` Python 3.13 (same as local and the serve image)
- `data/README.md`: null `zip_sha256` means identity is Weiss row counts in the data card
- `tests/test_ci.py` locks the pyarrow ceiling and the portable mount

**Decision:** Keep MLflow 2.22.5. Drop pyarrow to 19.0.1 (what this venv already ran). Do not bump MLflow just to keep pyarrow 23.

**Gotcha:** A venv that already has pyarrow 23 will look fine until a clean `pip install -e ".[dev]"`. `pip check` on a mixed venv is not enough.

**Demo clip:**
```bash
python -m pytest tests/test_ci.py -q
```

8 changes: 4 additions & 4 deletions docs/data_card.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# WISDM data card

Generated by `python scripts/audit.py`. Sampling rate is implied Hz: `1e9 / median_dt_ns` from timestamp diffs inside a session. Absolute Unix epoch is not used.
Audit of the raw [WISDM Smartphone and Smartwatch Activity and Biometrics Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset) dump on disk. This card describes raw sessions, not the repaired 20 Hz parquet. Regenerate with `python -m har.data.audit` (or `python scripts/audit.py`).

Dataset: [WISDM Smartphone and Smartwatch Activity and Biometrics Dataset (UCI 507)](https://archive.ics.uci.edu/dataset/507/wisdm+smartphone+and+smartwatch+activity+and+biometrics+dataset).
Sampling rate is implied Hz: `1e9 / median_dt_ns` from timestamp diffs inside a session. Absolute Unix epoch is unused.

## Row counts vs Weiss

Expand Down Expand Up @@ -110,6 +110,6 @@ Session implied Hz clustered around the observed peaks: 20, 25, 50, and 100. Do
## Limits

- No demographics (gender, handedness, height, phone model) in this dump, so no fairness slices.
- Start-of-trial seconds may not match the labeled activity; trim is a later repair flag.
- Accel and gyro clocks are not assumed to share sample instants; alignment is a later repair step.
- Start-of-trial seconds may not match the labeled activity. Repair can drop them (`trim_start_s`); the default tree is untrimmed.
- Accel and gyro clocks do not share sample instants. Repair interpolates both onto a shared 20 Hz grid per session (`python -m har.data.repair`).

Binary file added docs/figures/ablations_macro_f1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/leakage_macro_f1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/mlflow_charts_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/mlflow_charts_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/per_class_f1_phone_watch.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/per_group_f1_phone_watch.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/protocol_b_ladder.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/figures/sampling_rate_modes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 17 additions & 8 deletions docs/limitations.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Limitations of the archived student pipeline
# Limitations

This is a description of the 2024 notebook pipeline in `notebooks/archive/`, not of the rebuilt `src/har/` package. Keep these defects in mind when you read `docs/reports/evaluation.txt` (phone accuracy `0.855905403547367`). That number is Protocol A (leaky). It is not a subject-independent HAR result.
The 2024 notebook pipeline in `notebooks/archive/` reported phone accuracy `0.855905403547367` (`notebooks/archive/student_evaluation.txt`). That number is Protocol A (leaky). It is not a subject-independent HAR result. The defects below are why. The rebuilt `src/har/` package avoids them on Protocols B and C; remaining limits of that work are at the end.

## Subject leakage

Expand All @@ -24,24 +24,33 @@ A scaler fit on the full matrix before the split sees test windows. Fit scalers,

## Weak tree features

XGBoost is given `80 x 6 = 480` raw samples. The official ARFF already had distribution bins, peaks, MFCCs, and axis correlations. Flattened raw windows remain the A1/A2 reproduction. Statistical features are the Protocol B default, compared later (RQ3).
XGBoost is given `80 x 6 = 480` raw samples. The official ARFF already had distribution bins, peaks, MFCCs, and axis correlations. Flattened raw windows remain the A1/A2 reproduction. Statistical features are the Protocol B default.

## Exact-timestamp accel/gyro merge

IMU clocks rarely share sample instants. An inner join on the raw timestamp drops and distorts rows. Repair interpolates both streams onto a shared 20 Hz grid per session.

## Unused deep-learning imports

The phone notebook imports Keras CNN pieces. TensorFlow was in `requirements.txt` and is not a v1 runtime dependency. No CNN ships until a logged table shows XGBoost losing on GroupKFold macro-F1.
The phone notebook imports Keras CNN pieces. TensorFlow was in `requirements.txt` and is not a runtime dependency. Trees on repaired session features beat dummy, logreg, RF, and flattened raw under GroupKFold, so no CNN ships.

## Watch data unused

The student result is phone-only with no stated product choice. The dump has watch accel and gyro. Phone vs watch vs fusion is RQ4, under a subject-independent protocol.
The student result is phone-only with no stated product choice. The dump has watch accel and gyro. Under Protocol B, watch statistical XGBoost is 0.7031 macro-F1 and phone is 0.3272 on the same feature family.

## Evaluation writeup

`docs/reports/evaluation.txt` is a generic metric walkthrough, not a model card. It does not name the split, the window identity rules, or the timestamp handling. Rebuilt numbers live next to a protocol name in the README and in MLflow.
`notebooks/archive/student_evaluation.txt` is a generic metric walkthrough, not a model card. It does not name the split, the window identity rules, or the timestamp handling. Frozen numbers live next to a protocol name in the README and in MLflow.

## What this rebuild does not claim yet
## What the honest numbers do not mean

Task 9 filled the Protocol B/C table in the README from `docs/reports/`. A2 is `docs/reports/protocol_a2_phone_raw_flat_xgb.json`. Do not treat A2 vs 0.8559 as a leakage-only delta: the student matrix was unrepaired and concat-windowed. Do not treat statistical GroupKFold XGBoost as the same-representation A vs B gap; that cell is `protocol_b_phone_raw_flat_xgb.json`.
A2 is `docs/reports/protocol_a2_phone_raw_flat_xgb.json`. Do not treat A2 vs 0.8559 as a leakage-only delta: the student matrix was unrepaired and concat-windowed. Do not treat statistical GroupKFold XGBoost as the same-representation A vs B gap; that cell is `docs/reports/protocol_b_phone_raw_flat_xgb.json`.

## Remaining limits of this release

- No demographics, so no fairness analysis.
- Concat (`configs/protocol_b_concat_stat_xgb.yaml`) stacks 6-channel windows from both devices. It is not time-aligned 12-channel fusion.
- Protocol C is 46/5 x 3, not 51-fold LOSO.
- Phone eating and sitting stay weak even after repair. Watch sandwich (L) is 0.2816 F1 under Protocol B.
- The served ONNX bundle is a refit, not a GroupKFold fold. Abstain is uncalibrated (threshold 0.0).
- Mixed raw sampling rates are repaired to 20 Hz; residual orientation flips inside a session are not fully modeled (`reorient` default off; the ablation did not help 18-class phone GroupKFold).
44 changes: 44 additions & 0 deletions docs/model_card.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Model card: WISDM HAR

Intended use: a CPU API that maps one 5 s, 20 Hz IMU window (phone or watch, 6 channels) to one of 18 WISDM activities. Not a medical or safety device.

## Training data

Repaired WISDM 20 Hz parquet from UCI 507. No demographics, so no fairness slice. Timestamp deltas are treated as nanoseconds; absolute epoch is unused. Coverage holes, mixed sampling rates, and row counts: `docs/data_card.md`. Split rules: `docs/protocol.md`. Notebook defects that inflated the old 0.8559 accuracy: `docs/limitations.md`.

## Why trees

Trees on repaired session features were enough. Protocol B GroupKFold phone statistical XGBoost macro-F1 is 0.3272 (`configs/protocol_b_phone_stat_xgb.yaml`), which beats dummy 0.0151 (`configs/protocol_b_phone_stat_dummy.yaml`), logreg 0.2767 (`configs/protocol_b_phone_stat_logreg.yaml`), RF 0.3131 (`configs/protocol_b_phone_stat_rf.yaml`), and flattened raw 0.2924 (`configs/protocol_b_phone_raw_flat_xgb.yaml`). Watch statistical XGBoost is 0.7031 (`configs/protocol_b_watch_stat_xgb.yaml`). Hierarchical is 0.3271 (`configs/ablations/hierarchical.yaml`) and does not beat the flat tree. There is no TCN, no `configs/phone_tcn.yaml`, and no PyTorch extra.

## Served model

| Field | Value |
|-------|--------|
| Recommended bundle | Watch statistical XGBoost from `configs/protocol_b_watch_stat_xgb.yaml` |
| Protocol (metrics) | B, 5-fold GroupKFold on `subject_id` |
| Protocol B macro-F1 | 0.7031 (`docs/reports/protocol_b_watch_stat_xgb.json`) |
| Protocol B accuracy | 0.7013 |
| Features | statistical, 104 dims, 5.0 s window, 20 Hz, `T=100`, `C=6` |
| Artifact | ONNX (`python -m har.models.export --out models/watch_stat_xgb.onnx`) plus sidecar JSON. joblib is a fallback. |
| ONNX | XGBoost trees via `onnxmltools==1.16.0` / `onnx==1.22.0`. Statistical features stay in Python. `onnxruntime==1.20.1` runs the graph. |
| Abstain | `max(proba) < threshold`; default threshold 0.0 (never abstain). Not temperature-scaled. |
| p95 CPU latency | 2.7 ms over 100 `POST /predict` calls (FastAPI TestClient, 200-tree XGBoost, statistical 100x6 window, this CPU). Not Docker/uvicorn and not a 51-subject watch model. Pytest checks a stub path stays under 500 ms. |

Export fits on all windows from that config (one train subject used only for early stopping). That served fit is not a GroupKFold fold. Cite Protocol B numbers from the metrics JSON, not from the export command.

Phone statistical XGBoost is 0.3272 macro-F1 under the same protocol. Concat fusion is 0.5236 and is stacked 6-channel windows, not 12-channel alignment. Do not send a phone window to a watch bundle; the API returns 422 on `device` mismatch.

## Metrics to cite next to any number

- Primary: macro-F1. Also per-class F1, per-group F1 (locomotion, posture, hand, eating), balanced accuracy.
- Leaky student-style accuracy is Protocol A only. Do not put it next to this API.

## Failure modes

Watch group F1 from `docs/reports/protocol_b_watch_stat_xgb.json`: locomotion 0.9292, posture 0.6606, hand 0.8788, eating 0.8450. Sandwich (L) is the weak watch class (per-class F1 0.2816). Stairs 0.7028 and kicking 0.7831.

Phone eating and posture stay hard (eating group F1 0.4945 on `configs/protocol_b_phone_stat_xgb.yaml`; sitting 0.1943; eating per-class F1 0.07-0.11). Stairs 0.6588 and kicking 0.6470 are the weakest locomotion classes on phone. Hierarchical raises eating group F1 on phone (0.5855) but not 18-way macro-F1.

## How to serve

See `serving/README.md`. Endpoints: `GET /health`, `GET /labels`, `POST /predict`. Wrong window length or channel count is 422.
Loading
Loading