meme-core 0.1.0__py3-none-any.whl
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.
- meme_core/__init__.py +30 -0
- meme_core/guard/__init__.py +45 -0
- meme_core/guard/core.py +392 -0
- meme_core/guard/templates.py +93 -0
- meme_core/solver_bon/__init__.py +43 -0
- meme_core/solver_bon/core.py +244 -0
- meme_core-0.1.0.dist-info/METADATA +257 -0
- meme_core-0.1.0.dist-info/RECORD +10 -0
- meme_core-0.1.0.dist-info/WHEEL +4 -0
- meme_core-0.1.0.dist-info/licenses/LICENSE +190 -0
meme_core/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""
|
|
2
|
+
meme-core: Memory-Compute Pareto Analysis Core for Small Language Models
|
|
3
|
+
|
|
4
|
+
A minimal, open-source Python library for structured test-time memory strategies
|
|
5
|
+
and solver-based Best-of-N verification.
|
|
6
|
+
|
|
7
|
+
Components:
|
|
8
|
+
- guard: Guarded memory strategies with prose fallback
|
|
9
|
+
- solver_bon: Best-of-N selection using constraint solvers
|
|
10
|
+
|
|
11
|
+
Usage:
|
|
12
|
+
>>> from meme_core import guard, solver_bon
|
|
13
|
+
>>> strategy = guard.GuardedMemory(strategy="M3G", structure_kind="constraints")
|
|
14
|
+
>>> prompt = strategy.render(question="Who is the engineer?", constraints=[...])
|
|
15
|
+
>>> best_answer = solver_bon.best_of_n(answers, problem, use_solver=True)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
__author__ = "Abel"
|
|
20
|
+
|
|
21
|
+
from meme_core.guard import GuardedMemory, render_prompt
|
|
22
|
+
from meme_core.solver_bon import best_of_n, ConstraintSolver
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"GuardedMemory",
|
|
26
|
+
"render_prompt",
|
|
27
|
+
"best_of_n",
|
|
28
|
+
"ConstraintSolver",
|
|
29
|
+
"__version__",
|
|
30
|
+
]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""
|
|
2
|
+
guard: Guarded Memory Strategies
|
|
3
|
+
|
|
4
|
+
Implements memory strategies that fall back to plain prose when there is no
|
|
5
|
+
auxiliary material to structure, preventing the 30-50pp accuracy drop observed
|
|
6
|
+
with unstructured memory on pure-retrieval tasks.
|
|
7
|
+
|
|
8
|
+
Supported strategies:
|
|
9
|
+
- M2G/M3G/M4G: Block-authoritative guarded strategies
|
|
10
|
+
- M2Q/M3Q/M4Q: Question-authoritative guarded strategies
|
|
11
|
+
|
|
12
|
+
Reference:
|
|
13
|
+
MEME Project v3.7+ (https://github.com/abel/meme-llm)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from meme_core.guard.core import (
|
|
17
|
+
GuardedMemory,
|
|
18
|
+
render_prompt,
|
|
19
|
+
has_structure,
|
|
20
|
+
SYSTEM_PROMPT,
|
|
21
|
+
Problem,
|
|
22
|
+
)
|
|
23
|
+
from meme_core.guard.templates import (
|
|
24
|
+
TEMPLATE_M0,
|
|
25
|
+
TEMPLATE_M1,
|
|
26
|
+
TEMPLATE_M2,
|
|
27
|
+
TEMPLATE_M3,
|
|
28
|
+
TEMPLATE_M4,
|
|
29
|
+
TEMPLATE_GUARDED_BLOCK,
|
|
30
|
+
TEMPLATE_GUARDED_QUESTION,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"GuardedMemory",
|
|
35
|
+
"render_prompt",
|
|
36
|
+
"has_structure",
|
|
37
|
+
"SYSTEM_PROMPT",
|
|
38
|
+
"TEMPLATE_M0",
|
|
39
|
+
"TEMPLATE_M1",
|
|
40
|
+
"TEMPLATE_M2",
|
|
41
|
+
"TEMPLATE_M3",
|
|
42
|
+
"TEMPLATE_M4",
|
|
43
|
+
"TEMPLATE_GUARDED_BLOCK",
|
|
44
|
+
"TEMPLATE_GUARDED_QUESTION",
|
|
45
|
+
]
|
meme_core/guard/core.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core implementation of guarded memory strategies.
|
|
3
|
+
|
|
4
|
+
The guarded strategies fix two defects found in v3.0-v3.6:
|
|
5
|
+
1. EMPTY SCAFFOLD: When a problem has no auxiliary material, M2 renders
|
|
6
|
+
"- (no explicit constraints listed)" yet the instruction says
|
|
7
|
+
"Using ONLY the facts above" — the model is told to rely on nothing.
|
|
8
|
+
2. AUTHORITY INVERSION: "Using ONLY the facts above" makes the scaffold
|
|
9
|
+
authoritative over the question. When extraction fails, the model is
|
|
10
|
+
pinned to the noise.
|
|
11
|
+
|
|
12
|
+
The guarded strategies fix both:
|
|
13
|
+
- If there is nothing to structure, fall back to plain prose (M0)
|
|
14
|
+
- Otherwise render the scaffold with configurable authority framing
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from typing import Optional
|
|
22
|
+
|
|
23
|
+
# Minimum constraints/facts needed for a structured rendering to be meaningful
|
|
24
|
+
_STRUCTURE_MIN_ITEMS = 2
|
|
25
|
+
|
|
26
|
+
# What kind of auxiliary material a problem provides
|
|
27
|
+
STRUCTURE_KINDS = {
|
|
28
|
+
"constraints", # Puzzle givens to satisfy (ZebraLogic)
|
|
29
|
+
"quantities", # Numeric givens (GSM8K-Hard)
|
|
30
|
+
"options", # Fixed choice set (ARC)
|
|
31
|
+
"facts", # Statements to chain (HotpotQA)
|
|
32
|
+
"none", # Nothing to structure (TriviaQA, HumanEval)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
STRUCTURE_HINT = {
|
|
36
|
+
"constraints": "constraints",
|
|
37
|
+
"quantities": "given quantities",
|
|
38
|
+
"options": "answer options",
|
|
39
|
+
"facts": "facts",
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Problem:
|
|
45
|
+
"""Represents a problem for evaluation.
|
|
46
|
+
|
|
47
|
+
Attributes:
|
|
48
|
+
id: Unique problem identifier
|
|
49
|
+
question: The question text
|
|
50
|
+
expected: Expected answer (ground truth)
|
|
51
|
+
constraints: List of constraint/fact strings
|
|
52
|
+
structure_kind: Type of auxiliary material ("constraints", "quantities",
|
|
53
|
+
"options", "facts", or "none")
|
|
54
|
+
aliases: Acceptable answer variants (e.g., "Austen" for "Jane Austen")
|
|
55
|
+
"""
|
|
56
|
+
id: int
|
|
57
|
+
question: str
|
|
58
|
+
expected: str
|
|
59
|
+
constraints: list[str] = field(default_factory=list)
|
|
60
|
+
structure_kind: str = "none"
|
|
61
|
+
aliases: list[str] = field(default_factory=list)
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def from_dict(cls, data: dict) -> "Problem":
|
|
65
|
+
"""Create a Problem from a dictionary (e.g., loaded from JSONL)."""
|
|
66
|
+
return cls(
|
|
67
|
+
id=data["id"],
|
|
68
|
+
question=data["question"],
|
|
69
|
+
expected=str(data["expected"]),
|
|
70
|
+
constraints=data.get("constraints", []),
|
|
71
|
+
structure_kind=data.get("structure_kind", "none"),
|
|
72
|
+
aliases=data.get("aliases", []),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# Shared system prompt for all memory strategies
|
|
77
|
+
SYSTEM_PROMPT = (
|
|
78
|
+
"You are a precise solver. Reason step by step. "
|
|
79
|
+
"On the very last line, write `Answer: <final value>` — for example, "
|
|
80
|
+
"`Answer: Bob` or `Answer: 42`. Replace `<final value>` with the actual answer."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def has_structure(problem: Problem) -> bool:
|
|
85
|
+
"""Check if a problem offers material a structured view can organize.
|
|
86
|
+
|
|
87
|
+
Returns False when:
|
|
88
|
+
- structure_kind is "none" (pure retrieval tasks)
|
|
89
|
+
- There are fewer than 2 constraints/facts to organize
|
|
90
|
+
"""
|
|
91
|
+
if problem.structure_kind == "none":
|
|
92
|
+
return False
|
|
93
|
+
if len(problem.constraints) < _STRUCTURE_MIN_ITEMS:
|
|
94
|
+
return False
|
|
95
|
+
return True
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _extract_entity(constraint: str) -> str:
|
|
99
|
+
"""Best-effort entity extraction from a constraint sentence.
|
|
100
|
+
|
|
101
|
+
Handles common ZebraLogic phrasings:
|
|
102
|
+
- "X is [not] Y" / "X wears Y" / "X has Y" / "X studies Y" / "X likes Y"
|
|
103
|
+
- "Spot/House/Position/Seat N: X"
|
|
104
|
+
|
|
105
|
+
Falls back to first capitalized word.
|
|
106
|
+
"""
|
|
107
|
+
# Possessive patterns: "X's Y is Z" → entity = X
|
|
108
|
+
m = re.match(r"^([A-Z]\w+)'s\b", constraint)
|
|
109
|
+
if m:
|
|
110
|
+
return m.group(1) + "'s"
|
|
111
|
+
|
|
112
|
+
# "X is [not] Y" / "X wears Y" / "X has Y" / ...
|
|
113
|
+
m = re.match(
|
|
114
|
+
r"^([A-Z]\w+)\s+(?:is|are|wears|has|studies|lives|likes|drinks|owns)\b",
|
|
115
|
+
constraint,
|
|
116
|
+
)
|
|
117
|
+
if m:
|
|
118
|
+
return m.group(1)
|
|
119
|
+
|
|
120
|
+
# "Spot/House/Position/Seat N: X"
|
|
121
|
+
m = re.match(r"^((?:Spot|House|Position|Seat)\s*\d+)\s*:", constraint)
|
|
122
|
+
if m:
|
|
123
|
+
return m.group(1)
|
|
124
|
+
|
|
125
|
+
# "The X of Y" or "The X is in Y" → use second capitalized word
|
|
126
|
+
caps = re.findall(r"\b([A-Z][a-z]+)\b", constraint)
|
|
127
|
+
if len(caps) >= 2:
|
|
128
|
+
return caps[1]
|
|
129
|
+
if caps:
|
|
130
|
+
return caps[0]
|
|
131
|
+
|
|
132
|
+
return "?"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def render_m3(constraints: list[str]) -> str:
|
|
136
|
+
"""M3: entity-grouped facts (extracted from raw constraints)."""
|
|
137
|
+
by_entity: dict[str, list[str]] = {}
|
|
138
|
+
for c in constraints:
|
|
139
|
+
ent = _extract_entity(c)
|
|
140
|
+
if ent not in by_entity:
|
|
141
|
+
by_entity[ent] = []
|
|
142
|
+
by_entity[ent].append(c)
|
|
143
|
+
|
|
144
|
+
lines = []
|
|
145
|
+
for ent, facts in by_entity.items():
|
|
146
|
+
lines.append(f"### {ent}")
|
|
147
|
+
for f in facts:
|
|
148
|
+
lines.append(f" - {f}")
|
|
149
|
+
return "\n".join(lines)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def render_m4(constraints: list[str]) -> str:
|
|
153
|
+
"""M4: knowledge-graph view (entity -[polarity]-> attribute triples)."""
|
|
154
|
+
lines = ["Knowledge graph (entity --[POS|NEG]--> attribute):"]
|
|
155
|
+
for c in constraints:
|
|
156
|
+
polarity = "NEG" if re.search(r"\bnot\b", c, re.IGNORECASE) else "POS"
|
|
157
|
+
ent = _extract_entity(c)
|
|
158
|
+
# Strip the leading entity name to leave just the attribute portion
|
|
159
|
+
attr = re.sub(r"^[A-Z]\w+\s*", "", c).strip()
|
|
160
|
+
attr = attr.lstrip(".,;:") or "?"
|
|
161
|
+
|
|
162
|
+
# Special-case location constraints
|
|
163
|
+
m = re.match(r"^((?:Spot|House|Position|Seat)\s*\d+)\s*:\s*(.+)$", c)
|
|
164
|
+
if m:
|
|
165
|
+
ent = m.group(1)
|
|
166
|
+
attr = m.group(2)
|
|
167
|
+
|
|
168
|
+
lines.append(f" {ent} --[{polarity}]--> {attr}")
|
|
169
|
+
return "\n".join(lines)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class GuardedMemory:
|
|
173
|
+
"""Guarded memory strategy renderer.
|
|
174
|
+
|
|
175
|
+
The guarded strategies fix two defects in plain M2/M3/M4:
|
|
176
|
+
1. Empty scaffold: falls back to prose when there's nothing to structure
|
|
177
|
+
2. Authority inversion: supports both block-authoritative and
|
|
178
|
+
question-authoritative wording
|
|
179
|
+
|
|
180
|
+
Strategies:
|
|
181
|
+
- M0: No memory, raw prose question (baseline)
|
|
182
|
+
- M1: Full context + explicit constraint enumeration
|
|
183
|
+
- M2: Structured bullet constraints
|
|
184
|
+
- M3: Entity-grouped facts (auto-extracted)
|
|
185
|
+
- M4: Knowledge-graph triples
|
|
186
|
+
- M2G/M3G/M4G: Block-authoritative guarded (recommended for constraint tasks)
|
|
187
|
+
- M2Q/M3Q/M4Q: Question-authoritative guarded (recommended for retrieval tasks)
|
|
188
|
+
|
|
189
|
+
Example:
|
|
190
|
+
>>> problem = Problem(
|
|
191
|
+
... id=1,
|
|
192
|
+
... question="Who is the engineer?",
|
|
193
|
+
... expected="Alice",
|
|
194
|
+
... constraints=["Alice is the engineer", "Bob is the doctor"],
|
|
195
|
+
... structure_kind="constraints"
|
|
196
|
+
... )
|
|
197
|
+
>>> strategy = GuardedMemory(strategy="M3G")
|
|
198
|
+
>>> prompt = strategy.render(problem)
|
|
199
|
+
"""
|
|
200
|
+
|
|
201
|
+
def __init__(self, strategy: str = "M0"):
|
|
202
|
+
"""Initialize with a memory strategy.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
strategy: One of M0, M1, M2, M3, M4, B0, B1,
|
|
206
|
+
M2G, M3G, M4G, M2Q, M3Q, M4Q
|
|
207
|
+
"""
|
|
208
|
+
self.strategy = strategy.upper()
|
|
209
|
+
self._validate()
|
|
210
|
+
|
|
211
|
+
def _validate(self) -> None:
|
|
212
|
+
valid = {
|
|
213
|
+
"M0", "M1", "M2", "M3", "M4",
|
|
214
|
+
"B0", "B1",
|
|
215
|
+
"M2G", "M3G", "M4G",
|
|
216
|
+
"M2Q", "M3Q", "M4Q",
|
|
217
|
+
}
|
|
218
|
+
if self.strategy not in valid:
|
|
219
|
+
raise ValueError(
|
|
220
|
+
f"Unknown strategy: {self.strategy}. "
|
|
221
|
+
f"Valid: {', '.join(sorted(valid))}"
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
@property
|
|
225
|
+
def is_guarded(self) -> bool:
|
|
226
|
+
"""True if this is a guarded strategy (M*G or M*Q)."""
|
|
227
|
+
return self.strategy.endswith("G") or self.strategy.endswith("Q")
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def authority(self) -> Optional[str]:
|
|
231
|
+
"""Authority framing: 'block', 'question', or None for non-guarded."""
|
|
232
|
+
if self.strategy.endswith("Q"):
|
|
233
|
+
return "question"
|
|
234
|
+
if self.strategy.endswith("G"):
|
|
235
|
+
return "block"
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
def render(self, problem: Problem) -> str:
|
|
239
|
+
"""Render the full prompt for a given problem.
|
|
240
|
+
|
|
241
|
+
Args:
|
|
242
|
+
problem: The Problem instance to render
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
The formatted prompt string
|
|
246
|
+
"""
|
|
247
|
+
return render_prompt(self.strategy, problem)
|
|
248
|
+
|
|
249
|
+
def __repr__(self) -> str:
|
|
250
|
+
return f"GuardedMemory(strategy='{self.strategy}')"
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# Template strings
|
|
254
|
+
TEMPLATE_M0 = """Question: {question}
|
|
255
|
+
|
|
256
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
TEMPLATE_M1 = """Question: {question}
|
|
260
|
+
|
|
261
|
+
First, list all known constraints or facts explicitly (one per line).
|
|
262
|
+
Then reason step by step using those constraints.
|
|
263
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
TEMPLATE_M2 = """Given the following constraints:
|
|
267
|
+
{constraints}
|
|
268
|
+
|
|
269
|
+
Question: {question}
|
|
270
|
+
|
|
271
|
+
Using ONLY the constraints above, reason step by step.
|
|
272
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
TEMPLATE_M3 = """Known facts grouped by entity (auto-extracted):
|
|
276
|
+
{structured}
|
|
277
|
+
|
|
278
|
+
Question: {question}
|
|
279
|
+
|
|
280
|
+
Using ONLY the facts above, reason step by step.
|
|
281
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
282
|
+
"""
|
|
283
|
+
|
|
284
|
+
TEMPLATE_M4 = """{structured}
|
|
285
|
+
|
|
286
|
+
Question: {question}
|
|
287
|
+
|
|
288
|
+
Using ONLY the graph above, reason step by step.
|
|
289
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
290
|
+
"""
|
|
291
|
+
|
|
292
|
+
# B0: Long-Context baseline
|
|
293
|
+
TEMPLATE_B0 = """You are given the complete problem context below. Read all of it,
|
|
294
|
+
then answer the question at the end. Do not summarize — use the full context.
|
|
295
|
+
|
|
296
|
+
{question}
|
|
297
|
+
|
|
298
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
299
|
+
"""
|
|
300
|
+
|
|
301
|
+
# Guarded template variants
|
|
302
|
+
TEMPLATE_GUARDED_BLOCK = """{structured}
|
|
303
|
+
|
|
304
|
+
Question: {question}
|
|
305
|
+
|
|
306
|
+
Using ONLY the {kind} above, reason step by step.
|
|
307
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
308
|
+
"""
|
|
309
|
+
|
|
310
|
+
TEMPLATE_GUARDED_QUESTION = """{structured}
|
|
311
|
+
|
|
312
|
+
Question: {question}
|
|
313
|
+
|
|
314
|
+
The block above is a reading aid only. The QUESTION is authoritative: if the
|
|
315
|
+
block omits, contradicts, or is irrelevant to the question, follow the question.
|
|
316
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
317
|
+
"""
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _render_guarded(strategy: str, problem: Problem) -> str:
|
|
321
|
+
"""Render a guarded strategy (M2G/M3G/M4G/M2Q/M3Q/M4Q).
|
|
322
|
+
|
|
323
|
+
Args:
|
|
324
|
+
strategy: The guarded strategy name
|
|
325
|
+
problem: The Problem to render
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
Formatted prompt string
|
|
329
|
+
"""
|
|
330
|
+
authority = "question" if strategy.endswith("Q") else "block"
|
|
331
|
+
base = strategy.rstrip("GQ")
|
|
332
|
+
|
|
333
|
+
# If nothing to structure, fall back to prose (this is the key fix)
|
|
334
|
+
if not has_structure(problem):
|
|
335
|
+
return TEMPLATE_M0.format(question=problem.question)
|
|
336
|
+
|
|
337
|
+
kind = STRUCTURE_HINT.get(problem.structure_kind, "material")
|
|
338
|
+
|
|
339
|
+
if base == "M2":
|
|
340
|
+
body = "\n".join(f"- {c}" for c in problem.constraints)
|
|
341
|
+
structured = f"{kind.capitalize()} (verbatim list):\n{body}"
|
|
342
|
+
elif base == "M3":
|
|
343
|
+
structured = f"{kind.capitalize()} grouped (auto-extracted):\n" + render_m3(
|
|
344
|
+
problem.constraints
|
|
345
|
+
)
|
|
346
|
+
elif base == "M4":
|
|
347
|
+
structured = render_m4(problem.constraints)
|
|
348
|
+
else:
|
|
349
|
+
raise ValueError(f"Unknown base strategy: {base}")
|
|
350
|
+
|
|
351
|
+
tmpl = TEMPLATE_GUARDED_QUESTION if authority == "question" else TEMPLATE_GUARDED_BLOCK
|
|
352
|
+
return tmpl.format(structured=structured, question=problem.question, kind=kind)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def render_prompt(strategy: str, problem: Problem) -> str:
|
|
356
|
+
"""Render a prompt for a given memory strategy.
|
|
357
|
+
|
|
358
|
+
Args:
|
|
359
|
+
strategy: Memory strategy (M0, M1, M2, M3, M4, B0, B1, or guarded variants)
|
|
360
|
+
problem: The Problem to render
|
|
361
|
+
|
|
362
|
+
Returns:
|
|
363
|
+
Formatted prompt string
|
|
364
|
+
"""
|
|
365
|
+
if strategy == "M0":
|
|
366
|
+
return TEMPLATE_M0.format(question=problem.question)
|
|
367
|
+
|
|
368
|
+
if strategy == "M1":
|
|
369
|
+
return TEMPLATE_M1.format(question=problem.question)
|
|
370
|
+
|
|
371
|
+
if strategy == "M2":
|
|
372
|
+
bullets = "\n".join(f"- {c}" for c in problem.constraints) or "- (no explicit constraints listed)"
|
|
373
|
+
return TEMPLATE_M2.format(constraints=bullets, question=problem.question)
|
|
374
|
+
|
|
375
|
+
if strategy == "M3":
|
|
376
|
+
return TEMPLATE_M3.format(
|
|
377
|
+
structured=render_m3(problem.constraints), question=problem.question
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
if strategy == "M4":
|
|
381
|
+
return TEMPLATE_M4.format(
|
|
382
|
+
structured=render_m4(problem.constraints), question=problem.question
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
if strategy == "B0":
|
|
386
|
+
return TEMPLATE_B0.format(question=problem.question)
|
|
387
|
+
|
|
388
|
+
# Guarded strategies
|
|
389
|
+
if strategy in ("M2G", "M3G", "M4G", "M2Q", "M3Q", "M4Q"):
|
|
390
|
+
return _render_guarded(strategy, problem)
|
|
391
|
+
|
|
392
|
+
raise ValueError(f"Unknown memory strategy: {strategy}")
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Template strings for memory strategies.
|
|
3
|
+
|
|
4
|
+
These templates define how problems are rendered for each memory strategy.
|
|
5
|
+
The guarded strategies (M*G/M*Q) have two authority variants:
|
|
6
|
+
- Block-authoritative: The structured block is the authoritative restatement
|
|
7
|
+
- Question-authoritative: The question outranks the block
|
|
8
|
+
|
|
9
|
+
Reference: MEME Project v3.7+
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
# M0: No memory, raw prose question (baseline)
|
|
13
|
+
TEMPLATE_M0 = """Question: {question}
|
|
14
|
+
|
|
15
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
# M1: Full context + explicit constraint enumeration
|
|
19
|
+
TEMPLATE_M1 = """Question: {question}
|
|
20
|
+
|
|
21
|
+
First, list all known constraints or facts explicitly (one per line).
|
|
22
|
+
Then reason step by step using those constraints.
|
|
23
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
# M2: Structured constraints (memory-compressed)
|
|
27
|
+
TEMPLATE_M2 = """Given the following constraints:
|
|
28
|
+
{constraints}
|
|
29
|
+
|
|
30
|
+
Question: {question}
|
|
31
|
+
|
|
32
|
+
Using ONLY the constraints above, reason step by step.
|
|
33
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
# M3: Entity-grouped facts (auto-extracted)
|
|
37
|
+
TEMPLATE_M3 = """Known facts grouped by entity (auto-extracted):
|
|
38
|
+
{structured}
|
|
39
|
+
|
|
40
|
+
Question: {question}
|
|
41
|
+
|
|
42
|
+
Using ONLY the facts above, reason step by step.
|
|
43
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
# M4: Knowledge-graph triples
|
|
47
|
+
TEMPLATE_M4 = """{structured}
|
|
48
|
+
|
|
49
|
+
Question: {question}
|
|
50
|
+
|
|
51
|
+
Using ONLY the graph above, reason step by step.
|
|
52
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
# B0: Long-Context baseline
|
|
56
|
+
TEMPLATE_B0 = """You are given the complete problem context below. Read all of it,
|
|
57
|
+
then answer the question at the end. Do not summarize — use the full context.
|
|
58
|
+
|
|
59
|
+
{question}
|
|
60
|
+
|
|
61
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
# B1: RAG baseline (requires embedding model)
|
|
65
|
+
TEMPLATE_B1 = """Relevant context (retrieved, top-{k} of {n} items):
|
|
66
|
+
{retrieved}
|
|
67
|
+
|
|
68
|
+
Question: {question}
|
|
69
|
+
|
|
70
|
+
Using ONLY the retrieved context above, reason step by step.
|
|
71
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
# Guarded strategies: Block-authoritative
|
|
75
|
+
# The structured block is the authoritative restatement
|
|
76
|
+
TEMPLATE_GUARDED_BLOCK = """{structured}
|
|
77
|
+
|
|
78
|
+
Question: {question}
|
|
79
|
+
|
|
80
|
+
Using ONLY the {kind} above, reason step by step.
|
|
81
|
+
Your very last line must start with `Answer:` followed by the final value.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
# Guarded strategies: Question-authoritative
|
|
85
|
+
# The question outranks the block (better for retrieval tasks)
|
|
86
|
+
TEMPLATE_GUARDED_QUESTION = """{structured}
|
|
87
|
+
|
|
88
|
+
Question: {question}
|
|
89
|
+
|
|
90
|
+
The block above is a reading aid only. The QUESTION is authoritative: if the
|
|
91
|
+
block omits, contradicts, or is irrelevant to the question, follow the question.
|
|
92
|
+
Reason step by step. Your very last line must start with `Answer:` followed by the final value.
|
|
93
|
+
"""
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""
|
|
2
|
+
solver_bon: Best-of-N Selection with Constraint Solver Verification
|
|
3
|
+
|
|
4
|
+
Implements Best-of-N answer selection using a constraint solver as the reward
|
|
5
|
+
model. For constraint-satisfaction tasks with a unique verified solution,
|
|
6
|
+
this provides deterministic ground-truth comparison without requiring an LLM
|
|
7
|
+
reward model.
|
|
8
|
+
|
|
9
|
+
This is particularly effective for:
|
|
10
|
+
- ZebraLogic-style constraint satisfaction puzzles
|
|
11
|
+
- GSM8K-Hard arithmetic problems with verifiable solutions
|
|
12
|
+
- Any task where the ground truth is computable
|
|
13
|
+
|
|
14
|
+
Key insight (from MEME v3.9):
|
|
15
|
+
Best-of-N without a verifier has no selection criterion and degenerates
|
|
16
|
+
to a random sample. Using the constraint solver as the reward model
|
|
17
|
+
makes BoN deterministic and maximally effective.
|
|
18
|
+
|
|
19
|
+
Usage:
|
|
20
|
+
>>> from meme_core.solver_bon import best_of_n, ConstraintSolver
|
|
21
|
+
>>> solver = ConstraintSolver()
|
|
22
|
+
>>> winner, scores = best_of_n(
|
|
23
|
+
... answers=["10", "10.25", "10.5"],
|
|
24
|
+
... problem=problem,
|
|
25
|
+
... use_solver=True
|
|
26
|
+
... )
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from meme_core.solver_bon.core import (
|
|
30
|
+
best_of_n,
|
|
31
|
+
ConstraintSolver,
|
|
32
|
+
normalize_for_comparison,
|
|
33
|
+
score_with_solver,
|
|
34
|
+
__version__,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"best_of_n",
|
|
39
|
+
"ConstraintSolver",
|
|
40
|
+
"normalize_for_comparison",
|
|
41
|
+
"score_with_solver",
|
|
42
|
+
"__version__",
|
|
43
|
+
]
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Core implementation of Best-of-N with constraint solver verification.
|
|
3
|
+
|
|
4
|
+
For constraint-satisfaction tasks (structure_kind == "constraints"), the
|
|
5
|
+
expected answer IS the output of the constraint solver (every problem was
|
|
6
|
+
verified to have exactly one solution). Scoring is therefore deterministic:
|
|
7
|
+
100 if the answer matches the ground truth, 0 otherwise.
|
|
8
|
+
|
|
9
|
+
Reference:
|
|
10
|
+
MEME Project v3.9+ (https://github.com/abel/meme-llm)
|
|
11
|
+
Paper: "Memory is the Cheap Axis: Pareto Analysis of Test-Time Memory
|
|
12
|
+
and Compute for Small Language Models"
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from typing import Optional, Any
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class ScoreResult:
|
|
27
|
+
"""Result of scoring a candidate answer.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
answer: The candidate answer string
|
|
31
|
+
correct: Whether the answer is correct
|
|
32
|
+
confidence: Confidence score (0-100)
|
|
33
|
+
raw: Raw scoring output ("solver" for ground-truth comparison)
|
|
34
|
+
"""
|
|
35
|
+
answer: Optional[str]
|
|
36
|
+
correct: bool
|
|
37
|
+
confidence: int
|
|
38
|
+
raw: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def normalize_for_comparison(value: str, expected: str) -> bool:
|
|
42
|
+
"""Strict-ish answer comparison.
|
|
43
|
+
|
|
44
|
+
Order of tolerance (loosest last):
|
|
45
|
+
1. Exact normalized equality
|
|
46
|
+
2. Numeric equality within 0.01
|
|
47
|
+
3. Expected appears in the answer as a whole word
|
|
48
|
+
4. Last token of the answer equals last token of expected
|
|
49
|
+
|
|
50
|
+
Deliberately NOT a bare substring test to avoid false positives like
|
|
51
|
+
"...(e.g., lawyer, engineer, etc.)" scoring as correct for "engineer".
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
value: The extracted answer value
|
|
55
|
+
expected: The expected ground truth
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
True if the answer matches the expected value
|
|
59
|
+
"""
|
|
60
|
+
v = value.strip().lower().rstrip(".")
|
|
61
|
+
e = expected.strip().lower().rstrip(".")
|
|
62
|
+
|
|
63
|
+
if not v or not e:
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
# 1. Exact match
|
|
67
|
+
if v == e:
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
# 2. Numeric equality within tolerance
|
|
71
|
+
try:
|
|
72
|
+
return abs(float(v) - float(e)) < 0.01
|
|
73
|
+
except ValueError:
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
# 3. Whole-word match
|
|
77
|
+
if re.search(r"(?<![a-z0-9])" + re.escape(e) + r"(?![a-z0-9])", v):
|
|
78
|
+
return True
|
|
79
|
+
|
|
80
|
+
# 4. Last-token match
|
|
81
|
+
vt = re.findall(r"[a-z0-9]+", v)
|
|
82
|
+
et = re.findall(r"[a-z0-9]+", e)
|
|
83
|
+
return bool(vt and et and vt[-1] == et[-1])
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ConstraintSolver:
|
|
87
|
+
"""Constraint solver for verifying answers to constraint-satisfaction problems.
|
|
88
|
+
|
|
89
|
+
This solver provides deterministic ground-truth comparison for tasks where
|
|
90
|
+
the expected answer is the verified unique solution (e.g., ZebraLogic).
|
|
91
|
+
|
|
92
|
+
For open-ended tasks without a computable ground truth, use an LLM-based
|
|
93
|
+
reward model instead.
|
|
94
|
+
|
|
95
|
+
Example:
|
|
96
|
+
>>> solver = ConstraintSolver()
|
|
97
|
+
>>> result = solver.score(
|
|
98
|
+
... candidate_answer="lawyer",
|
|
99
|
+
... problem=problem,
|
|
100
|
+
... )
|
|
101
|
+
>>> print(result.correct, result.confidence)
|
|
102
|
+
True 100
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def score(
|
|
106
|
+
self,
|
|
107
|
+
candidate_answer: Optional[str],
|
|
108
|
+
expected: str,
|
|
109
|
+
aliases: Optional[list[str]] = None,
|
|
110
|
+
) -> ScoreResult:
|
|
111
|
+
"""Score a candidate answer against the expected answer.
|
|
112
|
+
|
|
113
|
+
Args:
|
|
114
|
+
candidate_answer: The answer to score
|
|
115
|
+
expected: The expected ground truth answer
|
|
116
|
+
aliases: Acceptable surface variants of the answer
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
ScoreResult with correct flag and confidence score
|
|
120
|
+
"""
|
|
121
|
+
if candidate_answer is None:
|
|
122
|
+
return ScoreResult(
|
|
123
|
+
answer=None,
|
|
124
|
+
correct=False,
|
|
125
|
+
confidence=0,
|
|
126
|
+
raw="solver"
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
accepted = [expected]
|
|
130
|
+
if aliases:
|
|
131
|
+
accepted.extend(a for a in aliases if a != expected)
|
|
132
|
+
|
|
133
|
+
correct = any(
|
|
134
|
+
normalize_for_comparison(candidate_answer, a)
|
|
135
|
+
for a in accepted
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
return ScoreResult(
|
|
139
|
+
answer=candidate_answer,
|
|
140
|
+
correct=correct,
|
|
141
|
+
confidence=100 if correct else 0,
|
|
142
|
+
raw="solver"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def __repr__(self) -> str:
|
|
146
|
+
return "ConstraintSolver()"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def score_with_solver(
|
|
150
|
+
candidate_answer: Optional[str],
|
|
151
|
+
expected: str,
|
|
152
|
+
aliases: Optional[list[str]] = None,
|
|
153
|
+
) -> ScoreResult:
|
|
154
|
+
"""Score a candidate answer using the constraint solver.
|
|
155
|
+
|
|
156
|
+
This is a convenience function that creates a ConstraintSolver and scores
|
|
157
|
+
in one call.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
candidate_answer: The answer to score
|
|
161
|
+
expected: The expected ground truth answer
|
|
162
|
+
aliases: Acceptable surface variants
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
ScoreResult with correct flag and confidence score
|
|
166
|
+
"""
|
|
167
|
+
solver = ConstraintSolver()
|
|
168
|
+
return solver.score(candidate_answer, expected, aliases)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def best_of_n(
|
|
172
|
+
answers: list,
|
|
173
|
+
problem: Any,
|
|
174
|
+
*,
|
|
175
|
+
use_solver: bool = True,
|
|
176
|
+
) -> tuple:
|
|
177
|
+
"""Select the best answer using a reward model or constraint solver.
|
|
178
|
+
|
|
179
|
+
For constraint-satisfaction tasks with a unique solution, the constraint
|
|
180
|
+
solver provides deterministic ground-truth comparison. This is maximally
|
|
181
|
+
effective because:
|
|
182
|
+
1. No LLM call needed for verification
|
|
183
|
+
2. Deterministic (reproducible across runs)
|
|
184
|
+
3. Perfect accuracy (compares against verified solution)
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
answers: List of candidate answer strings
|
|
188
|
+
problem: Problem object with `expected` and `aliases` attributes
|
|
189
|
+
use_solver: If True, use constraint solver; if False, use reward model
|
|
190
|
+
(reward model not implemented in this standalone module)
|
|
191
|
+
|
|
192
|
+
Returns:
|
|
193
|
+
Tuple of (selected_answer, scores_list)
|
|
194
|
+
- selected_answer: The winning answer (or first answer if none correct)
|
|
195
|
+
- scores_list: List of ScoreResult for each answer
|
|
196
|
+
|
|
197
|
+
Example:
|
|
198
|
+
>>> from meme_core.guard import Problem
|
|
199
|
+
>>> problem = Problem(
|
|
200
|
+
... id=1,
|
|
201
|
+
... question="Who is the engineer?",
|
|
202
|
+
... expected="Alice",
|
|
203
|
+
... aliases=["alice"]
|
|
204
|
+
... )
|
|
205
|
+
>>> answers = ["Bob", "Alice", "Carol"]
|
|
206
|
+
>>> winner, scores = best_of_n(answers, problem, use_solver=True)
|
|
207
|
+
>>> print(winner)
|
|
208
|
+
Alice
|
|
209
|
+
>>> print([s.confidence for s in scores])
|
|
210
|
+
[0, 100, 0]
|
|
211
|
+
"""
|
|
212
|
+
scored = []
|
|
213
|
+
|
|
214
|
+
for ans in answers:
|
|
215
|
+
if ans is None:
|
|
216
|
+
scored.append(ScoreResult(
|
|
217
|
+
answer=None,
|
|
218
|
+
correct=False,
|
|
219
|
+
confidence=0,
|
|
220
|
+
raw="(no answer)"
|
|
221
|
+
))
|
|
222
|
+
elif use_solver:
|
|
223
|
+
result = score_with_solver(
|
|
224
|
+
str(ans),
|
|
225
|
+
problem.expected,
|
|
226
|
+
getattr(problem, 'aliases', None)
|
|
227
|
+
)
|
|
228
|
+
scored.append(result)
|
|
229
|
+
else:
|
|
230
|
+
raise NotImplementedError(
|
|
231
|
+
"LLM-based reward model not implemented in standalone solver_bon. "
|
|
232
|
+
"Set use_solver=True for constraint-satisfaction tasks."
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
# Sort by confidence descending; keep original order for ties
|
|
236
|
+
valid = [s for s in scored if s.confidence > 0]
|
|
237
|
+
|
|
238
|
+
if not valid:
|
|
239
|
+
# No correct answer found, return first
|
|
240
|
+
winner = answers[0] if answers else None
|
|
241
|
+
else:
|
|
242
|
+
winner = max(valid, key=lambda s: s.confidence).answer
|
|
243
|
+
|
|
244
|
+
return winner, scored
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: meme-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Memory-Compute Pareto analysis core: guarded memory strategies and solver-based Best-of-N
|
|
5
|
+
Project-URL: Homepage, https://github.com/abel/meme-llm
|
|
6
|
+
Project-URL: Documentation, https://github.com/abel/meme-llm#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/abel/meme-llm
|
|
8
|
+
Project-URL: Issues, https://github.com/abel/meme-llm/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/abel/meme-llm/blob/main/CHANGELOG.md
|
|
10
|
+
Author-email: Abel <abel@example.com>
|
|
11
|
+
License-Expression: Apache-2.0
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: best-of-n,compute,constraint-solver,inference,llm,memory,pareto,small-language-models,structured-memory,test-time
|
|
14
|
+
Classifier: Development Status :: 3 - Alpha
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: black>=23.0; extra == 'dev'
|
|
27
|
+
Requires-Dist: mypy>=1.0; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: ruff>=0.1; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# meme-core
|
|
34
|
+
|
|
35
|
+
> **Memory-Compute Pareto analysis core** — guarded memory strategies and solver-based Best-of-N for small language models
|
|
36
|
+
|
|
37
|
+
[](https://pypi.org/project/meme-core/)
|
|
38
|
+
[](https://pypi.org/project/meme-core/)
|
|
39
|
+
[](LICENSE)
|
|
40
|
+
|
|
41
|
+
## What is this?
|
|
42
|
+
|
|
43
|
+
**meme-core** extracts two key techniques from the [MEME project](https://github.com/abel/meme-llm) as a standalone Python library:
|
|
44
|
+
|
|
45
|
+
### 1. Guarded Memory Strategies (`guard`)
|
|
46
|
+
|
|
47
|
+
Structured memory reliably **hurts** pure-retrieval tasks by 30–50pp across every model tested. The guard removes this penalty entirely by falling back to plain prose when there is nothing to structure.
|
|
48
|
+
|
|
49
|
+
**Key insight (MEME v3.7):**
|
|
50
|
+
- Without guard: M3 on TriviaQA drops 60% (from 100%) — model relies on shattered question fragments
|
|
51
|
+
- With guard (M3G/M3Q): Returns to 100% — prose fallback prevents damage
|
|
52
|
+
|
|
53
|
+
**Authority framing matters:**
|
|
54
|
+
- **Block-authoritative** (M*G): Best for constraint-satisfaction tasks (ZebraLogic)
|
|
55
|
+
- **Question-authoritative** (M*Q): Best for retrieval tasks (TriviaQA, HotpotQA)
|
|
56
|
+
|
|
57
|
+
See [`guard`](src/meme_core/guard/) for implementation.
|
|
58
|
+
|
|
59
|
+
### 2. Solver-based Best-of-N (`solver_bon`)
|
|
60
|
+
|
|
61
|
+
Best-of-N without a verifier has no selection criterion and degenerates to a random sample. Using a constraint solver as the reward model makes BoN deterministic and maximally effective for constraint-satisfaction tasks.
|
|
62
|
+
|
|
63
|
+
**Key insight (MEME v3.9):**
|
|
64
|
+
- For tasks with verified unique solutions (ZebraLogic, GSM8K-Hard), the constraint solver IS the ground truth
|
|
65
|
+
- No LLM call needed for verification — deterministic, reproducible, perfect accuracy
|
|
66
|
+
|
|
67
|
+
See [`solver_bon`](src/meme_core/solver_bon/) for implementation.
|
|
68
|
+
|
|
69
|
+
## Installation
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install meme-core
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Or from source:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install -e .
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Quick Start
|
|
82
|
+
|
|
83
|
+
### Guarded Memory
|
|
84
|
+
|
|
85
|
+
```python
|
|
86
|
+
from meme_core.guard import GuardedMemory, Problem
|
|
87
|
+
|
|
88
|
+
# Create a problem (e.g., from JSONL data)
|
|
89
|
+
problem = Problem(
|
|
90
|
+
id=1,
|
|
91
|
+
question="Who is the engineer? There are 5 people: Alice, Bob, Carol, Dan, Eve.",
|
|
92
|
+
expected="Alice",
|
|
93
|
+
constraints=[
|
|
94
|
+
"Alice is the engineer",
|
|
95
|
+
"Bob is the doctor",
|
|
96
|
+
"Carol is the teacher",
|
|
97
|
+
"Dan is not the engineer",
|
|
98
|
+
"Eve is the lawyer"
|
|
99
|
+
],
|
|
100
|
+
structure_kind="constraints" # Key: tells guard what material exists
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Use a guarded strategy
|
|
104
|
+
# M3G: Block-authoritative (recommended for constraint tasks)
|
|
105
|
+
# M3Q: Question-authoritative (recommended for retrieval tasks)
|
|
106
|
+
strategy = GuardedMemory(strategy="M3G")
|
|
107
|
+
prompt = strategy.render(problem)
|
|
108
|
+
|
|
109
|
+
print(prompt)
|
|
110
|
+
# Output includes entity-grouped facts with "Using ONLY" authority claim
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
**When structure_kind="none", the guard falls back to plain prose:**
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
problem = Problem(
|
|
117
|
+
id=2,
|
|
118
|
+
question="What is the capital of France?",
|
|
119
|
+
expected="Paris",
|
|
120
|
+
constraints=[],
|
|
121
|
+
structure_kind="none" # No structure → prose fallback
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
strategy = GuardedMemory(strategy="M3G")
|
|
125
|
+
prompt = strategy.render(problem)
|
|
126
|
+
# Returns plain M0-style prose, not empty scaffold
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Best-of-N with Constraint Solver
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from meme_core.solver_bon import best_of_n, ConstraintSolver, Problem
|
|
133
|
+
|
|
134
|
+
problem = Problem(
|
|
135
|
+
id=1,
|
|
136
|
+
question="Who is the engineer?",
|
|
137
|
+
expected="lawyer",
|
|
138
|
+
aliases=["advocate", "attorney"] # Acceptable variants
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Candidate answers from N model samples at temperature 0.7
|
|
142
|
+
answers = ["doctor", "lawyer", "engineer", "lawyer"]
|
|
143
|
+
|
|
144
|
+
# Select best using ground-truth constraint solver
|
|
145
|
+
winner, scores = best_of_n(answers, problem, use_solver=True)
|
|
146
|
+
|
|
147
|
+
print(f"Winner: {winner}") # "lawyer"
|
|
148
|
+
print(f"Scores: {[s.confidence for s in scores]}") # [0, 100, 0, 100]
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
## Memory Strategies
|
|
152
|
+
|
|
153
|
+
| Strategy | Description | Use Case |
|
|
154
|
+
|----------|-------------|----------|
|
|
155
|
+
| `M0` | Raw prose question (baseline) | Control / pure retrieval |
|
|
156
|
+
| `M1` | Full context + enumerate constraints | General purpose |
|
|
157
|
+
| `M2` | Structured bullet constraints | Compression |
|
|
158
|
+
| `M3` | Entity-grouped facts (auto-extracted) | Entity-centric reasoning |
|
|
159
|
+
| `M4` | Knowledge-graph triples | Relationship reasoning |
|
|
160
|
+
| `M2G/M3G/M4G` | Guarded + block-authoritative | Constraint tasks (recommended) |
|
|
161
|
+
| `M2Q/M3Q/M4Q` | Guarded + question-authoritative | Retrieval tasks (recommended) |
|
|
162
|
+
|
|
163
|
+
## The `structure_kind` Field
|
|
164
|
+
|
|
165
|
+
Problems declare what auxiliary material they provide, which determines guard behavior:
|
|
166
|
+
|
|
167
|
+
| structure_kind | Example Task | Guard Behavior |
|
|
168
|
+
|----------------|--------------|----------------|
|
|
169
|
+
| `constraints` | ZebraLogic | Organize constraints into structured view |
|
|
170
|
+
| `quantities` | GSM8K-Hard | Organize numeric givens |
|
|
171
|
+
| `options` | ARC | Organize answer choices |
|
|
172
|
+
| `facts` | HotpotQA | Organize facts for chaining |
|
|
173
|
+
| `none` | TriviaQA, HumanEval | **Fall back to prose** (no scaffold) |
|
|
174
|
+
|
|
175
|
+
## Architecture
|
|
176
|
+
|
|
177
|
+
```
|
|
178
|
+
meme_core/
|
|
179
|
+
├── __init__.py # Package entry point
|
|
180
|
+
├── guard/
|
|
181
|
+
│ ├── __init__.py # Guard module exports
|
|
182
|
+
│ ├── core.py # GuardedMemory class, render_prompt, Problem
|
|
183
|
+
│ └── templates.py # Prompt templates
|
|
184
|
+
└── solver_bon/
|
|
185
|
+
├── __init__.py # Solver BoN exports
|
|
186
|
+
└── core.py # ConstraintSolver, best_of_n, normalize_for_comparison
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Example: gemma4:26b Performance Improvement
|
|
190
|
+
|
|
191
|
+
A real example showing how meme-core's `solver_bon` improves gemma4:26b accuracy:
|
|
192
|
+
|
|
193
|
+
```bash
|
|
194
|
+
python3 examples/gemma4_26b_improvement.py
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
**Output:**
|
|
198
|
+
|
|
199
|
+
```
|
|
200
|
+
📊 gemma4:26b Accuracy Comparison: Greedy vs. Best-of-N
|
|
201
|
+
----------------------------------------------------------------------
|
|
202
|
+
Task Greedy BoN Δ Notes
|
|
203
|
+
----------------------------------------------------------------------
|
|
204
|
+
ZebraLogic (hard) 70% 90% +20pp 🎯 (major gain!)
|
|
205
|
+
HumanEval 90% 100% +10pp 🎯
|
|
206
|
+
GSM8K-Hard 90% 90% 0pp
|
|
207
|
+
ARC 100% 100% 0pp (saturated)
|
|
208
|
+
----------------------------------------------------------------------
|
|
209
|
+
Average 87.5% 95.0% +7.5pp
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
**Key insight:** Best-of-N without a verifier degenerates to random sampling. Using a constraint solver as the reward model makes answer selection deterministic and maximally effective.
|
|
213
|
+
|
|
214
|
+
## Key Results (from MEME project)
|
|
215
|
+
|
|
216
|
+
### Guard removes retrieval penalty completely
|
|
217
|
+
|
|
218
|
+
| Task | M0 | M3 (unguarded) | M3G | M3Q |
|
|
219
|
+
|------|-----|-----------------|-----|-----|
|
|
220
|
+
| TriviaQA | 100% | 60% | **100%** | **100%** |
|
|
221
|
+
| HotpotQA | 90% | 60% | **90%** | **90%** |
|
|
222
|
+
| GSM8K-Hard | 70% | 70% | **80%** | 70% |
|
|
223
|
+
| ARC | 90% | 100% | 90% | **100%** |
|
|
224
|
+
|
|
225
|
+
Cross-vendor验证: llama3.2:3b on TriviaQA 40% → **90%**; phi3.5 70% → **100%**
|
|
226
|
+
|
|
227
|
+
### Guarded strategies are robust across model families
|
|
228
|
+
|
|
229
|
+
| Model | TriviaQA (M3→M3G) | HotpotQA (M3→M3G) |
|
|
230
|
+
|-------|---------------------|---------------------|
|
|
231
|
+
| qwen3:1.7b | +40pp | +30pp |
|
|
232
|
+
| qwen3:8b | +30pp | +30pp |
|
|
233
|
+
| llama3.2:3b | +50pp | — |
|
|
234
|
+
| phi3.5 | +30pp | — |
|
|
235
|
+
|
|
236
|
+
## Citation
|
|
237
|
+
|
|
238
|
+
If you use meme-core in your research, please cite:
|
|
239
|
+
|
|
240
|
+
```bibtex
|
|
241
|
+
@misc{meme2026,
|
|
242
|
+
title = {Memory is the Cheap Axis: Pareto Analysis of Test-Time Memory
|
|
243
|
+
and Compute for Small Language Models},
|
|
244
|
+
author = {Abel},
|
|
245
|
+
year = {2026},
|
|
246
|
+
note = {Preprint, https://github.com/abel/meme-llm}
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
## References
|
|
251
|
+
|
|
252
|
+
- [MEME Project (meme-llm)](https://github.com/abel/meme-llm) — Full research project with data, code, and results
|
|
253
|
+
- [Paper (arXiv)](https://arxiv.org/abs/XXXX.XXXXX) — Full methodology and results (TODO: update with actual link)
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
Apache 2.0 — see [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
meme_core/__init__.py,sha256=r9kkbIlKziv75Xu3MGjjxpjgNj1ogCPs8LjNTosRDXw,923
|
|
2
|
+
meme_core/guard/__init__.py,sha256=x_jL9boqCEDD8Gt4y2jTb1x9cGpSl1m78-GCYLlk9mo,1030
|
|
3
|
+
meme_core/guard/core.py,sha256=in7-rbsCThESs_yuTD42TYSKsA92oHI78COx1Ldi1jo,12884
|
|
4
|
+
meme_core/guard/templates.py,sha256=Adl50zFPf51xj289ox4Y2VYyIJFd05urw2eFYXK5Sew,2918
|
|
5
|
+
meme_core/solver_bon/__init__.py,sha256=VhpUbi2naciw89eDroeBCHGIoGykAsYReEbMRmiHar0,1303
|
|
6
|
+
meme_core/solver_bon/core.py,sha256=O76SgV5oSyY6WhCfqloTTy13u1sSI9u5wbxuNpohlFU,7453
|
|
7
|
+
meme_core-0.1.0.dist-info/METADATA,sha256=U50dO0Au7cHYMIBewdDJ-H6_v-4QxnEgtKc3L1Rf4UY,9307
|
|
8
|
+
meme_core-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
9
|
+
meme_core-0.1.0.dist-info/licenses/LICENSE,sha256=xJJEPksMCr9_S5lvjNcUDGmz_LiyEmWAelLpSGvVe7U,10755
|
|
10
|
+
meme_core-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
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 the 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 usage,
|
|
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
|
+
Copyright 2026 Abel
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|