gibridllm-code / src /gibrid /tasks2.py
unkony's picture
sync code
5b024a9 verified
Raw History Blame Contribute Delete
7.01 kB
r"""Задача v2: несколько фактов об одном человеке, разные формулировки фактов и вопросов, ответы разных типов.
Отличия от v1:
- у человека несколько фактов (город, питомец, код, друг), и вопрос бывает про любой из них: недостаточно найти имя,
нужно выбрать правильный факт среди фактов того же человека;
- факт и вопрос сформулированы по-разному (3 варианта каждого), слова не совпадают;
- ответы разных типов: слово, число, два слова;
- в ловушках те же атрибуты у других людей;
- поиск по архиву берёт top-4 кусков (а не 2), нужный кусок должен оказаться среди них.
Формат возвращаемой задачи тот же, что у recall_train.make, плюс поля type (атрибут) и hit (нашёл ли поиск нужный кусок).
"""
import time
import index as aindex
import needle as nd
USE_INDEX = True # False: старый перебор всех кусков (needle.retrieve), для сравнения
W = 96
TOPK = 4
CONS, VOW = "bdfgklmnprstvz", "aeiou"
ATTRS = {
"city": {"facts": ["{n} lives in {a}.", "{n} moved to {a} last spring.", "These days {n} calls {a} home."],
"qs": ["Where does {n} live?", "Which city is home for {n}?", "In what city does {n} stay?"]},
"pet": {"facts": ["{n} has a pet called {a}.", "{n} named the dog {a}.", "The pet of {n} is {a}."],
"qs": ["What is the name of the pet of {n}?", "What does {n} call the dog?", "Which pet does {n} have?"]},
"code": {"facts": ["The access code of {n} is {a}.", "{n} uses the code {a} at the door.",
"{n} wrote down the number {a}."],
"qs": ["What is the access code of {n}?", "Which number does {n} use at the door?",
"What code did {n} write down?"]},
"friend": {"facts": ["{n} is friends with {a}.", "The best friend of {n} is {a}.", "{n} often goes out with {a}."],
"qs": ["Who is the friend of {n}?", "Who is the best friend of {n}?", "Who does {n} often go out with?"]},
}
def pseudo(rng, syl, cap=False):
w = "".join(rng.choice(CONS) + rng.choice(VOW) for _ in range(syl))
return w.capitalize() if cap else w
def gen_answer(attr, rng):
if attr == "city":
return pseudo(rng, rng.randint(2, 3), True)
if attr == "pet":
return pseudo(rng, 2, True)
if attr == "code":
return str(rng.randint(100, 99999))
return pseudo(rng, 2, True) + " " + pseudo(rng, 2, True) # friend: два слова
def fact_text(rng, attr, name, ans):
return rng.choice(ATTRS[attr]["facts"]).format(n=name, a=ans)
def make2(rng, tok, split, far, dist=None, hist=None):
"""far=True: нужный факт за пределами окна; far=False: внутри окна (но архив длинный, hist токенов истории)."""
kinds = list(ATTRS)
while True:
names = list(dict.fromkeys(pseudo(rng, rng.randint(2, 3), True) for _ in range(30)))[:12]
tn, others = names[0], names[1:]
attr = rng.choice(kinds)
ans = gen_answer(attr, rng)
needle = fact_text(rng, attr, tn, ans)
question = rng.choice(ATTRS[attr]["qs"]).format(n=tn)
qtext = "Q: " + question + " A:"
d = dist or (rng.randint(250, 1500) if far else rng.randint(8, 36))
n_dis = min(10, max(2, d // 60)) if far else rng.randint(1, 2)
same = [fact_text(rng, a2, tn, gen_answer(a2, rng)) for a2 in rng.sample([a for a in kinds if a != attr],
rng.randint(1, 2))]
others_facts = []
for n in others[:n_dis]:
a2 = rng.choice(kinds) # может совпасть с attr: самая коварная ловушка
others_facts.append(fact_text(rng, a2, n, gen_answer(a2, rng)))
after, total = [], 0
while total < d:
s = nd.filler(rng)
after.append(s)
total += len(nd.enc(tok, s))
before = [nd.filler(rng) for _ in range(8)]
for s in others_facts:
after.insert(rng.randrange(len(after) + 1), s)
for s in same: # факты того же человека: до или после нужного
part = before if rng.random() < 0.5 else after
part.insert(rng.randrange(len(part) + 1), s)
sents = before + [needle] + after
tidx = len(before)
sent_ids = [nd.enc(tok, s) for s in sents]
q = nd.enc(tok, qtext)
flat_len = sum(len(s) for s in sent_ids) + len(q)
after_needle = flat_len - sum(len(s) for s in sent_ids[:tidx])
if (after_needle <= W) != far:
break
if not far: # длинный архив: вопрос про недавнее, но история большая
extra, extra_s, total, target = [], [], 0, hist or rng.randint(250, 1500)
while total < target:
s_ = nd.filler(rng)
e = nd.enc(tok, s_)
extra.append(e)
extra_s.append(s_)
total += len(e)
sent_ids = extra + sent_ids
sents = extra_s + sents
tidx += len(extra)
flat = [x for s in sent_ids for x in s] + q
pos, skip_from = 0, len(sent_ids)
for i in range(len(sent_ids) - 1, -1, -1): # куски, не вошедшие целиком в окно, доступны для поиска
pos += len(sent_ids[i])
if pos > W - len(q):
skip_from = i
break
t0 = time.perf_counter()
idx = aindex.build(sent_ids) if USE_INDEX else None
build_s = time.perf_counter() - t0 # строится постепенно, по мере поступления кусков; здесь считаем целиком
t0 = time.perf_counter()
picked = idx.query(q, TOPK, skip_from) if USE_INDEX else nd.retrieve(sent_ids, q, TOPK, skip_from)
retr_s = time.perf_counter() - t0
return {"window": flat[-W:], "mem": [x for i in picked for x in sent_ids[i]], "q": q, "ans": ans.lower(),
"ans_ids": nd.enc(tok, ans), "far": far, "retr_s": retr_s, "build_s": build_s, "chunks": len(sent_ids), "type": attr,
"hit": int(tidx in picked) if far else None,
# текстовое представление (для тестов на других моделях, например Qwen)
"sents_text": sents, "question": question, "ans_text": ans, "tidx": tidx}