Googlu15's picture
intent labeling + ReuseStats
97d4655 verified
Raw History Blame Contribute Delete
3.92 kB
"""Stage 2b: label history conversations with the IAC intent classifier, learn ReuseStats,
and label every replay-trace request."""
from __future__ import annotations
import json
import os
import sys
import time
import numpy as np
REPO_DIR = os.environ.get("IAC_REPO", "/work/iac-repo")
sys.path.insert(0, REPO_DIR)
from iac.classifier import ( # noqa: E402
BATCH_SIZE,
IntentClassifier,
conversation_intents_fn,
label_conversations,
label_inputs,
turn_records,
)
from iac.data import SyntheticDelay, load_conversations # noqa: E402
from iac.stats import ReuseStats # noqa: E402
CKPT = "/work/iac-repo/checkpoints/intent_e5_large_instruct_30cls.pt"
HISTORY = "/work/data/splits/sharechat/history.jsonl.gz"
STATS_OUT = "/work/artifacts/stats_sharechat.json"
INTENTS_OUT = "/work/artifacts/replay_intents.json"
def main():
t0 = time.time()
os.makedirs("/work/artifacts", exist_ok=True)
print("loading history split...", flush=True)
convs = load_conversations(HISTORY)
print(f" {len(convs)} conversations", flush=True)
clf = IntentClassifier.from_checkpoint(CKPT, device="cuda", embedder_dtype="autocast-bf16")
if os.path.exists(STATS_OUT):
print("stats already exist, skipping history labeling", flush=True)
else:
labels = label_conversations(convs, clf, batch_size=BATCH_SIZE)
records = turn_records(convs, conversation_intents_fn(labels), 1800.0, SyntheticDelay(), seed=0)
stats = ReuseStats.learn(records, session_timeout=1800.0,
metadata={"split": HISTORY, "conversations": len(convs),
"requests": len(records)})
stats.save(STATS_OUT)
print(f"stats saved: {len(stats)} states in {time.time() - t0:.0f}s", flush=True)
if os.path.exists(INTENTS_OUT):
print("replay intents already exist, skipping", flush=True)
else:
trace_start = time.time()
from iac.data import Trace
trace = Trace.load("/work/traces/sharechat_r3")
reqs = sorted(trace.requests, key=lambda r: r.req_id)
turns = [trace.classifier_turns(r) for r in reqs]
flat = []
B = BATCH_SIZE
for i in range(0, len(turns), B):
flat.extend(clf.predict(turns[i : i + B]))
if (i // B) % 50 == 0:
print(f" replay {i + len(turns[i:i+B])}/{len(turns)} "
f"({time.time() - trace_start:.0f}s)", flush=True)
intents = {str(r.req_id): lab for r, lab in zip(reqs, flat)}
with open(INTENTS_OUT, "w") as f:
json.dump(intents, f)
print(f"replay intents saved in {time.time() - trace_start:.0f}s", flush=True)
# report
stats = ReuseStats.load(STATS_OUT)
report = {"states": len(stats),
"defaults": {"p_next": stats.default_p_next,
"reuse_window": stats.default_reuse_window}}
examples = []
for key in list(stats.table)[:3]:
p, mu, sigma = stats.lookup_dist(key[0], key[1])
examples.append({"intent": key[0], "turn": key[1], "p_next": p,
"reuse_window_s": float(np.exp(mu))})
report["examples"] = examples
trace = Trace.load("/work/traces/sharechat_r3")
reqs = sorted(trace.requests, key=lambda r: r.req_id)
intents = json.load(open(INTENTS_OUT))
ps = []
for r in reqs:
p, _, _ = stats.lookup_dist(intents.get(str(r.req_id)), r.turn)
ps.append(p)
ps = np.asarray(ps)
report["replay"] = {"requests": len(ps), "mean_p_next": float(ps.mean()),
"median_p_next": float(np.median(ps))}
with open("/work/artifacts/stats_report.json", "w") as f:
json.dump(report, f, indent=1)
print(json.dumps(report, indent=1), flush=True)
print(f"total {time.time() - t0:.0f}s", flush=True)
if __name__ == "__main__":
main()