memaudit 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. memaudit-0.1.0/LICENSE +202 -0
  2. memaudit-0.1.0/PKG-INFO +352 -0
  3. memaudit-0.1.0/README.md +311 -0
  4. memaudit-0.1.0/pyproject.toml +85 -0
  5. memaudit-0.1.0/setup.cfg +4 -0
  6. memaudit-0.1.0/src/memaudit/__init__.py +27 -0
  7. memaudit-0.1.0/src/memaudit/__main__.py +3 -0
  8. memaudit-0.1.0/src/memaudit/audit.py +678 -0
  9. memaudit-0.1.0/src/memaudit/callback.py +155 -0
  10. memaudit-0.1.0/src/memaudit/canaries.py +418 -0
  11. memaudit-0.1.0/src/memaudit/cli.py +389 -0
  12. memaudit-0.1.0/src/memaudit/compliance.py +531 -0
  13. memaudit-0.1.0/src/memaudit/constants.py +88 -0
  14. memaudit-0.1.0/src/memaudit/demo.py +372 -0
  15. memaudit-0.1.0/src/memaudit/doctor.py +167 -0
  16. memaudit-0.1.0/src/memaudit/exceptions.py +21 -0
  17. memaudit-0.1.0/src/memaudit/injection.py +371 -0
  18. memaudit-0.1.0/src/memaudit/preflight.py +439 -0
  19. memaudit-0.1.0/src/memaudit/py.typed +0 -0
  20. memaudit-0.1.0/src/memaudit/recommendations.py +84 -0
  21. memaudit-0.1.0/src/memaudit/report.py +276 -0
  22. memaudit-0.1.0/src/memaudit/scoring.py +354 -0
  23. memaudit-0.1.0/src/memaudit/stats.py +276 -0
  24. memaudit-0.1.0/src/memaudit/types.py +53 -0
  25. memaudit-0.1.0/src/memaudit/utils.py +434 -0
  26. memaudit-0.1.0/src/memaudit.egg-info/PKG-INFO +352 -0
  27. memaudit-0.1.0/src/memaudit.egg-info/SOURCES.txt +47 -0
  28. memaudit-0.1.0/src/memaudit.egg-info/dependency_links.txt +1 -0
  29. memaudit-0.1.0/src/memaudit.egg-info/entry_points.txt +2 -0
  30. memaudit-0.1.0/src/memaudit.egg-info/requires.txt +17 -0
  31. memaudit-0.1.0/src/memaudit.egg-info/top_level.txt +1 -0
  32. memaudit-0.1.0/tests/test_adversarial.py +237 -0
  33. memaudit-0.1.0/tests/test_buyer_defaults.py +56 -0
  34. memaudit-0.1.0/tests/test_canaries.py +74 -0
  35. memaudit-0.1.0/tests/test_cli.py +63 -0
  36. memaudit-0.1.0/tests/test_compliance.py +201 -0
  37. memaudit-0.1.0/tests/test_demo_report.py +51 -0
  38. memaudit-0.1.0/tests/test_doctor.py +17 -0
  39. memaudit-0.1.0/tests/test_inject.py +73 -0
  40. memaudit-0.1.0/tests/test_multiseed.py +116 -0
  41. memaudit-0.1.0/tests/test_peft_surfaces.py +100 -0
  42. memaudit-0.1.0/tests/test_preflight.py +103 -0
  43. memaudit-0.1.0/tests/test_product_surface.py +54 -0
  44. memaudit-0.1.0/tests/test_report.py +67 -0
  45. memaudit-0.1.0/tests/test_scoring.py +83 -0
  46. memaudit-0.1.0/tests/test_sft_integration.py +67 -0
  47. memaudit-0.1.0/tests/test_smoke.py +95 -0
  48. memaudit-0.1.0/tests/test_stats.py +78 -0
  49. memaudit-0.1.0/tests/test_verify_provenance.py +181 -0
memaudit-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by such Contributor, or claims asserted against such
174
+ Contributor, by reason of your accepting any additional warranty
175
+ or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 memaudit contributors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,352 @@
1
+ Metadata-Version: 2.4
2
+ Name: memaudit
3
+ Version: 0.1.0
4
+ Summary: Local Trainer/TRL plugin that audits fine-tunes for membership leakage and regurgitation: two verdicts, canaries, PEFT pre-flight, no phone-home
5
+ Author: memaudit contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/mem-audit/memaudit
8
+ Project-URL: Documentation, https://ansh200516.github.io/memaudit-site/
9
+ Project-URL: Source, https://github.com/mem-audit/memaudit
10
+ Project-URL: Issues, https://github.com/mem-audit/memaudit/issues
11
+ Keywords: memorization,membership-inference,canary,privacy,huggingface,trl,lora,peft,gdpr,edpb,fine-tuning
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Legal Industry
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Security
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: transformers>=4.56.2
28
+ Requires-Dist: torch>=2.5
29
+ Requires-Dist: datasets>=2.20
30
+ Requires-Dist: numpy>=1.24
31
+ Requires-Dist: scipy>=1.10
32
+ Provides-Extra: peft
33
+ Requires-Dist: peft<0.21,>=0.15; extra == "peft"
34
+ Provides-Extra: trl
35
+ Requires-Dist: trl<1.0,>=0.15; extra == "trl"
36
+ Provides-Extra: hub
37
+ Requires-Dist: huggingface_hub>=0.24; extra == "hub"
38
+ Provides-Extra: dev
39
+ Requires-Dist: pytest>=8.0; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # memaudit
43
+
44
+ **Training-data memorization auditor for Hugging Face Trainer / TRL fine-tunes.**
45
+
46
+ A local, Apache-2.0 plugin that answers two questions every fine-tune in a regulated setting should document ([EDPB Opinion 28/2024](https://www.edpb.europa.eu/) para 55 / para 58):
47
+
48
+ 1. **Membership** - can an attacker with logprob access tell what was trained on?
49
+ 2. **Regurgitation** - does the model emit training content when prompted with a prefix?
50
+
51
+ memaudit injects pre-registered canaries into the *raw* dataset, runs a PEFT-aware pre-flight when training starts, and writes `memaudit-report.json` when training ends. The same engine is available as a post-hoc CLI (`memaudit audit --ref auto`).
52
+
53
+ It runs **entirely on your machine**. There is no phone-home, no account, no SaaS.
54
+
55
+ > This tool produces **evidence of resistance to the attacks it actually runs**. It does **not** make you GDPR / AI Act / CNIL compliant.
56
+
57
+ ## Who it is for
58
+
59
+ Fine-tuners who have to *document* membership-inference and regurgitation testing (legal / compliance / security reviewers), and engineers who need the audit **inside the training loop** rather than a post-hoc upload.
60
+
61
+ **What you are buying:** a pip-installable, fully-local test layer. You get a versioned JSON report with both verdicts, negative controls, Clopper-Pearson CIs, provenance hashes, and an explicit limitations statement. You do **not** get a compliance certificate, a SaaS dashboard, or paper-scale numbers from this README's tiny demo.
62
+
63
+ ## Measured demo (this repo, not a 7B)
64
+
65
+ These numbers were produced by `python examples/demo.py` on 2026-08-27 (Apple MPS). The model is a **randomly-initialized 1-block TinyDemoLM** (hidden=64, vocab=256), full fine-tune, seed 0. Canaries were 99% of tokens by design so the instrument can show a **positive signal**. This is **not** a pretrained GPT-2 or 7B result.
66
+
67
+ | Metric | Measured value |
68
+ |---|---|
69
+ | Method | base-calibrated Min-K%++ (secret-span) |
70
+ | Inserted canaries / held-out controls | 16 / 100 |
71
+ | Repetition tier | 16x |
72
+ | **TPR @ 1% FPR** | **1.000** (16/16 detected) |
73
+ | 95% CI (Clopper-Pearson) | **[0.794, 1.000]** |
74
+ | Headline valid? | yes (`n_controls=100`) |
75
+ | Regurgitation (exact / BLEU>0.75 / NED<=0.1) | **16/16 = 1.000** at 16x |
76
+ | Negative-control regurgitation | **0.00** (n=100) |
77
+ | Negative-control mean headline score | -15.31 (well below members) |
78
+ | Train wall-clock | 7.0 s (last-batch loss 0.126) |
79
+ | Audit wall-clock | 20.3 s |
80
+ | Seed / schema / tool | 0 / 1.1.0 / 0.1.0 |
81
+
82
+ Reproduce:
83
+
84
+ ```bash
85
+ pip install -e ".[dev]"
86
+ python examples/demo.py # writes examples/demo-report.json
87
+ # or: memaudit demo --output-dir examples
88
+ ```
89
+
90
+ A checked-in copy of that report lives at `examples/demo-report.json`. Re-running the demo overwrites it with whatever *this* machine measures.
91
+
92
+ If a tiny model cannot memorize, memaudit **refuses** a fake TPR@1%FPR rather than inventing one. This run memorized; the CI is wide because n=16 members.
93
+
94
+ ## LoRA benchmark (pretrained distilgpt2, honest budget)
95
+
96
+ Measured 2026-08-27 on Apple MPS. **Not a 7B result.** Canary token budget **0.93%**. Scoring used live `peft.disable_adapter()` (`--ref auto`) on one model copy.
97
+
98
+ | Metric | Run A (1 ep, r=8, lr=2e-4) | Run B (3 ep, r=16, lr=5e-4) |
99
+ |---|---|---|
100
+ | Model | distilgpt2 + LoRA on `c_attn` | same |
101
+ | Host / members / controls | 10,000 / 16 / 100 | same |
102
+ | Repetitions | {1, 4, 16} | same |
103
+ | **TPR @ 1% FPR** | **0.000** (0/16) | **0.000** (0/16) |
104
+ | 95% CI | **[0.000, 0.206]** | **[0.000, 0.206]** |
105
+ | AUC (secondary) | 0.498 | 0.657 |
106
+ | Headline valid | yes | yes |
107
+ | Regurgitation | 0/16 | 0/16 |
108
+ | Negative-control regurgitation | 0.00 | 0.00 |
109
+ | Train / audit wall-clock | 142 s / 68 s | 274 s / 71 s |
110
+ | `reference.mode` | `disable_adapter` | `disable_adapter` |
111
+
112
+ This is the opposite of the overfit demo: at an honest 0.93% canary budget, LoRA did **not** leak at 1% FPR. Run B's AUC rose (0.50 -> 0.66) so ranking moved, but the pre-declared headline stayed 0. That is a measured result, not a missing test. Reproduce:
113
+
114
+ ```bash
115
+ pip install "memaudit[peft,dev]"
116
+ python benchmarks/run_lora_benchmark.py --n-host 10000 --n 16 --n-controls 100 --epochs 1 --lora-r 8
117
+ ```
118
+
119
+ ### Bigger n: 100 members / 200 controls (measured, honest budget)
120
+
121
+ Same pretrained distilgpt2 + LoRA on MPS, 2026-08-27. The script auto-grew the host to **80,000 rows** to keep the canary budget at **0.77%** (<=1%). Multi-seed stability (`--seeds 0,1,2`) included. **Not a 7B result.**
122
+
123
+ | Metric | Run C (safe: 1 ep, r=8, lr 2e-4) | Run D (deliberately risky: 5 ep, r=16, lr 1e-3) |
124
+ |---|---|---|
125
+ | Host / members / controls | 80,000 / 100 / 200 | 80,000 / 100 / 200 |
126
+ | Canary token budget | 0.77% | 0.77% |
127
+ | **TPR @ 1% FPR** (primary calibration) | **0.000** (0/100) | **0.000** (0/100) |
128
+ | 95% CI | **[0.000, 0.036]** | [0.000, 0.036] |
129
+ | **AUC (secondary)** | 0.586 | **0.848** |
130
+ | Regurgitation / control regurgitation | 0/100 / 0.00 (n=200) | 0/100 / 0.00 (n=200) |
131
+ | Stability: per-seed TPR (seeds 0,1,2) | 0.000 / 0.010 / 0.010 (mean 0.007) | **0.000 / 0.090 / 0.090** (mean 0.060) |
132
+ | Train / audit wall-clock | 753 s / 173 s | 2,757 s / 170 s |
133
+
134
+ n=100 is the honest upgrade over n=16: zero detections now cap the true TPR at **3.6%** with 95% confidence (vs 20.6% at n=16). Run D is why the risky config is labeled risky -- and why multi-seed mode exists: the AUC jumps 0.59 -> **0.85** (the member/control distributions clearly separated), and while the primary threshold calibration still lands at 0 detections, two of three bootstrap calibrations detect **9/100 canaries at 1% FPR**. A single-seed run would have reported Run C and Run D as identical headlines; the `stability` block shows the risky config is sitting on the detection edge. No verbatim regurgitation in either run. See `benchmarks/README.md` for all rows and reproduce commands.
135
+
136
+ ## TRL SFTTrainer live run (measured)
137
+
138
+ `benchmarks/run_sft_benchmark.py` runs the full claimed path on a **live `trl.SFTTrainer`** (TRL 0.29.1): prompt/completion dataset, `completion_only_loss=True`, LoRA r=8 on distilgpt2, `inject()` + `MemorizationAuditCallback` end-to-end. Measured 2026-08-27 on Apple MPS, host 10,000 records, canary budget **0.93%** -- same scale as Run A, **not a 7B result**:
139
+
140
+ | Metric | SFT live run (1 ep, r=8, lr=2e-4) |
141
+ |---|---|
142
+ | Trainer | `trl.SFTTrainer`, `completion_only_loss=True` |
143
+ | Host / members / controls | 10,000 / 16 / 100 |
144
+ | Preflight survival scan | **16/16 found** (9 token-level, 7 string-level fallback), 0 fully masked, 10,106 processed rows scanned |
145
+ | **TPR @ 1% FPR** | **0.000** (0/16), 95% CI [0.000, 0.206] |
146
+ | AUC (secondary) | 0.516 |
147
+ | Regurgitation / neg-control regurgitation | 0/16 / 0.00 (n=100) |
148
+ | Stability (seeds 0,1,2) | TPR mean/min/max 0.000 / 0.000 / 0.000 |
149
+ | `reference.mode` | `disable_adapter` |
150
+ | Train / audit wall-clock | 192 s / 52 s |
151
+ | `memaudit verify` on the written report | pass |
152
+
153
+ The value of this run is the **integration evidence**: TRL's tokenized prompt/completion pipeline kept all 16 canaries trainable (the survival scan found 7 of them via string-level fallback where BPE merged tokens across the prompt/completion boundary -- exactly the case the scan's fallback exists for), the callback audited an SFTTrainer-owned PEFT model via `disable_adapter()`, and the result matches the HF-Trainer run at the same scale. Reproduce:
154
+
155
+ ```bash
156
+ pip install "memaudit[peft,trl,dev]"
157
+ python benchmarks/run_sft_benchmark.py --output-dir benchmarks/out-sft \
158
+ --n-host 10000 --n 16 --n-controls 100 --epochs 1 --seeds 0,1,2
159
+ # or as a gated test: MEMAUDIT_RUN_SFT=1 pytest -m integration
160
+ ```
161
+
162
+ ## What it catches (and what it does not)
163
+
164
+ | In scope | Out of scope |
165
+ |---|---|
166
+ | Membership inference (canary MIA, TPR @ 1% FPR + CI) | Model inversion / reconstruction |
167
+ | Prefix-prompted regurgitation (exact / BLEU / edit distance) | Attribute inference |
168
+ | LoRA / PEFT embedding-trainability pre-flight | Shadow-model LiRA, DP certificates |
169
+ | Set-level signal on a sample of *your* real records | Broad red-teaming, PII discovery |
170
+
171
+ Membership and regurgitation **routinely disagree**. A loss-only audit is the wrong answer in both directions; v0.1 always reports both.
172
+
173
+ Default canaries are **high-perplexity regular tokens from the existing vocabulary**. memaudit **never resizes the vocab**. The new-token family is gated and unimplemented in v0.1 (frozen-embedding LoRA leaves new rows untrained and the audit would silently measure noise).
174
+
175
+ Pre-flight **blocks** silent false confidence: wrong canary placement, `fmt` vs column mismatch, ShareGPT `from`/`value`, labels=-100 on the secret, canaries longer than `max_length`, empty inclusion coins, missing tokenizer. TPR@1%FPR is **refused** (not fabricated) when there are fewer than 100 held-out controls.
176
+
177
+ ## Install
178
+
179
+ ```bash
180
+ pip install memaudit # core: transformers, torch, datasets, numpy, scipy
181
+ pip install "memaudit[peft]" # LoRA / adapter-toggle scoring
182
+ pip install "memaudit[trl]" # SFTTrainer lint (optional)
183
+ pip install "memaudit[hub]" # reserved for later model-card push
184
+ pip install -e ".[dev,peft,trl]" # from a clone
185
+ ```
186
+
187
+ Requires Python 3.10+ and `transformers>=4.56.2` (works on 5.x; the callback reads `processing_class`, not the removed `tokenizer=` kwarg).
188
+
189
+ ```bash
190
+ pytest
191
+ memaudit demo --output-dir examples
192
+ ```
193
+
194
+ ## 15-line usage
195
+
196
+ ```python
197
+ from memaudit import generate_canaries, inject, MemorizationAuditCallback
198
+
199
+ canaries = generate_canaries(
200
+ tokenizer, n=32, n_controls=100, family="high_ppl",
201
+ repetitions=(1, 4, 16), seed=0,
202
+ )
203
+ train_ds, manifest = inject(train_ds, canaries, fmt="auto", seed=0)
204
+
205
+ # build SFTTrainer / Trainer on train_ds as usual
206
+ trainer.add_callback(
207
+ MemorizationAuditCallback(
208
+ trainer=trainer, manifest=manifest, real_sample=64, ref="auto",
209
+ )
210
+ )
211
+ trainer.train() # writes <output_dir>/memaudit-report.json
212
+ # ref="auto" is the LoRA one-copy path. Full FT: pass ref=<base model> or ref="none".
213
+ ```
214
+
215
+ **Injection is a pre-train helper.** It cannot live in the callback: transformers builds the dataloader before `on_train_begin`, and TRL tokenizes / loss-masks / packs inside `SFTTrainer.__init__` before any hook fires.
216
+
217
+ The secret is always placed on the **trainable** side of the record (`completion` / assistant turn / `text` body). A prompt- or user-turn canary is labeled `-100` under `completion_only_loss` / `assistant_only_loss` and would silently zero the audit - inject() refuses that placement.
218
+
219
+ Post-hoc / after a ZeRO-3 or FSDP run (in-callback scoring is deferred there):
220
+
221
+ ```bash
222
+ memaudit audit --model ./out --canary-set ./out/memaudit-manifest.json \
223
+ --dataset ./train.jsonl --ref auto
224
+ # --manifest is an alias for --canary-set; both accept the inject() manifest
225
+ ```
226
+
227
+ `--ref auto` uses `disable_adapter()` on an unmerged LoRA so one model copy scores both fine-tuned and base. It **refuses** to silently fall back on a full fine-tune or a merged adapter: pass `--ref <base-checkpoint>` or explicit `--ref none` (target-only Min-K%++, labeled as a downgraded headline).
228
+
229
+ ## What the report means
230
+
231
+ `memaudit-report.json` is schema `1.1.0` (`schema_version`; additive on `1.0.0` -- every 1.0.0 field is still there). Headline fields:
232
+
233
+ | Field | Meaning |
234
+ |---|---|
235
+ | `membership.headline_attack` | Pre-declared **base-calibrated Min-K%++** (same two forwards also yield masked loss, loss ratio, Min-K%) |
236
+ | `membership.tpr_at_1pct_fpr` | Detection rate on inserted canaries at 1% FPR, thresholded on **held-out** canaries. `null` when `n_controls < 100` (`headline_valid=false`) |
237
+ | `membership.ci_low` / `ci_high` | Clopper-Pearson 95% interval. With tens of canaries this interval is wide - that is honest |
238
+ | `membership.auc` | Secondary. Average-case; not the headline |
239
+ | `regurgitation.overall.rate` | Fraction of inserted canaries the model completes from a 25% / 50% prefix (exact, BLEU>0.75, or sliding-window NED<=0.1) |
240
+ | `regurgitation.by_tier` | Same rate at repetition 1 / 4 / 16. 1x is MIA-tier only |
241
+ | `negative_controls` | Never-inserted canaries. Always run |
242
+ | `real_records.set_level` | Exploratory t-test on a sample of real rows vs held-out. Per-record list is **hashed**, not a verdict |
243
+ | `audit_seconds` | Wall-clock of the audit engine |
244
+ | `recommendations` | Heuristics (dedup -> fewer epochs -> cooler LoRA -> ...). Not a compliance program |
245
+ | `compliance_annex` | EDPB Opinion 28/2024 mapping: attack-coverage table (para 55), threat models (para 58(c)), test scope, release context (para 46), limitations. New in 1.1.0 |
246
+ | `release_context` | User-declared `public-api` / `internal` / `open-weights` (default `unspecified`). Never inferred |
247
+ | `stability` | Only with `--seeds`: multi-seed audit-procedure variance (`null` on single-seed runs) |
248
+ | `provenance` | Canary-manifest SHA-256, dataset fingerprint, model/adapter fingerprint, resolved config, python/torch/transformers versions |
249
+ | `report_sha256` | Self-hash of the canonicalized report content, stamped at write time (+ `<report>.sha256` sidecar) |
250
+ | `phone_home` | Always `false` |
251
+ | `local_only` | Always `true` |
252
+
253
+ Scores are computed on the **secret span only**. Full-sequence loss collapses detection.
254
+
255
+ ## Compliance annex, verify, multi-seed (schema 1.1.0)
256
+
257
+ **EDPB-mapped annex.** Every report carries a `compliance_annex` implementing the [EDPB Opinion 28/2024](https://www.edpb.europa.eu/) para 46 / para 55 / para 58 mapping: an attack-coverage table (membership inference para 55(i) and regurgitation para 55(iii) **in scope** with methods; attribute inference, exfiltration para 55(ii), model inversion para 55(iv), reconstruction para 55(v) explicitly **out of scope**), a threat model per attack and per canary family used (attacker access + assumptions, sourced from the published literature), test-scope metadata (n canaries, reps grid, seeds, dataset rows, negative-control results, run date, tool version), the user-declared release context, and a limitations statement quoting para 55: *"successful testing which covers widely known, state-of-the-art attacks can only be evidence for the resistance to those attacks."* The annex is documented test evidence -- it does **not** constitute a determination of anonymity or GDPR compliance. Render it as markdown for a DPO:
258
+
259
+ ```bash
260
+ memaudit report --annex out/memaudit-report.json # markdown to stdout
261
+ memaudit report out/memaudit-report.json -o annex.md # or to a file
262
+ ```
263
+
264
+ **Release context (para 46).** Declare how the model will be exposed -- it changes which attack surface is "reasonably likely": `--release-context public-api|internal|open-weights` (API: `run_audit(..., release_context=...)` or `MemorizationAuditCallback(..., release_context=...)`). Default `unspecified`; the annex then says so.
265
+
266
+ **Provenance + verify.** Reports are self-hashed at write time: `report_sha256` is the SHA-256 of the canonicalized report content (sorted keys, compact separators, minus the hash field), stamped into the JSON and into a `<report>.sha256` sidecar. Check integrity later:
267
+
268
+ ```bash
269
+ memaudit verify out/memaudit-report.json # exit 0 = intact, 1 = mismatch
270
+ ```
271
+
272
+ This proves content integrity, not authorship. Cryptographic signing of the report file (GPG / sigstore) is a release-runbook step outside memaudit; memaudit does not implement key management.
273
+
274
+ **Multi-seed mode.** `--seeds 0,1,2` (API: `run_audit(..., seeds=[0,1,2])`) adds a `stability` block. The model is trained once and canary scoring / greedy generation are deterministic, so what varies per seed is the randomness that actually exists in the audit procedure: bootstrap resampling of held-out control scores (threshold calibration) and real-record sampling. The block is labeled **audit-procedure variance, not training variance** (re-training across seeds is out of scope) and reports `variance: {tpr_mean, tpr_min, tpr_max, tpr_std, per_seed: [...]}`. Single-seed stays the default.
275
+
276
+ ## Architecture (why it is shaped this way)
277
+
278
+ ```
279
+ generate_canaries() # pure; no Trainer
280
+ inject() # raw dataset only
281
+ MemorizationAuditCallback
282
+ on_train_begin # PEFT pre-flight + survival scan (raises on silent-zero configs)
283
+ on_train_end # run_audit, or write a deferred CLI command under ZeRO-3/FSDP
284
+ run_audit() # shared engine (callback + CLI)
285
+ memaudit audit # post-hoc; --canary-set == --manifest == inject() JSON
286
+ memaudit demo # tiny overfit; measured metrics, not paper numbers
287
+ ```
288
+
289
+ Ten landmines encoded in the implementation (source-checked against transformers 5.x / TRL / PEFT):
290
+
291
+ 1. No callback-time injection
292
+ 2. Secret never in the prompt / user turn
293
+ 3. No vocab resize
294
+ 4. Secret-span scoring
295
+ 5. No in-callback forwards under ZeRO-3 / FSDP
296
+ 6. `disable_adapter()` skipped when `bias != "none"` or merged
297
+ 7. Standalone short canary records; warn on `wrapped` packing; skip first packed token
298
+ 8. `model.eval()` + `inference_mode` + unwrap
299
+ 9. `processing_class` only
300
+ 10. Two verdicts, always
301
+
302
+ ## Canary families (v0.1)
303
+
304
+ | Family | Construction |
305
+ |---|---|
306
+ | `high_ppl` **(default)** | Rejection-sample from the base model at high temperature into a PPL band. **If no model is passed**, falls back to rare-token unigram draws from the existing vocab (recorded in `generation_notes`) |
307
+ | `unigram` / `bigram` | Least-likely tokens under corpus n-gram counts; uniform-from-vocab if no corpus |
308
+ | `structured` | `CANARY-ID:...` template + random fill (exposure metric later) |
309
+ | `random` | Uniform existing-vocab draws (also used as control twins) |
310
+ | `new_token` | **Unimplemented.** Would require `resize_token_embeddings` |
311
+
312
+ Defaults: 32 insert-eligible + **100** never-inserted controls (the TPR@1% FPR floor), 25-64 tokens, repetitions `{1,4,16}`, Bernoulli(1/2) inclusion coins. Going below 100 controls emits a warning and the report **refuses** the TPR@1% FPR headline. Use >=200 / >=200 for a production audit.
313
+
314
+ ## Limitations
315
+
316
+ - Small canary counts give wide CIs. Published audits use hundreds to thousands of canaries. v0.1 defaults are a CPU-friendly starting point, not a regulatory sample size.
317
+ - Thresholds are calibrated **on this run's controls** and do not transfer across model families.
318
+ - Real-record per-item flags are noisy (published AUC ~0.72-0.78 on honest fine-tunes). Believe the set-level test, not a single hash.
319
+ - Black-box, final-model audits are structurally loose. A small TPR is not a privacy certificate.
320
+ - The README demo **overfits on purpose** (canaries ~ 99% of tokens). Your production run should stay near the 0.1% token-budget target.
321
+ - Multi-seed mode measures **audit-procedure variance only** (bootstrap threshold calibration + real-record sampling); re-training across seeds is out of scope.
322
+ - DPO / GRPO / Hub model-card push / PII flagging / PANAME mapping are not in v0.1.
323
+ - LoRA-aware, not LoRA-only. Full fine-tunes need `--ref <base-checkpoint>` or explicit `--ref none`.
324
+ - `memaudit demo --lora` needs `memaudit[peft]` **and** a transformers `PreTrainedModel`. The checked-in demo is full FT on `TinyDemoLM`.
325
+
326
+ ## Supported versions (verified on this machine)
327
+
328
+ | Piece | Buyer stack (LoRA bench) | Wheel install (clean venv) |
329
+ |---|---|---|
330
+ | Python | 3.12.11 | 3.12.11 |
331
+ | torch | 2.7.1 (PyPI, MPS) | 2.13.0 (PyPI, MPS) |
332
+ | transformers | 4.56.2 | 5.16.1 |
333
+ | peft | 0.20.0 | not installed (optional extra) |
334
+ | trl | 0.29.1 | not installed (optional extra) |
335
+ | datasets | 3.6.0 | 5.0.1 (pulled by `pip install` wheel) |
336
+
337
+ **Known-bad combo:** transformers 5.16.x + torch 2.6.dev hangs on FSDP imports (`CPUOffloadPolicy`). The hang is the *dev* torch, not 5.16 itself: a clean venv with transformers 5.16.1 + torch 2.13.0 imported and ran `memaudit doctor` here. Do **not** use `--system-site-packages` over a conda torch nightly. Recommended LoRA pin: `transformers==4.56.2` + `torch>=2.5,<2.8` + `peft==0.20.0`.
338
+
339
+ ## Buyer acceptance
340
+
341
+ ```bash
342
+ memaudit doctor --output-dir examples # env + tiny demo + schema
343
+ # or, if a report already exists:
344
+ memaudit doctor --skip-demo --report examples/demo-report.json
345
+ bash scripts/acceptance.sh
346
+ ```
347
+
348
+ The implementation module is `memaudit.injection`. The public helper remains `from memaudit import inject`.
349
+
350
+ ## License
351
+
352
+ Apache-2.0. Local execution is the product; a SaaS re-host does not capture it.