sdm-learn 0.1.0.dev0__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.
- sdm_learn-0.1.0.dev0/LICENSE +201 -0
- sdm_learn-0.1.0.dev0/MANIFEST.in +10 -0
- sdm_learn-0.1.0.dev0/PKG-INFO +35 -0
- sdm_learn-0.1.0.dev0/README.md +1 -0
- sdm_learn-0.1.0.dev0/examples/demo.py +319 -0
- sdm_learn-0.1.0.dev0/pyproject.toml +57 -0
- sdm_learn-0.1.0.dev0/setup.cfg +4 -0
- sdm_learn-0.1.0.dev0/src/sdm/__init__.py +71 -0
- sdm_learn-0.1.0.dev0/src/sdm/__main__.py +51 -0
- sdm_learn-0.1.0.dev0/src/sdm/data.py +238 -0
- sdm_learn-0.1.0.dev0/src/sdm/format.md +84 -0
- sdm_learn-0.1.0.dev0/src/sdm/formats.py +1182 -0
- sdm_learn-0.1.0.dev0/src/sdm/gateway.py +169 -0
- sdm_learn-0.1.0.dev0/src/sdm/learn.py +699 -0
- sdm_learn-0.1.0.dev0/src/sdm/signals.py +386 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/PKG-INFO +35 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/SOURCES.txt +20 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/dependency_links.txt +1 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/entry_points.txt +2 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/requires.txt +19 -0
- sdm_learn-0.1.0.dev0/src/sdm_learn.egg-info/top_level.txt +1 -0
- sdm_learn-0.1.0.dev0/tests/test_sdm.py +1319 -0
|
@@ -0,0 +1,201 @@
|
|
|
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, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
include LICENSE
|
|
2
|
+
include README.md
|
|
3
|
+
recursive-include examples *.py
|
|
4
|
+
recursive-include tests *.py
|
|
5
|
+
|
|
6
|
+
# The GIFs stay out of the distribution: 2.5 MB of animation helps a reader on
|
|
7
|
+
# GitHub and does nothing for an install. The README points at them by URL so
|
|
8
|
+
# the PyPI page still shows them.
|
|
9
|
+
prune assets
|
|
10
|
+
prune runs
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sdm-learn
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Self-documenting models: the document is the model.
|
|
5
|
+
Author: Yulu Gan
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/sunrainyg/sdm
|
|
8
|
+
Project-URL: Repository, https://github.com/sunrainyg/sdm
|
|
9
|
+
Keywords: machine-learning,llm,interpretability,self-documenting,supervised-learning
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: httpx>=0.24
|
|
19
|
+
Provides-Extra: image
|
|
20
|
+
Requires-Dist: Pillow>=9; extra == "image"
|
|
21
|
+
Requires-Dist: cairosvg>=2.5; extra == "image"
|
|
22
|
+
Provides-Extra: audio
|
|
23
|
+
Requires-Dist: numpy>=1.21; extra == "audio"
|
|
24
|
+
Requires-Dist: Pillow>=9; extra == "audio"
|
|
25
|
+
Provides-Extra: video
|
|
26
|
+
Requires-Dist: numpy>=1.21; extra == "video"
|
|
27
|
+
Requires-Dist: Pillow>=9; extra == "video"
|
|
28
|
+
Requires-Dist: cairosvg>=2.5; extra == "video"
|
|
29
|
+
Provides-Extra: all
|
|
30
|
+
Requires-Dist: numpy>=1.21; extra == "all"
|
|
31
|
+
Requires-Dist: Pillow>=9; extra == "all"
|
|
32
|
+
Requires-Dist: cairosvg>=2.5; extra == "all"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# sdm
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# sdm
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""A runnable demonstration of supervised learning in a skill document.
|
|
2
|
+
|
|
3
|
+
python demo.py --fake # no API key needed
|
|
4
|
+
python demo.py --fake --format html # the same loop, HTML skill
|
|
5
|
+
python demo.py # against the real model
|
|
6
|
+
|
|
7
|
+
It scores the no-document baseline first, then learns a skill document from the
|
|
8
|
+
training rows under the gate and scores again, so the printed accuracies
|
|
9
|
+
bracket whatever the learned document was worth.
|
|
10
|
+
|
|
11
|
+
``--fake`` swaps the model for a keyword stub that genuinely reads its own
|
|
12
|
+
skill document and genuinely rewrites it from the revealed labels. It is far
|
|
13
|
+
weaker than an LLM, but it exercises the same loop, so the demo runs offline
|
|
14
|
+
and still shows accuracy moving as the document accumulates signatures.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import re
|
|
21
|
+
from collections import Counter
|
|
22
|
+
|
|
23
|
+
import sdm
|
|
24
|
+
from sdm import gateway
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# --------------------------------------------------------------------------
|
|
28
|
+
# A small labeled dataset. No row contains its own label as a word.
|
|
29
|
+
# --------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
TRAIN = [
|
|
32
|
+
("Congratulations, you are a winner! Claim your free prize now.", "junk"),
|
|
33
|
+
("Standup moved to 10am, check the calendar invite.", "real"),
|
|
34
|
+
("URGENT: wire the deposit today or the offer expires.", "junk"),
|
|
35
|
+
("Here are the slides from yesterday's review.", "real"),
|
|
36
|
+
("Claim your free cash bonus, click the link to continue.", "junk"),
|
|
37
|
+
("Can you review my pull request when you get a chance?", "real"),
|
|
38
|
+
("Guaranteed income from home, no experience needed, act now.", "junk"),
|
|
39
|
+
("The build is failing on main and the tests are red.", "real"),
|
|
40
|
+
("You have won a free cruise! Click here to claim the prize.", "junk"),
|
|
41
|
+
("Moving our one-on-one to Thursday, does that work?", "real"),
|
|
42
|
+
("Final notice: wire transfer required to release your funds.", "junk"),
|
|
43
|
+
("I pushed the fix, the tests are green now.", "real"),
|
|
44
|
+
("Exclusive offer, guaranteed returns, double your cash today.", "junk"),
|
|
45
|
+
("Left a few comments on the design doc.", "real"),
|
|
46
|
+
("Free gift card waiting, claim it before the offer ends.", "junk"),
|
|
47
|
+
("Can we push the deploy until after the demo?", "real"),
|
|
48
|
+
("Lucky winner! Click to claim your cash prize now.", "junk"),
|
|
49
|
+
("Adding the review notes to the calendar invite.", "real"),
|
|
50
|
+
("Verify your account immediately or lose access forever.", "junk"),
|
|
51
|
+
("The deploy is blocked until the tests pass.", "real"),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
TEST = [
|
|
55
|
+
("Claim your free gift card, the offer expires tonight.", "junk"),
|
|
56
|
+
("Do you have the slides from the review meeting?", "real"),
|
|
57
|
+
("Guaranteed cash prize, click the link to claim.", "junk"),
|
|
58
|
+
("Rescheduling the standup to Friday, see the calendar.", "real"),
|
|
59
|
+
("URGENT: wire the funds today, this offer is final.", "junk"),
|
|
60
|
+
("I left comments on the pull request, the tests are green.", "real"),
|
|
61
|
+
("You are our lucky winner, claim your free bonus.", "junk"),
|
|
62
|
+
("The deploy is waiting on the failing build.", "real"),
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
CLASSES = ("junk", "real")
|
|
66
|
+
DESCRIPTION = "Each input is the body of one email."
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def build() -> sdm.Dataset:
|
|
70
|
+
return sdm.dataset(
|
|
71
|
+
[{"text": text, "label": label} for text, label in TRAIN],
|
|
72
|
+
[{"text": text, "label": label} for text, label in TEST],
|
|
73
|
+
classes=CLASSES, name="email", title="Email skill",
|
|
74
|
+
description=DESCRIPTION,
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# --------------------------------------------------------------------------
|
|
79
|
+
# The offline stub
|
|
80
|
+
# --------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
STOPWORDS = {
|
|
83
|
+
"the", "a", "an", "and", "or", "to", "of", "in", "on", "for", "your",
|
|
84
|
+
"you", "i", "is", "are", "was", "it", "me", "my", "we", "at", "that",
|
|
85
|
+
"this", "with", "from", "have", "has", "will", "be", "not", "no", "if",
|
|
86
|
+
"can", "do", "does", "now", "today", "input", "appears", "when",
|
|
87
|
+
# the stub's own document phrasing, so it never counts as evidence
|
|
88
|
+
"body", "mentions", "wording", "such", "any", "one", "signature",
|
|
89
|
+
"signatures", "email", "skill", "learned", "class", "doctype", "html",
|
|
90
|
+
"head", "meta", "charset", "utf", "title", "li", "ul", "hr",
|
|
91
|
+
}
|
|
92
|
+
RULE_LINE_RE = re.compile(r"(R\d{3}) \[support=\d+ used=\d+ hit=\d+\] (.+)")
|
|
93
|
+
LIST_ITEM_RE = re.compile(r"<li>\s*(\w+):\s*([^<]+)</li>")
|
|
94
|
+
SKILL_FILE_RE = re.compile(r"<skill_file[^>]*>(.*?)</skill_file>", re.DOTALL)
|
|
95
|
+
SOURCE_RE = re.compile(r"<current_source>(.*?)</current_source>", re.DOTALL)
|
|
96
|
+
EXAMPLE_RE = re.compile(
|
|
97
|
+
r'<example id="P\d+" true="([^"]+)"[^>]*>\s*(.*?)\s*<evidence>',
|
|
98
|
+
re.DOTALL)
|
|
99
|
+
INPUT_RE = re.compile(r'<input id="P(\d+)">\s*(.*?)\s*</input>', re.DOTALL)
|
|
100
|
+
CURRENT_RE = re.compile(
|
|
101
|
+
r'<current_input id="P(\d+)">\s*(.*?)\s*</current_input>', re.DOTALL)
|
|
102
|
+
DOCUMENT_RE = re.compile(r'<document id="([AB])">(.*?)</document>', re.DOTALL)
|
|
103
|
+
BLOCK_RE = re.compile(r"[Rr]eturn (?:ONLY|only) an? <(\w+)> block")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def words(text: str) -> set[str]:
|
|
107
|
+
return {word for word in re.findall(r"[a-z]+", text.lower())
|
|
108
|
+
if len(word) > 2 and word not in STOPWORDS}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def read_document(text: str) -> dict[str, tuple[str, set[str]]]:
|
|
112
|
+
"""Per-class (rule id, signature words), from Markdown or from HTML.
|
|
113
|
+
|
|
114
|
+
The stub keeps no memory of its own. Like the model, it reads back the
|
|
115
|
+
document it wrote last time, whatever format that document is in.
|
|
116
|
+
"""
|
|
117
|
+
found: dict[str, tuple[str, set[str]]] = {}
|
|
118
|
+
label = "general"
|
|
119
|
+
for line in text.splitlines():
|
|
120
|
+
if line.startswith("### "):
|
|
121
|
+
label = line[4:].strip()
|
|
122
|
+
match = RULE_LINE_RE.search(line)
|
|
123
|
+
if match and label in CLASSES:
|
|
124
|
+
found[label] = (match.group(1), words(match.group(2)))
|
|
125
|
+
for name, listed in LIST_ITEM_RE.findall(text):
|
|
126
|
+
if name in CLASSES:
|
|
127
|
+
found[name] = ("none", words(listed))
|
|
128
|
+
return found
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def flatten(messages: list) -> str:
|
|
132
|
+
parts = []
|
|
133
|
+
for message in messages:
|
|
134
|
+
body = message["content"]
|
|
135
|
+
parts.append(body if isinstance(body, str) else "\n".join(
|
|
136
|
+
block["text"] for block in body if block.get("type") == "text"))
|
|
137
|
+
return "\n".join(parts)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class KeywordModel:
|
|
141
|
+
"""A stub that follows the document it is given and then rewrites it."""
|
|
142
|
+
|
|
143
|
+
def __init__(self):
|
|
144
|
+
self.revisions = 0
|
|
145
|
+
|
|
146
|
+
def _classify(self, text: str, learned) -> tuple[str, str]:
|
|
147
|
+
best, best_score, best_id = CLASSES[0], 0, "none"
|
|
148
|
+
for label, (rule_id, signature) in learned.items():
|
|
149
|
+
score = len(signature & words(text))
|
|
150
|
+
if score > best_score:
|
|
151
|
+
best, best_score, best_id = label, score, rule_id
|
|
152
|
+
return best, best_id
|
|
153
|
+
|
|
154
|
+
def _predictions(self, prompt: str) -> str:
|
|
155
|
+
block = SKILL_FILE_RE.search(prompt)
|
|
156
|
+
learned = read_document(block.group(1) if block else "")
|
|
157
|
+
found = INPUT_RE.findall(prompt) or CURRENT_RE.findall(prompt)
|
|
158
|
+
cites = "R001,R002 or none" in prompt
|
|
159
|
+
lines = []
|
|
160
|
+
for number, text in found:
|
|
161
|
+
label, rule_id = self._classify(text, learned)
|
|
162
|
+
middle = f" {rule_id} |" if cites else ""
|
|
163
|
+
lines.append(f"P{int(number):02d} | {label} |{middle} "
|
|
164
|
+
f"keyword overlap")
|
|
165
|
+
return "<predictions>\n" + "\n".join(lines) + "\n</predictions>"
|
|
166
|
+
|
|
167
|
+
def _gate(self, prompt: str) -> str:
|
|
168
|
+
tail = prompt.split("</document>")[-1]
|
|
169
|
+
found = CURRENT_RE.findall(tail) or INPUT_RE.findall(tail)
|
|
170
|
+
blocks = []
|
|
171
|
+
for letter, body in DOCUMENT_RE.findall(prompt):
|
|
172
|
+
learned = read_document(body)
|
|
173
|
+
lines = [f"P{int(number):02d} | "
|
|
174
|
+
f"{self._classify(text, learned)[0]} | keyword overlap"
|
|
175
|
+
for number, text in found]
|
|
176
|
+
blocks.append(f'<predictions document="{letter}">\n'
|
|
177
|
+
+ "\n".join(lines) + "\n</predictions>")
|
|
178
|
+
return "\n".join(blocks)
|
|
179
|
+
|
|
180
|
+
def _signatures(self, prompt: str) -> dict[str, list[str]]:
|
|
181
|
+
"""Grow each class signature with words this batch separated cleanly."""
|
|
182
|
+
source = SOURCE_RE.search(prompt)
|
|
183
|
+
learned = read_document(source.group(1) if source else "")
|
|
184
|
+
known = {word for _, signature in learned.values()
|
|
185
|
+
for word in signature}
|
|
186
|
+
counts: dict[str, Counter] = {label: Counter() for label in CLASSES}
|
|
187
|
+
for label, body in EXAMPLE_RE.findall(prompt):
|
|
188
|
+
if label in counts:
|
|
189
|
+
counts[label].update(words(body) - known)
|
|
190
|
+
|
|
191
|
+
grown: dict[str, list[str]] = {}
|
|
192
|
+
for label in CLASSES:
|
|
193
|
+
others = Counter()
|
|
194
|
+
for other, counter in counts.items():
|
|
195
|
+
if other != label:
|
|
196
|
+
others.update(counter)
|
|
197
|
+
fresh = sorted(word for word, count in counts[label].items()
|
|
198
|
+
if not others[word])[:6]
|
|
199
|
+
existing = learned.get(label, ("none", set()))[1]
|
|
200
|
+
if fresh or existing:
|
|
201
|
+
grown[label] = sorted(existing | set(fresh))[:30]
|
|
202
|
+
return grown
|
|
203
|
+
|
|
204
|
+
def _revision(self, prompt: str) -> str:
|
|
205
|
+
self.revisions += 1
|
|
206
|
+
block = BLOCK_RE.search(prompt)
|
|
207
|
+
name = block.group(1) if block else "edits"
|
|
208
|
+
grown = self._signatures(prompt)
|
|
209
|
+
if name == "edits":
|
|
210
|
+
return self._edits(prompt, grown)
|
|
211
|
+
return f"<{name}>\n{self._page(grown)}\n</{name}>"
|
|
212
|
+
|
|
213
|
+
@staticmethod
|
|
214
|
+
def _edits(prompt: str, grown: dict[str, list[str]]) -> str:
|
|
215
|
+
source = SOURCE_RE.search(prompt)
|
|
216
|
+
learned = read_document(source.group(1) if source else "")
|
|
217
|
+
edits = []
|
|
218
|
+
for label, signature in grown.items():
|
|
219
|
+
listed = ", ".join(signature)
|
|
220
|
+
if label in learned and learned[label][0] != "none":
|
|
221
|
+
edits.append(f"REVISE | {learned[label][0]} | wording such "
|
|
222
|
+
f"as {listed}")
|
|
223
|
+
else:
|
|
224
|
+
edits.append(f"ADD | {label} | wording such as {listed}")
|
|
225
|
+
return "<edits>\n" + "\n".join(edits or ["NOOP"]) + "\n</edits>"
|
|
226
|
+
|
|
227
|
+
@staticmethod
|
|
228
|
+
def _page(grown: dict[str, list[str]]) -> str:
|
|
229
|
+
"""The same learned signatures, written as a standalone HTML page."""
|
|
230
|
+
items = "\n".join(f"<li>{label}: {', '.join(signature)}</li>"
|
|
231
|
+
for label, signature in grown.items())
|
|
232
|
+
return f"""<!DOCTYPE html>
|
|
233
|
+
<html>
|
|
234
|
+
<head><meta charset="utf-8"><title>Email skill</title></head>
|
|
235
|
+
<body>
|
|
236
|
+
<h1>Email skill</h1>
|
|
237
|
+
<h2>Reading procedure</h2>
|
|
238
|
+
<p>Score the input against each signature below and pick the best overlap.</p>
|
|
239
|
+
<h2>Per-class signatures</h2>
|
|
240
|
+
<ul>
|
|
241
|
+
{items}
|
|
242
|
+
</ul>
|
|
243
|
+
</body>
|
|
244
|
+
</html>"""
|
|
245
|
+
|
|
246
|
+
def __call__(self, session, messages, max_tokens, effort=None) -> str:
|
|
247
|
+
prompt = flatten(messages)
|
|
248
|
+
if "deterministic evaluation component" in prompt:
|
|
249
|
+
return self._gate(prompt)
|
|
250
|
+
if "candidate revision" in prompt:
|
|
251
|
+
return self._revision(prompt)
|
|
252
|
+
return self._predictions(prompt)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
class Session:
|
|
256
|
+
def close(self):
|
|
257
|
+
pass
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def use_stub() -> None:
|
|
261
|
+
# Every module reaches the gateway through model, so replacing the
|
|
262
|
+
# transport there is enough to guarantee this run stays offline.
|
|
263
|
+
gateway.complete = KeywordModel()
|
|
264
|
+
gateway.client = lambda *args, **kwargs: Session()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# --------------------------------------------------------------------------
|
|
268
|
+
|
|
269
|
+
def main(argv=None) -> int:
|
|
270
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
271
|
+
parser.add_argument("--fake", action="store_true",
|
|
272
|
+
help="use the offline keyword stub, no API key needed")
|
|
273
|
+
parser.add_argument("--format", default=None,
|
|
274
|
+
help="a section of format.md; the stub can drive "
|
|
275
|
+
"'markdown' and 'html'")
|
|
276
|
+
parser.add_argument("--batch-size", type=int, default=4)
|
|
277
|
+
parser.add_argument("--cycles", type=int, default=2)
|
|
278
|
+
parser.add_argument("--run-dir", default=None,
|
|
279
|
+
help="checkpoint the run here")
|
|
280
|
+
arguments = parser.parse_args(argv)
|
|
281
|
+
|
|
282
|
+
if arguments.fake:
|
|
283
|
+
use_stub()
|
|
284
|
+
print("FAKE MODEL: a keyword stub stands in for the LLM. The loop is\n"
|
|
285
|
+
"real, the accuracies are only as good as the stub.\n")
|
|
286
|
+
|
|
287
|
+
data = build()
|
|
288
|
+
chosen = arguments.format or sdm.load_formats()[0]
|
|
289
|
+
print(f"{data}\nskill format: {chosen}\n")
|
|
290
|
+
|
|
291
|
+
try:
|
|
292
|
+
control = sdm.train(data, algo="baseline")
|
|
293
|
+
empty = sdm.evaluate(control, data, batch_size=arguments.batch_size)
|
|
294
|
+
print(f"\nno document: {empty}")
|
|
295
|
+
|
|
296
|
+
skill = sdm.train(data, algo="gate", format=arguments.format,
|
|
297
|
+
batch_size=arguments.batch_size,
|
|
298
|
+
holdout_per_class=2, cycles=arguments.cycles,
|
|
299
|
+
run_dir=arguments.run_dir)
|
|
300
|
+
learned = sdm.evaluate(skill, data, batch_size=arguments.batch_size)
|
|
301
|
+
print(f"\nlearned document: {learned}")
|
|
302
|
+
except sdm.SetupNeeded as error:
|
|
303
|
+
print(f"\n{error}\n\nOr run this demo offline with --fake.")
|
|
304
|
+
return 1
|
|
305
|
+
|
|
306
|
+
accepted = sum(entry["decision"]["accepted"]
|
|
307
|
+
for entry in skill.state["candidates"])
|
|
308
|
+
print(f"\ndelta: {learned.accuracy - empty.accuracy:+.1%} on "
|
|
309
|
+
f"{learned.total} test rows, "
|
|
310
|
+
f"{accepted}/{len(skill.state['candidates'])} candidates accepted, "
|
|
311
|
+
f"{len(skill.state['request_audit'])} requests spent")
|
|
312
|
+
print(f"\n{'-' * 70}\n{skill.text}\n{'-' * 70}")
|
|
313
|
+
if arguments.run_dir:
|
|
314
|
+
print(f"\nrun saved to {arguments.run_dir}/")
|
|
315
|
+
return 0
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
if __name__ == "__main__":
|
|
319
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
# The distribution name is sdm-learn because PyPI's `sdm` is taken by an
|
|
7
|
+
# unrelated 2018 package. The import name is `sdm`, which is what appears in
|
|
8
|
+
# the paper and in every example; scikit-learn/sklearn is the same split.
|
|
9
|
+
name = "sdm-learn"
|
|
10
|
+
# One source of truth: sdm.__version__. A PyPI version number can never be
|
|
11
|
+
# reused, so a stale duplicate here is the kind of mistake you cannot undo.
|
|
12
|
+
dynamic = ["version"]
|
|
13
|
+
description = "Self-documenting models: the document is the model."
|
|
14
|
+
readme = "README.md"
|
|
15
|
+
requires-python = ">=3.9"
|
|
16
|
+
license = "Apache-2.0"
|
|
17
|
+
license-files = ["LICENSE"]
|
|
18
|
+
authors = [{ name = "Yulu Gan" }]
|
|
19
|
+
keywords = ["machine-learning", "llm", "interpretability",
|
|
20
|
+
"self-documenting", "supervised-learning"]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 4 - Beta",
|
|
23
|
+
"Intended Audience :: Science/Research",
|
|
24
|
+
"Programming Language :: Python :: 3",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
26
|
+
"Operating System :: OS Independent",
|
|
27
|
+
]
|
|
28
|
+
dependencies = ["httpx>=0.24"]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
# One extra per skill format that renders something. A text-only install needs
|
|
32
|
+
# none of these, which is why they are not in `dependencies`.
|
|
33
|
+
image = ["Pillow>=9", "cairosvg>=2.5"]
|
|
34
|
+
audio = ["numpy>=1.21", "Pillow>=9"]
|
|
35
|
+
video = ["numpy>=1.21", "Pillow>=9", "cairosvg>=2.5"]
|
|
36
|
+
all = ["numpy>=1.21", "Pillow>=9", "cairosvg>=2.5"]
|
|
37
|
+
|
|
38
|
+
[project.scripts]
|
|
39
|
+
sdm = "sdm.__main__:main"
|
|
40
|
+
|
|
41
|
+
[project.urls]
|
|
42
|
+
Homepage = "https://github.com/sunrainyg/sdm"
|
|
43
|
+
Repository = "https://github.com/sunrainyg/sdm"
|
|
44
|
+
|
|
45
|
+
[tool.setuptools]
|
|
46
|
+
package-dir = { "" = "src" }
|
|
47
|
+
|
|
48
|
+
[tool.setuptools.dynamic]
|
|
49
|
+
version = { attr = "sdm.__version__" }
|
|
50
|
+
|
|
51
|
+
[tool.setuptools.packages.find]
|
|
52
|
+
where = ["src"]
|
|
53
|
+
|
|
54
|
+
[tool.setuptools.package-data]
|
|
55
|
+
# format.md ships with the package as the read-only default. `sdm init` copies
|
|
56
|
+
# it out so a project can edit its own.
|
|
57
|
+
sdm = ["format.md"]
|