floop: anonymize named entities before INIT (his design) #16

Merged
onibot merged 1 commits from feature/init-anonymization into main 2026-10-22 16:48:48 +02:00
4 changed files with 204 additions and 3 deletions
Showing only changes of commit 0ed26d3406 - Show all commits
+67
View File
@@ -0,0 +1,67 @@
"""Query anonymization before INIT (his design, 22/10): the model must
decompose the question's SHAPE, not lean on its knowledge of the people in
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
...) before INIT sees the query; the placeholders are restored in the
returned subquestions — deterministically, by exact string replacement.
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
"""
from __future__ import annotations
import dspy
from pydantic import BaseModel
class NamedEntity(BaseModel):
"""One named entity found in the question."""
name: str = dspy.OutputField(
desc="the entity's exact surface text as it appears in the question, copied verbatim")
kind: str = dspy.OutputField(
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
class EntityMaskSignature(dspy.Signature):
"""You are the MASK step of a reasoning machine. Find the named entities
in the question — people, organizations, places, titles of works, events.
Copy each one's text exactly as it appears; do not add entities that are
not explicitly named."""
question: str = dspy.InputField()
entities: list[NamedEntity] = dspy.OutputField(
desc="the named entities found; empty when none")
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
"""Mask the question deterministically. Longer names first (so
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
Returns (masked_question, restore_map placeholder -> original)."""
restore: dict[str, str] = {}
counters: dict[str, int] = {}
masked = question
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
name = ent.name.strip()
if not name or name not in masked:
continue
kind = ent.kind.strip().upper()
prefix = _PREFIX.get(kind, "OTHER")
counters[prefix] = counters.get(prefix, 0) + 1
ph = f"{prefix}_{counters[prefix]}"
if ph in restore: # same surface text twice: keep one mask
continue
masked = masked.replace(name, ph)
restore[ph] = name
return masked, restore
def restore_mask(text: str, restore: dict[str, str]) -> str:
"""Restore placeholders to the original names, longest first (so
PERSON_10 is not eaten by PERSON_1)."""
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
reverse=True):
text = text.replace(ph, name)
return text
+25 -3
View File
@@ -19,6 +19,8 @@ try:
except ImportError: # pragma: no cover — dspy <3.x
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
from .anonymize import EntityMaskSignature, apply_mask, restore_mask
class Subquestion(BaseModel):
"""One open subquestion in the goal's decomposition."""
@@ -122,6 +124,7 @@ class FloopModules:
self.expert = dspy.Predict(ExpertSignature)
self.missing = dspy.Predict(MissingSignature)
self.answer = dspy.Predict(AnswerSignature)
self.mask = dspy.Predict(EntityMaskSignature)
def init_decompose(self, question: str) -> tuple[list[dict], str]:
"""(parsed subquestions, raw model output). The machine decides what
@@ -130,12 +133,31 @@ class FloopModules:
Typed output: a response that violates the Subquestion schema raises
AdapterParseError AFTER dspy's own JSON re-ask; its lm_response IS
the raw garbage — hand it back as the degrade signal."""
the raw garbage — hand it back as the degrade signal.
ANONYMIZATION (his design): named entities are masked before INIT
so the model decomposes shape, not identity — restored in the
returned subquestions, deterministically."""
masked, restore = self.anonymize(question)
try:
pred = self.init(question=question)
pred = self.init(question=masked)
except AdapterParseError as e:
return [], (e.lm_response or "unparseable response")
return self._subs_from_typed(pred.subquestions), ""
subs = []
for s in self._subs_from_typed(pred.subquestions):
subs.append({**s, "text": restore_mask(s["text"], restore)})
return subs, ""
def anonymize(self, question: str) -> tuple[str, dict]:
"""Mask named entities to typed placeholders. No entity found (or the
mask call dies) -> the question passes unchanged, mask map empty."""
try:
pred = self.mask(question=question)
entities = pred.entities or []
except AdapterParseError:
return question, {}
masked, restore = apply_mask(question, entities)
return masked, restore
@staticmethod
def _subs_from_typed(subs) -> list[dict]:
+1
View File
@@ -156,6 +156,7 @@ _STAGE_BY_MODULE = {
"Expert": "EXPERT",
"Missing": "MISSING",
"Answer": "ANSWER",
"EntityMaskSignature": "MASK",
"KnowledgeExpert": "knowledge",
"InitSignature": "INIT",
"RouteSignature": "ROUTE",
+111
View File
@@ -0,0 +1,111 @@
"""Query anonymization tests (his design, 22/10): INIT must decompose the
question's SHAPE, not lean on its knowledge of the named people in it.
Laws under test:
1. MASK proposes entities; apply_mask/restore_mask are DETERMINISTIC —
longer names first, one mask per surface text, typed placeholders.
2. init_decompose masks before INIT and restores in the subquestions.
3. No entities found -> the question reaches INIT unchanged.
4. MASK dying (AdapterParseError) -> passthrough, never a dead run.
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
Run: .venv/bin/python tests/anonymize.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import warnings
warnings.filterwarnings("ignore")
import dspy
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from dspy.utils.exceptions import AdapterParseError
from floop.dspy_modules import FloopModules
from floop.anonymize import NamedEntity, apply_mask, restore_mask
def _lm(script: list[str]) -> None:
"""An engine replaying a script: one raw response per LM call."""
class RawEngine:
def __init__(self):
self.i = 0
def complete(self, request):
raw = script[min(self.i, len(script) - 1)]
self.i += 1
return Response(
id="x", model="t",
message=Message(role="assistant",
parts=(TextPart(text=raw),)),
finish_reason="stop",
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
Q = "Who was the President before Pedro Sanchez?"
_MASKED_ENTS = '''[[ ## entities ## ]]
[{"name": "Pedro Sanchez", "kind": "PERSON"}]
[[ ## completed ## ]]'''
_TWO_SUBS = '''[[ ## subquestions ## ]]
[{"text": "Which office does PERSON_1 hold as President?", "depends_on": [], "answer_type": "OPEN"},
{"text": "Who held that same office before PERSON_1 took office?", "depends_on": [1], "answer_type": "OPEN"}]
[[ ## completed ## ]]'''
def test_apply_restore_deterministic():
ents = [NamedEntity(name="Pedro Sanchez", kind="PERSON")]
masked, restore = apply_mask(Q, ents)
assert masked == "Who was the President before PERSON_1?", masked
assert restore == {"PERSON_1": "Pedro Sanchez"}
# longer first: a full name is never half-masked by a shorter one
ents2 = [NamedEntity(name="Pedro Sanchez", kind="PERSON"),
NamedEntity(name="Pedro", kind="PERSON")]
m2, r2 = apply_mask("Pedro Sanchez and Pedro", ents2)
assert m2 == "PERSON_1 and PERSON_2", m2
assert restore_mask(m2, r2) == "Pedro Sanchez and Pedro"
# restore order: PERSON_10 before PERSON_1
r3 = {f"PERSON_{i}": f"name{i}" for i in range(1, 11)}
assert "name10" in restore_mask("PERSON_10", r3)
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
def test_init_decompose_masks_and_restores():
# script: first call = MASK, second = INIT
_lm([_MASKED_ENTS, _TWO_SUBS])
subs, raw = FloopModules().init_decompose(Q)
assert len(subs) == 2, subs
assert "Pedro Sanchez" in subs[0]["text"] and "PERSON_1" not in subs[0]["text"], subs[0]
assert subs[1]["deps"] == [1]
print("ok: INIT sees the masked query; subquestions come back restored")
def test_no_entities_passthrough():
_lm(['''[[ ## entities ## ]]
[]
[[ ## completed ## ]]''', _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
print("ok: no entities found -> question reaches INIT unchanged")
def test_mask_death_passthrough():
# MASK response violates the schema -> AdapterParseError -> passthrough
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
print("ok: MASK death -> passthrough, never a dead run")
if __name__ == "__main__":
test_apply_restore_deterministic()
test_init_decompose_masks_and_restores()
test_no_entities_passthrough()
test_mask_death_passthrough()
print("\nanonymization tests passed")