Repository navigation
Expand file tree
/
Copy pathdirect_report.py
More file actions
96 lines (88 loc) · 22.8 KB
/
Copy pathdirect_report.py
File metadata and controls
96 lines (88 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""Render the Stage 1 report from saved artifacts; never calls an LLM."""
import argparse
import json
from collections import Counter
from pathlib import Path
from project_paths import DEFAULT_DATASET, public_path
from direct_llm import ROOT, CLASSES, read_lines
def percent(x):
return 'N/A' if x is None else f'{x:.2%}'
def matrix_table(matrix):
lines=['| True / predicted | '+' | '.join(CLASSES+['Invalid/missing'])+' |', '|---|'+'---:|'*8]
for label,row in zip(CLASSES,matrix):
lines.append('| '+label+' | '+' | '.join(map(str,row))+' |')
return lines
def build(run, smoke, failed_smoke, data, output):
run,smoke,failed_smoke,data=map(Path,[run,smoke,failed_smoke,data])
e=json.loads((run/'evaluation.json').read_text())
s=json.loads((smoke/'evaluation.json').read_text())
failed=json.loads((failed_smoke/'evaluation.json').read_text())
meta=json.loads((run/'run.json').read_text())
manifest=json.loads((data/'manifest.json').read_text())
rows=read_lines(run/'responses.jsonl')
c={**meta['config'], 'dataset': DEFAULT_DATASET};u=e['uncertainty'];diag=e['identical_inputs']
completion = f"**Completion status: {u['valid_responses']}/{e['overall']['n']} valid predictions.** Status counts: {json.dumps(e['status_counts'])}. "
if u['valid_responses'] < e['overall']['n']:
completion += 'The initial full-validation attempt exhausted OpenRouter account credits (HTTP 402). This is an incomplete inference experiment, not a completed full-validation recognition result. Aggregate failure-inclusive scores measure operational completion as well as correctness; interpret model recognition only on the separately identified valid-response subset.'
else:
completion += 'All observations have valid predictions. Earlier failed attempts remain included in the usage log; final prediction metrics use the successful response for each observation.'
lines=['# PrivSense Stage 1: Direct LLM privacy inference', '', completion, '', '## 1. Research question', '', 'Can a passive LLM infer seven human activities directly from a restricted shake/no-shake binary sequence, without a classifier, examples, tools, or additional sensor knowledge? This report concerns direct inference, not an agentic attack. The earlier experiment-planning pilot is preserved and is not used as a capability-matched baseline.', '', '## 2. Attacker threat model and exact information', '', 'Each stateless request contains only: sensor-system origin; 0 = static/no shake; 1 = shake; the seven candidate activity names; and the actual 100 binary samples. It contains no labels, subject or recording identifiers, sampling rate, placement, duration, raw IMU, class frequencies, features, auxiliary examples, prior responses, or correctness feedback. The meaning static/no shake follows the requested prompt; it must not be interpreted as proof that the body is perfectly motionless.', '', 'The trusted exporter reads labels solely to create evaluator metadata and a stratified smoke subset. The inference runner reads an observations-only JSONL file and constructs a fresh two-message request for every window. Local IDs associate results with truth but are not sent in prompts. There are no tools or classifier calls. OpenRouter and its serving provider receive the binary observations and prompts. The API credential is confined to the authentication header and redacted defensively from persisted results.', '', '## 3. Dataset and construction', '', f'UTAH-STM-HAR, processed right-pocket CSV files, existing dec_tree_out_1 column. Validation subjects 8 and 9 only; {len(manifest["files"])} source recordings, {manifest["windows"]} nonoverlapping 100-sample windows. Sampling is 50 Hz and window duration 2 seconds; neither fact is given to Qwen. Binary values are not changed. Timestamp discontinuities and recording boundaries are never crossed; incomplete tails are dropped. Source SHA-256 hashes, drops and split metadata are saved in the preparation manifest.', '', 'Training users 1–7 remain available only to the separate evaluator for prior-only baselines. Previously inspected test users 10–11 are not read. They must not be described as untouched final test subjects. The smoke subset contains one window per subject/activity (14 total), selected by the fixed seed-42 ordering. It overlaps the full validation set and is not an independent test.', '', '## 4. Exact prompts', '', '### System', '```text',meta['system_prompt'],'```', '', '### User template', '```text',meta['user_template'],'```', '', 'The {sequence} placeholder is replaced with json.dumps(bits): a bracketed, comma-separated list of all 100 observed integers, not a summary. Each response log stores the exact rendered messages. No earlier conversation is appended.', '', '## 5. Model and API configuration', '', '```json',json.dumps(c,indent=2),'```', '', 'Endpoint: https://openrouter.ai/api/v1/chat/completions. Additional request settings: response_format={"type":"json_object"}, provider={"require_parameters":true}, reasoning={"enabled":false}. No model sampling seed or provider pin is set. Source ordering uses seed 42; API outputs are not guaranteed deterministic. Eight concurrent stateless requests use fixed submission order, with completion order associated by local ID. A separate request is made for every duplicate window; no response caching is implemented by this code.', '', 'OpenRouter reasoning control reference: https://openrouter.ai/docs/guides/best-practices/reasoning-tokens . Internal reasoning was disabled after an operational smoke failure, not selected using recognition accuracy. User-visible explanation summaries remain required.', '', '## 6. Execution, schema, and reliability', '', 'The first smoke configuration omitted an explicit reasoning setting. Its 600-token completion allowance was consumed by reasoning, producing no final JSON. All attempts are retained. The second smoke run explicitly disabled reasoning; prompts, observation selection and response length were unchanged. Only after schema validation and a roughly $0.51 projected full-run cost did the full run begin.', '', '| Run | Requests | Statuses | Reported cost USD |', '|---|---:|---|---:|']
for name,v in [('Initial operational smoke',failed),('Configured smoke',s),('Full validation',e)]:
lines.append(f"| {name} | {v['usage']['requests']} | {json.dumps(v['status_counts'])} | {v['usage']['reported_cost_usd']:.6f} |")
lines += ['', 'Response schema: exactly predicted_activity (one of seven labels), nonempty explanation, alternative_activities (distinct valid labels other than the prediction), confidence (numeric 0–1), and sufficient_information (boolean). JSON/schema failures are invalid, not silently repaired. API errors are logged without credentials. No automatic retries are made. The initial implementation submitted every planned request even after credit failure; this produced 1,719 HTTP 402 records. It has now been corrected to stop new submissions on 401/402/403 while preserving in-flight results. Default resume skips completed responses; explicit --resume --retry-api-errors appends attempts for failed API requests only. Successful predictions are never replaced, and all attempt costs remain recorded. Primary scores count invalid/missing responses as incorrect; valid-only metrics are also saved. Confidence does not change forced-choice scoring. No correctness feedback reaches Qwen.', '', '## 7. Evaluation and baseline definitions', '', 'Seven-class accuracy, macro-F1 across all seven labels, balanced accuracy, confusion matrix, moving/stationary accuracy, subject/recording metrics, identical-input groups, self-reported uncertainty, invalid responses, tokens and costs are computed after inference. Moving = Downstairs/Jogging/Upstairs/Walking; stationary = Laying/Sitting/Standing. Moving/stationary predictions are derived from the predicted activity, not a separately prompted answer.', '', 'Baselines: (1) majority label from training users 1–7; (2) analytic uniform guessing; (3) analytic training-prior guessing; (4) a fixed predeclared rule: more than half ones -> Walking, otherwise Sitting. This rule is deliberately a coarse heuristic and does not distinguish activities within a motion group. Prior statistics are never sent to Qwen. Guessing F1 is F1 of the expected confusion matrix, not expected finite-sample F1. No fitted activity classifier is used for any Stage 1 prediction.', '', '## 8. Full validation results (unresolved failures count as errors)', '', '| Method | Accuracy | Balanced accuracy | Macro-F1 | Moving/stationary accuracy |', '|---|---:|---:|---:|---:|']
methods=[('Direct Qwen',e['overall']),('Training-majority',e['baselines']['training_majority']),('Fixed binary rule',e['baselines']['fixed_binary_rule'])]
for name,v in methods:
lines.append(f"| {name} | {percent(v['accuracy'])} | {percent(v['balanced_accuracy'])} | {v['macro_f1']:.5f} | {percent(v['moving_stationary_accuracy'])} |")
for name,key in [('Uniform guessing (analytic)','uniform_guessing'),('Training-prior guessing (analytic)','training_prior_guessing')]:
v=e['baselines'][key]
lines.append(f"| {name} | {percent(v['expected_accuracy'])} | {percent(v['expected_balanced_accuracy'])} | {v['macro_f1_from_expected_confusion']:.5f} | {percent(v['expected_moving_stationary_accuracy'])} |")
if e['valid_only'] and e['valid_only']['n'] < e['overall']['n']:
lines += ['', '### Valid-response subset (not the complete validation set)', '', f"Only {e['valid_only']['n']} windows have usable model answers. They are not a newly selected representative test set. Compare baselines on exactly these same windows; do not compare this accuracy to the full-set pattern bound. The valid-subset pattern bound is {percent(e['valid_subset_pattern_bound'])}.", '', '| Method on valid subset | Accuracy | Balanced accuracy | Macro-F1 | Moving/stationary |', '|---|---:|---:|---:|---:|']
for name,v in [('Direct Qwen',e['valid_only']),('Training-majority',e['baselines_valid_only']['training_majority']),('Fixed binary rule',e['baselines_valid_only']['fixed_binary_rule'])]:
lines.append(f"| {name} | {percent(v['accuracy'])} | {percent(v['balanced_accuracy'])} | {v['macro_f1']:.5f} | {percent(v['moving_stationary_accuracy'])} |")
for name,key in [('Uniform guessing (analytic)','uniform_guessing'),('Training-prior guessing (analytic)','training_prior_guessing')]:
v=e['baselines_valid_only'][key]
lines.append(f"| {name} | {percent(v['expected_accuracy'])} | {percent(v['expected_balanced_accuracy'])} | {v['macro_f1_from_expected_confusion']:.5f} | {percent(v['expected_moving_stationary_accuracy'])} |")
lines += ['', 'On the initial 228 valid responses, Qwen always selected Laying for all-zero inputs and Jogging for all-one inputs. Its apparent accuracy difference from the fixed Walking/Sitting rule reflects the chosen labels and subset frequencies, not additional within-pattern discrimination. No agentic or seven-class recognition advantage is established.']
lines += ['', 'Valid-only Qwen confusion matrix:', '']+matrix_table(e['valid_only']['confusion_matrix'])
lines += ['', '### Qwen confusion matrix', '']+matrix_table(e['overall']['confusion_matrix'])
lines += ['', '### Subject summaries', '', '| Subject | Windows | Accuracy | Macro-F1 | Moving/stationary |', '|---|---:|---:|---:|---:|']
for subject,v in e['by_subject'].items():
lines.append(f"| {subject} | {v['n']} | {percent(v['accuracy'])} | {v['macro_f1']:.5f} | {percent(v['moving_stationary_accuracy'])} |")
if e.get('by_subject_valid_only') and e['valid_only']['n'] < e['overall']['n']:
lines += ['', 'Subject summaries restricted to valid responses:', '', '| Subject | Valid windows | Accuracy | Macro-F1 |', '|---|---:|---:|---:|']
for subject,v in e['by_subject_valid_only'].items():
lines.append(f"| {subject} | {v['n']} | {percent(v['accuracy'])} | {v['macro_f1']:.5f} |")
lines += ['', f"Equal-weight recording-average accuracy: {percent(e['group_macro_summaries']['recording']['accuracy'])}; equal-weight subject-average accuracy: {percent(e['group_macro_summaries']['subject']['accuracy'])}. Recording-level balanced accuracy averages only true classes present in each recording; recording-level F1 still uses all seven labels. These group summaries are descriptive, not independent trials.", '', '### Smoke metrics (pipeline check only)', '', f"Configured smoke: accuracy {percent(s['overall']['accuracy'])}, macro-F1 {s['overall']['macro_f1']:.5f}, moving/stationary accuracy {percent(s['overall']['moving_stationary_accuracy'])}. This balanced 14-window subset has different class weighting from full validation.", '', '## 9. Identical-input information limit', '', f"Unique observable patterns: **{diag['unique_patterns']}**. Examples in patterns shared by multiple activities: **{diag['ambiguous_examples']} / {e['overall']['n']}**. The empirical deterministic pattern accuracy bound is **{percent(diag['empirical_deterministic_pattern_accuracy_bound'])}**.", '', 'For each exact input pattern, the evaluator counts the most frequent true label; summing those counts and dividing by the number of windows gives the bound. It uses evaluation labels and is not a deployable baseline. Randomized predictions may fluctuate around their expected performance; an occasional correct guess does not identify an activity from the observation.', '', '| Pattern | Windows | True activities/counts | Qwen predictions/counts | Group accuracy | Inconsistent labels? |', '|---|---:|---|---|---:|---|']
for p in diag['patterns']:
label='100 zeros' if p['pattern']=='0'*100 else '100 ones' if p['pattern']=='1'*100 else p['pattern']
lines.append(f"| {label} | {p['n']} | {json.dumps(p['label_counts'])} | {json.dumps(p['prediction_counts'])} | {percent(p['accuracy'])} | {p['inconsistent_valid_predictions']} |")
lines += ['', f"Cross-label unordered pairs with identical inputs: {sum(p['contradictory_label_pairs'] for p in diag['patterns'])}. These are pair counts, not independent observations.", '', '## 10. Confidence, uncertainty and failures', '', f"Valid answers: {u['valid_responses']}. Insufficient-information fraction among valid answers: {percent(u['insufficient_information_fraction'])}. Mean confidence: {u['mean_confidence']}. Mean confidence on correct predictions: {u['confidence_when_correct']}; on incorrect predictions: {u['confidence_when_wrong']}. Incorrect answers with confidence >=0.8: {u['high_confidence_wrong_count_0_8']}.", '', '| Confidence bin | Valid responses | Mean confidence | Observed accuracy |', '|---|---:|---:|---:|']
for b in u['confidence_bins']:
lines.append(f"| {b['low']:.1f}–{b['high']:.1f} | {b['n']} | {percent(b['mean_confidence'])} | {percent(b['accuracy'])} |")
lines += ['', 'Bins are left-inclusive and right-exclusive, except the final bin includes 1.0. Confidence is self-reported and not assumed calibrated. Insufficient-information=true/false is reported separately from forced-choice correctness. All predictions remain scored; acknowledging uncertainty does not award accuracy credit.', '', '### Saved explanation examples', '']
seen=set()
for r in sorted(rows,key=lambda r:r['id']):
if r['status']=='valid' and r['pattern'] not in seen:
seen.add(r['pattern'])
lines += [f"Observation {r['id']} ({'all zeros' if r['pattern']=='0'*100 else 'all ones'}):", '```json', json.dumps(r['prediction'],indent=2), '```','']
lines += ['The smoke explanations included unsupported assertions that all-one outputs establish high-frequency, rhythmic or high-intensity motion, and that a run of zeros represents a long duration. Sampling rate, elapsed duration, amplitude, and detector internals are not given. These claims are not established by the supplied sequence. A zero detector output also does not prove absolute physical immobility. Explanation quality is assessed qualitatively here; no automated factuality score or exhaustive annotation is claimed.', '', '## 11. Tokens and cost', '', '```json',json.dumps(e['usage'],indent=2),'```', '', 'Costs are API-reported USD; routing/caching can affect charges. Missing usage fields and timed-out requests may leave costs unaccounted for. Initial operational smoke cost is reported separately rather than hidden. Token totals include repeated identical prompts; model responses are not reused by the harness.', '', '## 12. Limitations and interpretation', '', '- One model, one temperature, one placement, and two validation subjects. Repeated independent runs are supported but robustness is not established by this single full run.', '- Many windows originate from the same recording; no independent-window confidence intervals or significance claims are made.', '- Minimal knowledge includes the semantic phrase static/no shake and the candidate activities. General pretrained activity knowledge may influence guesses, but does not create distinguishing evidence in identical binary observations.', '- A fixed class-list order and forced-choice requirement may bias choices. Self-reported uncertainty is not a substitute for calibrated probabilities.', '- Recognition of moving versus stationary behavior must not be represented as successful seven-class recognition.', '- The empirical information bound applies to these finite observed windows and permitted inputs, not to all sensor placements, devices, or real deployments.', '- The detector firmware, detector-training subjects, and correspondence of these processed outputs to the prior paper remain unverified.', '- The old planner pilot has different information access and is not presented as a direct-LLM baseline.', '- The initial failed smoke and repeated configured smoke are engineering checks; the full validation set includes those observations. This is development evidence, not a fresh final-test claim.', '- The implementation isolates information through separate exports and code paths, not an OS sandbox. No untrusted generated code is executed.', '', '## 13. Recommended Stage 2 experiments (not implemented)', '', '1. Verify binary-output provenance and the original paper’s Game 1 protocol before interpreting discrepancies.', '2. Compare metadata-only additions while holding binary observations fixed: placement, modality, sampling rate, detector purpose. Such facts cannot distinguish truly identical inputs by themselves.', '3. Compare longer coherent observations as a separate factor. Do not concatenate unrelated recordings or expect longer constant sequences to add information.', '4. Add explicitly authorized labeled training examples as a separate auxiliary-information factor; keep all validation labels hidden from the model.', '5. Repeat independent runs and compare class-order sensitivity, confidence behavior, and supported explanation claims under a predeclared protocol.', '', 'Stage 3 autonomy and information requests are not implemented. Stage 1 directly measures passive LLM inference. If any predictions remain unavailable, completion requires account credits and the recovery command below; do not label partial results as a completed full validation run.', '', '## Artifacts and reproduction', '', f'- Full run: `{public_path(run)}`', f'- Configured smoke: `{public_path(smoke)}`', f'- Initial operational smoke: `{public_path(failed_smoke)}`', f'- Prepared observations, evaluator truth, source hashes: `{public_path(data)}`', '- Code: `direct_llm.py`; report renderer: `direct_report.py`; configuration: `configs/direct_llm.json`; tests: `tests/test_direct_llm.py`.', '', '```bash', 'source .venv/bin/activate', '# Preparation already exists in this workspace; run once on a fresh checkout:', 'python direct_llm.py prepare', 'python direct_llm.py infer --smoke --run runs/direct-stage1-smoke-new', 'python direct_llm.py evaluate --smoke --run runs/direct-stage1-smoke-new', 'python direct_llm.py infer --run runs/direct-stage1-repeat', 'python direct_llm.py evaluate --run runs/direct-stage1-repeat', 'python direct_report.py', '# After account credits are available, recover only unsuccessful API requests:', 'python direct_llm.py infer --run runs/direct-stage1-full --resume --retry-api-errors', 'python direct_llm.py evaluate --run runs/direct-stage1-full', 'python direct_report.py', '```', '', 'Use new run directories for repeats. Do not re-run preparation into an existing directory. Copy the config and pass --config to change sampling settings; preserve each run independently. Credentials, data and raw run outputs are ignored by Git. The report contains aggregate results and example outputs, never credentials.']
lines += ['', '## Interpretation of the completed observation set', '', f"Direct Qwen accuracy is {percent(e['overall']['accuracy'])}, macro-F1 {e['overall']['macro_f1']:.5f}, and moving/stationary accuracy {percent(e['overall']['moving_stationary_accuracy'])}. The fixed binary-rule accuracy is {percent(e['baselines']['fixed_binary_rule']['accuracy'])}.", '']
for p in diag['patterns']:
lines.append(f"- {'All-zero' if p['pattern']=='0'*100 else 'All-one' if p['pattern']=='1'*100 else 'Mixed'} input: {json.dumps(p['prediction_counts'])}.")
lines += ['', 'For this completed run, the exact-activity scores match the predeclared simple binary rule. The model distinguishes broad motion groups but does not distinguish the activities sharing an observation. Matching the empirical pattern bound is not evidence of uniquely identifying an activity. Its confidence in exact labels is substantially higher than observed correctness despite acknowledging insufficient information. This establishes a limited direct-inference baseline, not an agentic advantage or a general privacy guarantee.', '']
attempt_statuses = dict(Counter(r['status'] for r in rows))
recovered = sum(r.get('attempt',1)>1 and r['status']=='valid' for r in rows)
recovery_cost = sum((r.get('usage') or {}).get('cost',0) or 0 for r in rows if r.get('attempt',1)>1)
lines += ['', '## Recovery audit', '', f'Persisted attempt statuses (including historical failures): {json.dumps(attempt_statuses)}. Successful recovery predictions: {recovered}. API-reported recovery cost: ${recovery_cost:.6f}. Earlier successful predictions were not replaced. Latest-result status counts above are distinct from attempt counts; historic HTTP 402 failures remain in the usage/audit log. Recovery used the same prompts and model settings.', '']
Path(output).parent.mkdir(parents=True,exist_ok=True)
Path(output).write_text('\n'.join(lines)+'\n')
print(output)
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--run',default=str(ROOT/'runs/direct-stage1-full'))
p.add_argument('--smoke',default=str(ROOT/'runs/direct-stage1-smoke-002'))
p.add_argument('--failed-smoke',default=str(ROOT/'runs/direct-stage1-smoke'))
p.add_argument('--data',default=str(ROOT/'data/direct-stage1'))
p.add_argument('--output',default=str(ROOT/'reports/direct_llm_inference_pilot.md'))
a=p.parse_args();build(a.run,a.smoke,a.failed_smoke,a.data,a.output)