Repository navigation
Expand file tree
/
Copy pathdependency.py
More file actions
143 lines (124 loc) · 4.82 KB
/
Copy pathdependency.py
File metadata and controls
143 lines (124 loc) · 4.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import asyncio
import csv
import json
import random
from typing import TypedDict
from openai import AsyncOpenAI
from config import LLM_MODEL
from data import LOADERS, Question
from methods import BASELINE, make_chunks
from settings import RESULTS, Chunk
SAMPLE = 100
CONCURRENCY = 8
PROMPT = """You see one chunk cut out of a longer document. You do not see the rest of the document.
Decide whether a reader could understand this chunk and answer questions from it on its own.
Check four ways a chunk can depend on its document:
- not_self_contained: you cannot tell what the chunk is about.
- unresolved_reference: it refers back to something defined elsewhere ("the employee", "our model", "this method").
- needs_structure: it only makes sense with the document's structure (which section, which table or list).
- ambiguous_without_title: it is unclear which entity, company, or event it is about.
Reply with JSON only:
{"not_self_contained": bool, "unresolved_reference": bool, "needs_structure": bool,
"ambiguous_without_title": bool, "self_contained": bool, "reason": "one short sentence"}
Set self_contained to true only when all four checks are false.
Chunk:
\"\"\"
{chunk}
\"\"\""""
class Label(TypedDict):
qid: str
variant: str
chunk: str
not_self_contained: bool
unresolved_reference: bool
needs_structure: bool
ambiguous_without_title: bool
self_contained: bool
reason: str
def answer_chunk(q: Question, chunks: list[Chunk]) -> Chunk:
"""The chunk that holds the start of the question's answer passage."""
start = q["evidence"][0][0]
return next(
c
for c in chunks
if c["doc_id"] == q["doc_id"] and c["start"] <= start < c["end"]
)
def sample_chunks(dataset: str, prefix: bool) -> list[tuple[str, str]]:
"""(question id, chunk text) for a fixed random sample of answer chunks."""
data = LOADERS[dataset]()
chunks = make_chunks(data, {**BASELINE, "prefix": prefix})
questions = random.Random(0).sample(data["questions"], SAMPLE)
return [(q["qid"], answer_chunk(q, chunks)["text"]) for q in questions]
async def label_one(
client: AsyncOpenAI,
gate: asyncio.Semaphore,
qid: str,
text: str,
variant: str,
model: str = LLM_MODEL,
) -> Label | None:
"""Label one chunk. Returns None when the model gives no valid JSON after 5 tries."""
async with gate:
for attempt in range(5):
response = await client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": PROMPT.replace("{chunk}", text)}],
response_format={"type": "json_object"},
temperature=0,
)
try:
verdict = json.loads(response.choices[0].message.content or "")
return {"qid": qid, "variant": variant, "chunk": text, **verdict}
except json.JSONDecodeError:
await asyncio.sleep(2 * (attempt + 1))
return None
async def label_dataset(
client: AsyncOpenAI, dataset: str, model: str = LLM_MODEL
) -> list[Label]:
"""Label the plain and the title-prefixed version of the same answer chunks. Saved once."""
suffix = "" if model == LLM_MODEL else "_" + model.split("/")[-1]
out = RESULTS / f"dependency_{dataset}{suffix}.json"
if out.exists():
return json.loads(out.read_text())
gate = asyncio.Semaphore(CONCURRENCY)
jobs = [
label_one(client, gate, qid, text, variant, model)
for variant, prefix in (("plain", False), ("prefix", True))
for qid, text in sample_chunks(dataset, prefix)
]
results = await asyncio.gather(*jobs)
labels = [r for r in results if r is not None]
print(
f"{dataset}: {len(results) - len(labels)} chunks dropped after 5 failed tries"
)
out.write_text(json.dumps(labels, indent=2))
return labels
def write_spotcheck(labels: dict[str, list[Label]], n: int = 10) -> None:
"""A CSV of n plain chunks per dataset for a person to label in the `human_self_contained` column."""
path = RESULTS / "dependency_spotcheck.csv"
if path.exists():
return
with path.open("w", newline="") as f:
writer = csv.writer(f)
writer.writerow(
[
"dataset",
"qid",
"chunk",
"llm_self_contained",
"llm_reason",
"human_self_contained",
]
)
for dataset, rows in labels.items():
for row in [r for r in rows if r["variant"] == "plain"][:n]:
writer.writerow(
[
dataset,
row["qid"],
row["chunk"],
row["self_contained"],
row["reason"],
"",
]
)