"""Ask the language model about a real window: a smartphone on the waist (UCI-HAR test split, participant 2). 1. load SetCon (seed 1) and its language model through transformers 2. turn the phone's raw windows into model windows and set the setup reference from six unlabeled windows 3. ask what the person is doing and how the activity is performed, then let it choose among four activities python examples/ask_lm.py --unimts-dir (see setcon/data.py for the download) Needs the language model's environment (requirements-lm.txt: transformers 5). """ import argparse import json import sys from pathlib import Path import numpy as np import torch REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO)) from setcon import load_model, processing # noqa: E402 from transformers import AutoModel # noqa: E402 ap = argparse.ArgumentParser() ap.add_argument("--unimts-dir", required=True) ap.add_argument("--window", type=int, default=150, help="window of participant 2 to ask about (0-301)") ap.add_argument("--model", default=None, help="local folder or hub id of the repository (default: this one)") a = ap.parse_args() device = "cuda" if torch.cuda.is_available() else "cpu" repo = a.model or str(REPO) setcon = load_model(seed=1, model=repo, device=device) lm = AutoModel.from_pretrained(repo, subfolder="lm", trust_remote_code=True).to(device).eval() # UCI-HAR: 50 Hz, columns 3-5 angular velocity (rad/s), 6-8 total acceleration (g). Participant 2 = windows 0-301. d = Path(a.unimts_dir) / "UCIHAR" X = np.load(d / "X_test.npy")[:302].astype(np.float64) y = np.load(d / "y_test.npy")[:302] classes = [" ".join(v) for v in json.loads((d / "UCIHAR.json").read_text())["label_dictionary"].values()] windows = processing.prepare_device(acc=X[:, :, 6:9] * 9.80665, gyro=X[:, :, 3:6], fs=50) # (302, 200, 9) # Setup reference from six unlabeled windows of the same device, as for zero-shot classification. context = np.random.default_rng(0).choice(len(windows), 6, replace=False) ref = setcon.estimate_reference(windows[context], site="c_spine1") windows = processing.set_reference(windows, ref["reference"]) x = processing.place_devices({"c_spine1": windows[a.window:a.window + 1]}) # (1, 200, 22, 9) print(f"window {a.window}, true class '{classes[int(y[a.window])]}'") for q in ("What is the person doing?", "How is the activity performed in terms of pace?"): print(f"Q: {q}\nA: {lm.ask(setcon, x, q)[0]}") options = ["walking", "sitting", "lying", "walking upstairs"] q = "Which activity is this: " + " ".join(f"{'ABCD'[i]}) {o}" for i, o in enumerate(options)) + "?" choice = lm.choose(setcon, x, q, [f"{'ABCD'[i]}) {o}" for i, o in enumerate(options)])[0] print(f"Q: {q}\nchosen: {options[choice['index']]} (mean token NLL per option: " + ", ".join(f"{v:.2f}" for v in choice["nll"]) + ")")