floop: anonymize named entities before INIT (his design)
The model was using its own knowledge of the people in the question to decide decomposition (his qwen collapsed Pedro Sanchez to ONE subquestion: 'the question is nearly atomic because I know who he is'). Structural fix: INIT sees the question's SHAPE, not identity. - EntityMaskSignature (typed NER proposal): entities as list[NamedEntity] (name verbatim + kind) — the typed-output law, no string parsing - apply_mask/restore_mask: DETERMINISTIC code (LLMs propose, code applies): longest names first, one placeholder per surface text, typed prefixes PERSON_1/ORGANIZATION_1/..., restore longest-first (PERSON_10 never eaten by PERSON_1) - init_decompose: mask -> INIT -> restore in each returned subquestion; MASK finding no entities OR dying (AdapterParseError) -> passthrough, never a dead run - MASK stage in the prompt log (prompts/01-MASK.txt) VERIFIED: tests/anonymize.py 4/4 (deterministic apply/restore, E2E mask+restore, no-entity passthrough, mask-death passthrough); suite 15/15. Live E2E (glm-5.3-flash): MASK found exactly Pedro Sanchez (reasoning explicitly excluded 'President' as a role, not entity); INIT saw 'Who was the President before PERSON_1?' and returned FOUR subquestions (identity, office, term start, predecessor) — the shape split he wanted, plus a 'who is PERSON_1' question; run answers Rajoy correctly (E1-E4). OPEN (his question pending): the model now asks WHO the placeholder is, spending one call per run. Options: (a) keep, (b) desc note that placeholders are known entities, (c) give INIT the masked question PLUS the original as context. Not decided — he answers when back.
This commit is contained in:
@@ -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")
|
||||
Reference in New Issue
Block a user