Aleksander22's picture
Slayer1B-1.09-Instruct-26.11: weights, card, notes, training code, manifests and results (history squashed; training data not published)
6071ec5
Raw History Blame Contribute Delete
33.3 kB
"""Teacher generation for the s3 mix with Qwen/Qwen3-8B (Apache-2.0, non-thinking mode) on one GPU per shard.
Every output row keeps provenance (teacher + revision, source dataset + license, task) so the generated set can be
published separately later. Each shard runs its whole chain (translate -> solve, question -> answer -> follow-ups)
on its own slice of the seeds, so the 8 GPU processes never need to talk to each other.
CUDA_VISIBLE_DEVICES=i python teacher.py --shard i --nshard 8 --out /workspace/s3gen [--scale 1.0]
Tasks
math_en GSM8K train / AQuA-RAT train / MATH train (levels 1-3): EN step-by-step, kept only if the final answer matches the key
math_pl same problems translated to Polish by the teacher, solved in Polish, same key check
math_aug new GSM8K-style problems (PL + EN) written by the teacher, solved twice, kept only if both answers agree
know general-knowledge / advice / explanation questions in many formats (PL + EN), teacher-written questions and answers
multiturn 2-4 user turns: teacher plays the user (follow-up moves) and the assistant
safety Aegis 2.0 prompts: unsafe -> short refusal with a safe alternative, safe -> normal help (PL translations for half)
instruct verifiable format constraints (one word, exactly N items, yes/no, N bullet points, translation)
humor short jokes, funny names, playful rhymes (PL + EN)
"""
from __future__ import annotations
import argparse
import ast
import glob
import hashlib
import json
import random
import re
import time
from fractions import Fraction
from pathlib import Path
SRC = Path("/workspace/s3src")
MODEL = "/workspace/models/Qwen3-8B"
TEACHER = "Qwen/Qwen3-8B@b968826d9c"
LIC = {"gsm8k": "MIT", "aqua": "Apache-2.0", "math": "MIT", "aegis": "CC-BY-4.0", "teacher": "Apache-2.0 (teacher output)"}
SYS_MATH = {"en": "You are a careful math tutor. Solve the problem step by step, briefly: at most 8 short steps, plain text (no markdown "
"headings, no bold), LaTeX only when really needed. End with a final line exactly in the form 'Answer: <final answer>'.",
"pl": "Jesteś starannym nauczycielem matematyki. Rozwiąż zadanie krok po kroku, zwięźle: najwyżej 8 krótkich kroków, zwykły "
"tekst (bez nagłówków markdown i pogrubień), LaTeX tylko gdy naprawdę potrzebny. Pisz poprawną polszczyzną. Zakończ "
"ostatnią linią dokładnie w formie 'Odpowiedź: <wynik>'."}
MC_NOTE = {"en": " The answer is one of the lettered options: the final line must be 'Answer: <letter>'.",
"pl": " Odpowiedź jest jedną z opcji oznaczonych literami: ostatnia linia ma mieć postać 'Odpowiedź: <litera>'."}
SYS_TR = ("Przetłumacz poniższe zadanie matematyczne na naturalny, poprawny język polski. Zachowaj wszystkie liczby, wzory LaTeX i "
"oznaczenia opcji (A), B) ...) bez zmian. Imiona możesz zostawić. Zwróć wyłącznie przetłumaczoną treść zadania, bez rozwiązania.")
SYS_ASSIST = {"pl": "Jesteś pomocnym asystentem. Odpowiadaj po polsku, poprawną polszczyzną, rzeczowo i zwięźle: zwykle 2-8 zdań, listy "
"tylko gdy naprawdę pasują, bez nagłówków markdown. Nie wymyślaj faktów; jeśli czegoś nie wiesz na pewno, powiedz to.",
"en": "You are a helpful assistant. Answer in English, factually and concisely: usually 2-8 sentences, lists only when they "
"really fit, no markdown headings. Do not invent facts; if you are not sure, say so."}
CATS_PL = ["historia Polski", "historia powszechna", "geografia Polski", "geografia świata", "biologia", "ludzkie ciało i zdrowie", "chemia",
"fizyka", "astronomia", "matematyka szkolna", "literatura polska", "literatura światowa", "język polski i gramatyka",
"ortografia i interpunkcja", "sztuka i malarstwo", "muzyka", "film i seriale", "sport", "kuchnia polska", "gotowanie i przepisy",
"dieta i żywienie", "ogród i rośliny", "zwierzęta domowe", "przyroda i ekologia", "pogoda i klimat", "technologia i komputery",
"programowanie dla początkujących", "internet i bezpieczeństwo w sieci", "smartfony i aplikacje", "finanse osobiste",
"podatki i urzędy w Polsce", "prawa konsumenta", "praca i kariera", "nauka i studia", "szkoła i edukacja", "wychowanie dzieci",
"relacje i komunikacja", "psychologia codzienna", "podróże po Polsce", "podróże za granicę", "samochody i prowadzenie",
"transport publiczny", "dom i remont", "sprzątanie i porządki", "moda i ubrania", "hobby i rękodzieło", "gry planszowe i komputerowe",
"filozofia", "religie świata", "polityka i państwo (neutralnie)", "ekonomia", "wynalazki i odkrycia", "języki obce", "kultura i tradycje polskie",
"święta i obyczaje", "architektura", "medycyna i pierwsza pomoc", "sen i odpoczynek", "sport i trening w domu", "motywacja i nawyki"]
CATS_EN = ["world history", "geography", "biology", "human body and health", "chemistry", "physics", "astronomy", "school mathematics",
"literature", "English grammar", "art and painting", "music", "movies", "sports", "cooking", "nutrition", "gardening", "pets",
"nature and environment", "weather and climate", "computers and technology", "beginner programming", "online safety",
"personal finance", "careers and job hunting", "studying and learning", "parenting", "relationships and communication",
"everyday psychology", "travel", "cars and driving", "home repair", "cleaning", "fashion", "hobbies and crafts", "games",
"philosophy", "world religions", "economics", "inventions and discoveries", "language learning", "holidays and traditions",
"architecture", "first aid", "sleep", "fitness at home", "habits and motivation", "space exploration", "oceans", "dinosaurs"]
STYLES_PL = ["krótkie pytanie faktograficzne", "prośba o wyjaśnienie 'dlaczego' lub 'jak to działa'", "porównanie dwóch rzeczy",
"prośba o praktyczną radę w konkretnej sytuacji", "prośba o wyjaśnienie jak dziecku", "prośba o listę kroków",
"pytanie o definicję pojęcia", "pytanie potoczne, pisane bez polskich znaków albo z literówką", "pytanie z opisem własnej sytuacji",
"prośba o krótkie podsumowanie tematu", "pytanie 'co jest lepsze/czy warto'", "pytanie podchwytliwe lub z błędnym założeniem",
"luźna rozmowa / small talk", "prośba o pomysły (burza mózgów)"]
STYLES_EN = ["short factual question", "asking 'why' or 'how does it work'", "comparison of two things", "asking for practical advice in a specific situation",
"explain like I'm five", "asking for a list of steps", "asking for a definition", "casual question with typos or no capitals",
"question describing a personal situation", "asking for a short summary of a topic", "'which is better / is it worth it' question",
"trick question or one with a false premise", "small talk", "asking for ideas (brainstorm)"]
MOVES_PL = ["dopytaj o szczegół z ostatniej odpowiedzi", "poproś o konkretny przykład", "poproś o prostsze wyjaśnienie", "nie zgódź się albo wskaż wątpliwość",
"poproś o krótsze podsumowanie w 1-2 zdaniach", "zadaj powiązane, nowe pytanie", "opisz swoją sytuację i zapytaj, co z tego wynika dla ciebie",
"odwołaj się do czegoś, co asystent wspomniał wcześniej (np. 'a to drugie?')", "podziękuj i zadaj kolejne pytanie", "poproś o listę kroków albo plan",
"zmień temat na pokrewny", "napisz krótko i potocznie, jak w komunikatorze"]
MOVES_EN = ["ask about a detail from the last answer", "ask for a concrete example", "ask for a simpler explanation", "disagree or raise a doubt",
"ask for a 1-2 sentence summary", "ask a related new question", "describe your own situation and ask what it means for you",
"refer back to something the assistant mentioned earlier", "say thanks and ask another question", "ask for steps or a plan",
"switch to a related topic", "write briefly and casually, like in a chat app"]
THINGS = {"pl": ["owoców", "warzyw", "kolorów", "stolic europejskich", "zwierząt domowych", "instrumentów muzycznych", "polskich miast", "planet Układu Słonecznego",
"polskich pisarzy", "języków programowania", "sportów zespołowych", "rzek w Polsce", "gatunków muzycznych", "mebli", "ptaków"],
"en": ["fruits", "vegetables", "colours", "European capitals", "pets", "musical instruments", "planets", "programming languages", "team sports",
"rivers", "music genres", "pieces of furniture", "birds", "countries in Africa", "board games"]}
NUM_PL = {2: "dwa", 3: "trzy", 4: "cztery", 5: "pięć"}
JOKE_TOPICS = {"pl": ["programistach", "kotach", "nauczycielach", "studentach", "lekarzach", "pogodzie", "poniedziałkach", "kawie", "matematyce",
"informatykach", "rowerzystach", "biurze", "wakacjach", "gotowaniu", "psach", "sąsiadach", "zakupach", "pociągach"],
"en": ["programmers", "cats", "teachers", "students", "doctors", "the weather", "Mondays", "coffee", "math", "dogs", "the office",
"holidays", "cooking", "neighbours", "computers"]}
# ------------------------------------------------------------------ answer checking
def last_answer(text, lang):
keys = ["Odpowiedź:", "Odpowiedz:", "Answer:"] if lang == "pl" else ["Answer:"]
for line in reversed(text.strip().splitlines()):
for k in keys:
if k in line:
return line.split(k, 1)[1].strip().strip(".").strip()
return None
def to_num(s):
if s is None:
return None
s = s.replace("\\$", "").replace("$", "").replace(",", "").replace("\u00a0", "").replace(" ", "").replace("%", "")
s = re.sub(r"\\(text|mathrm)\{[^}]*\}", "", s)
s = re.sub(r"(zł|PLN|USD|dollars?|dolar\w*|km|cm|m|kg|g|h|min|minut\w*|godzin\w*|years?|lat|osób|sztuk\w*|units?)\.?$", "", s, flags=re.I)
m = re.fullmatch(r"-?\d+(\.\d+)?", s)
if m:
return float(s)
m = re.fullmatch(r"\\?d?frac\{(-?\d+)\}\{(\d+)\}", s.replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac"))
if m:
return float(Fraction(int(m.group(1)), int(m.group(2))))
m = re.fullmatch(r"(-?\d+)/(\d+)", s)
if m and int(m.group(2)):
return float(Fraction(int(m.group(1)), int(m.group(2))))
return None
def norm_tex(s):
s = (s or "").strip().strip("$").replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac").replace("\\left", "").replace("\\right", "")
s = s.replace("\\!", "").replace("\\,", "").replace(" ", "").replace("^\\circ", "").replace("^{\\circ}", "").replace("\\%", "").rstrip(".")
s = re.sub(r"\\text\{\s*([^}]*)\}", r"\1", s)
return s
def boxed(sol):
i = sol.rfind("\\boxed")
if i < 0:
return None
j, depth, out = sol.find("{", i), 0, ""
for ch in sol[j:]:
depth += ch == "{"
depth -= ch == "}"
out += ch
if depth == 0:
break
return out[1:-1]
def same(pred, gold, mc=False):
if pred is None or gold is None:
return False
if mc:
m = re.match(r"\(?([A-E])\b", pred.strip())
return bool(m) and m.group(1) == gold
a, b = to_num(pred), to_num(gold)
if a is not None and b is not None:
return abs(a - b) <= 1e-6 * max(1, abs(b))
return norm_tex(pred) == norm_tex(gold)
# ------------------------------------------------------------------ seeds
def seeds_math(rnd):
import pyarrow.parquet as pq
out = []
for r in pq.read_table(SRC / "openai__gsm8k/main/train-00000-of-00001.parquet").to_pylist():
out.append({"src": "gsm8k", "q": r["question"], "gold": r["answer"].split("####")[-1].strip().replace(",", ""), "mc": False})
aq = pq.read_table(SRC / "deepmind__aqua_rat/raw/train-00000-of-00001.parquet").to_pylist()
rnd.shuffle(aq)
for r in aq[:45000]:
opts = r["options"] if isinstance(r["options"], list) else ast.literal_eval(r["options"])
if len(r["question"]) > 900:
continue
out.append({"src": "aqua", "q": r["question"].strip() + "\nOptions: " + " ".join(opts), "gold": r["correct"].strip(), "mc": True})
for f in sorted(glob.glob(str(SRC / "EleutherAI__hendrycks_math/*/train-*.parquet"))):
for r in pq.read_table(f).to_pylist():
if r["level"] in ("Level 1", "Level 2", "Level 3") and "[asy]" not in r["problem"]:
g = boxed(r["solution"])
if g:
out.append({"src": "math", "q": r["problem"], "gold": g, "mc": False, "level": r["level"], "type": r["type"]})
return out
def seeds_safety(rnd):
d = json.load(open(SRC / "nvidia__Aegis-AI-Content-Safety-Dataset-2.0/train.json"))
uns = [x for x in d if x["prompt_label"] == "unsafe" and x["prompt"] and x["prompt"] != "REDACTED" and 15 < len(x["prompt"]) < 600]
saf = [x for x in d if x["prompt_label"] == "safe" and x["prompt"] and x["prompt"] != "REDACTED" and 15 < len(x["prompt"]) < 600]
rnd.shuffle(uns)
rnd.shuffle(saf)
return [{"prompt": x["prompt"], "unsafe": True, "cat": x["violated_categories"]} for x in uns[:5000]] + \
[{"prompt": x["prompt"], "unsafe": False, "cat": ""} for x in saf[:2500]]
# ------------------------------------------------------------------ main
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--shard", type=int, required=True)
ap.add_argument("--nshard", type=int, default=8)
ap.add_argument("--out", default="/workspace/s3gen")
ap.add_argument("--scale", type=float, default=1.0)
ap.add_argument("--only", default="")
a = ap.parse_args()
from vllm import LLM, SamplingParams
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
only = set(a.only.split(",")) if a.only else None
llm = LLM(MODEL, dtype="bfloat16", max_model_len=4096, gpu_memory_utilization=0.90, enable_prefix_caching=True, seed=a.shard)
rnd = random.Random(f"s3-teacher-{a.shard}")
mine = lambda xs: [x for i, x in enumerate(xs) if i % a.nshard == a.shard]
def chat(convs, temp=0.7, max_tokens=700, n=1):
if not convs:
return []
sp = SamplingParams(temperature=temp, top_p=0.9, max_tokens=max_tokens, n=n, seed=rnd.randint(0, 2**31))
res = llm.chat(convs, sp, chat_template_kwargs={"enable_thinking": False}, use_tqdm=False)
return [[(o.text.strip(), o.finish_reason) for o in r.outputs] for r in res]
files = {}
def emit(task, lang, messages, source, extra=None):
if task not in files:
files[task] = open(out / f"{task}.s{a.shard}.jsonl", "a", encoding="utf-8")
rid = hashlib.sha1(json.dumps(messages, ensure_ascii=False).encode()).hexdigest()[:16]
files[task].write(json.dumps({"id": f"{task}-{rid}", "task": task, "lang": lang, "messages": messages, "teacher": TEACHER,
"source": source, "source_license": LIC.get(source, LIC["teacher"]), **(extra or {})}, ensure_ascii=False) + "\n")
files[task].flush()
def log(*x):
print(time.strftime("%H:%M:%S"), f"[shard {a.shard}]", *x, flush=True)
S = lambda c: {"role": "system", "content": c}
U = lambda c: {"role": "user", "content": c}
A = lambda c: {"role": "assistant", "content": c}
want = lambda t: only is None or t in only
# ---------------- math EN + PL
if want("math"):
ms = mine(seeds_math(random.Random("math-seeds")))
ms = ms[: int(len(ms) * a.scale)]
log("math seeds", len(ms))
res = chat([[S(SYS_MATH["en"] + (MC_NOTE["en"] if m["mc"] else "")), U(m["q"])] for m in ms], temp=0.6, max_tokens=700)
ok = 0
for m, r in zip(ms, res):
t, fin = r[0]
if fin == "stop" and same(last_answer(t, "en"), m["gold"], m["mc"]):
emit("math_en", "en", [U(m["q"]), A(t)], m["src"], {"gold": m["gold"]})
ok += 1
log("math_en kept", ok, "/", len(ms))
tr = chat([[S(SYS_TR), U(m["q"])] for m in ms], temp=0.3, max_tokens=900)
pl = [(m, r[0][0]) for m, r in zip(ms, tr) if r[0][1] == "stop" and len(r[0][0]) > 10]
res = chat([[S(SYS_MATH["pl"] + (MC_NOTE["pl"] if m["mc"] else "")), U(q)] for m, q in pl], temp=0.6, max_tokens=800)
ok = 0
for (m, q), r in zip(pl, res):
t, fin = r[0]
if fin == "stop" and same(last_answer(t, "pl"), m["gold"], m["mc"]):
emit("math_pl", "pl", [U(q), A(t)], m["src"], {"gold": m["gold"], "translated_by": TEACHER})
ok += 1
log("math_pl kept", ok, "/", len(pl))
# ---------------- new GSM-style problems, solved twice
if want("math_aug"):
import pyarrow.parquet as pq
g = [r["question"] for r in pq.read_table(SRC / "openai__gsm8k/main/train-00000-of-00001.parquet").to_pylist()]
n_aug = int(9000 * a.scale)
prompts, langs = [], []
for _ in range(n_aug):
lang = rnd.choice(["pl", "pl", "en"])
seed = rnd.choice(g)
if lang == "pl":
p = (f"Przykład zadania tekstowego z matematyki dla szkoły podstawowej:\n{seed}\n\nNapisz JEDNO nowe, inne zadanie o podobnej trudności "
f"(2-5 kroków rachunkowych), osadzone w polskich realiach (złotówki, polskie imiona i miejsca), z inną historią i innymi liczbami, "
f"którego odpowiedzią jest jedna liczba całkowita. Napisz poprawną polszczyzną. Zwróć wyłącznie treść zadania.")
else:
p = (f"Example of a grade-school math word problem:\n{seed}\n\nWrite ONE new, different problem of similar difficulty (2-5 arithmetic steps), "
f"with a different story and different numbers, whose answer is a single whole number. Output only the problem text.")
prompts.append([U(p)])
langs.append(lang)
probs = chat(prompts, temp=1.0, max_tokens=300)
items = [(l, r[0][0]) for l, r in zip(langs, probs) if r[0][1] == "stop" and 40 < len(r[0][0]) < 900]
sol = chat([[S(SYS_MATH[l]), U(q)] for l, q in items], temp=0.7, max_tokens=700, n=2)
ok = 0
for (l, q), r in zip(items, sol):
(t1, f1), (t2, f2) = r
a1, a2 = to_num(last_answer(t1, l)), to_num(last_answer(t2, l))
if f1 == f2 == "stop" and a1 is not None and a1 == a2 and float(a1).is_integer():
emit("math_aug", l, [U(q), A(t1)], "teacher", {"self_consistent": True})
ok += 1
log("math_aug kept", ok, "/", len(items))
# ---------------- knowledge questions -> answers -> multi-turn
if want("know"):
reps = max(1, int(round(4 * a.scale)))
jobs = [("pl", c, s) for c in CATS_PL for s in STYLES_PL for _ in range(reps)] + [("en", c, s) for c in CATS_EN for s in STYLES_EN for _ in range(max(1, reps - 1))]
jobs = mine(jobs)
qs_raw = chat([[U((f"Wygeneruj 8 różnorodnych wiadomości, które prawdziwy użytkownik mógłby wysłać asystentowi AI. Temat: {c}. Styl: {s}. "
f"Każda wiadomość ma być samodzielna (bez odwołań do wcześniejszej rozmowy), po polsku, o różnej długości i formie. "
f"Zwróć wyłącznie listę JSON z 8 stringami.") if l == "pl" else
(f"Generate 8 diverse messages a real user might send to an AI assistant. Topic: {c}. Style: {s}. Each message must be "
f"self-contained, in English, with varied length and form. Return only a JSON list of 8 strings."))] for l, c, s in jobs],
temp=1.0, max_tokens=900)
qs, seen = [], set()
for (l, c, s), r in zip(jobs, qs_raw):
t = re.sub(r"^```(json)?|```$", "", r[0][0].strip()).strip()
try:
arr = json.loads(t)
except Exception:
continue
for q in arr if isinstance(arr, list) else []:
if isinstance(q, str) and 8 < len(q) < 600 and q.lower() not in seen:
seen.add(q.lower())
qs.append((l, c, s, q))
log("know questions", len(qs))
ans = chat([[S(SYS_ASSIST[l]), U(q)] for l, c, s, q in qs], temp=0.5, max_tokens=500)
convs = []
for (l, c, s, q), r in zip(qs, ans):
t, fin = r[0]
if fin == "stop" and t:
convs.append({"lang": l, "cat": c, "style": s, "msgs": [U(q), A(t)]})
rnd.shuffle(convs)
n_multi = int(len(convs) * 0.75)
multi, single = convs[:n_multi], convs[n_multi:]
for cv in single:
emit("know", cv["lang"], cv["msgs"], "teacher", {"category": cv["cat"], "style": cv["style"]})
target = {id(cv): rnd.choice([2, 3, 3, 4]) for cv in multi}
alive = multi
for rnd_i in range(3):
alive = [cv for cv in alive if len([m for m in cv["msgs"] if m["role"] == "user"]) < target[id(cv)]]
if not alive:
break
ups = []
for cv in alive:
tr = "\n\n".join(("UŻYTKOWNIK: " if m["role"] == "user" else "ASYSTENT: ") + m["content"] for m in cv["msgs"]) if cv["lang"] == "pl" else \
"\n\n".join(("USER: " if m["role"] == "user" else "ASSISTANT: ") + m["content"] for m in cv["msgs"])
mv = rnd.choice(MOVES_PL if cv["lang"] == "pl" else MOVES_EN)
ups.append([U((f"Oto rozmowa użytkownika z asystentem AI:\n\n{tr}\n\nNapisz JEDNĄ następną wiadomość użytkownika. Ruch: {mv}. Pisz naturalnie, "
f"jak człowiek, po polsku. Zwróć wyłącznie treść tej wiadomości.") if cv["lang"] == "pl" else
(f"Here is a conversation between a user and an AI assistant:\n\n{tr}\n\nWrite the user's NEXT single message. Move: {mv}. "
f"Write naturally, like a person. Return only the message text."))])
umsg = chat(ups, temp=0.9, max_tokens=200)
nxt = []
for cv, r in zip(alive, umsg):
t, fin = r[0]
t = re.sub(r"^(UŻYTKOWNIK|USER|Użytkownik|User):\s*", "", t).strip().strip('"„”')
if fin == "stop" and 2 < len(t) < 500:
cv["msgs"].append(U(t))
nxt.append(cv)
rep = chat([[S(SYS_ASSIST[cv["lang"]])] + cv["msgs"] for cv in nxt], temp=0.5, max_tokens=500)
alive = []
for cv, r in zip(nxt, rep):
t, fin = r[0]
if fin == "stop" and t:
cv["msgs"].append(A(t))
alive.append(cv)
else:
cv["msgs"].pop()
log("multiturn round", rnd_i + 2, "alive", len(alive))
for cv in multi:
if len(cv["msgs"]) >= 4:
emit("multiturn", cv["lang"], cv["msgs"], "teacher", {"category": cv["cat"], "style": cv["style"], "user_turns": len(cv["msgs"]) // 2})
else:
emit("know", cv["lang"], cv["msgs"][:2], "teacher", {"category": cv["cat"], "style": cv["style"]})
# ---------------- safety
if want("safety"):
ss = mine(seeds_safety(random.Random("aegis")))
half = [rnd.random() < 0.5 for _ in ss]
tr = chat([[U("Przetłumacz na naturalny polski. Zwróć wyłącznie tłumaczenie:\n\n" + x["prompt"])] for x, h in zip(ss, half) if h], temp=0.3, max_tokens=400)
it = iter(tr)
items = []
for x, h in zip(ss, half):
if h:
t, fin = next(it)[0]
if fin != "stop":
continue
items.append(("pl", t, x))
else:
items.append(("en", x["prompt"], x))
sysm = {("pl", True): "Ta prośba jest szkodliwa, niebezpieczna lub nieetyczna. Odmów po polsku krótko i uprzejmie (1-3 zdania), bez moralizowania i bez "
"podawania jakichkolwiek szkodliwych szczegółów; jeśli to możliwe, zaproponuj bezpieczną, pomocną alternatywę.",
("en", True): "This request is harmful, dangerous or unethical. Decline briefly and politely (1-3 sentences), without lecturing and without any "
"harmful details; if possible, offer a safe, helpful alternative.",
("pl", False): SYS_ASSIST["pl"], ("en", False): SYS_ASSIST["en"]}
# Aegis labels some legitimate requests (medical, legal, sexual-health information) as unsafe: the teacher re-judges
# every "unsafe" prompt, and only the ones it also finds harmful get a refusal; the rest get a normal answer.
judge = chat([[U("Would fully answering the following request help someone cause real harm (violence, crime, weapons, hacking, "
"self-harm, abuse, hate, sexual content involving minors, dangerous drugs)? Reply with exactly one word: YES or NO.\n\n"
f"Request: {p}")] for l, p, x in items], temp=0.0, max_tokens=3)
harmful = [x["unsafe"] and r[0][0].strip().upper().startswith("YES") for (l, p, x), r in zip(items, judge)]
res = chat([[S(sysm[(l, h)]), U(p)] for (l, p, x), h in zip(items, harmful)], temp=0.6, max_tokens=350)
for (l, p, x), h, r in zip(items, harmful, res):
t, fin = r[0]
if fin == "stop" and t:
emit("safety", l, [U(p), A(t)], "aegis", {"aegis_unsafe": x["unsafe"], "refused": h, "aegis_category": x["cat"]})
log("safety done", len(items))
# ---------------- verifiable instruction following
if want("instruct"):
jobs = []
for _ in range(int(1600 * a.scale)):
l = rnd.choice(["pl", "pl", "en"])
k = rnd.choice(["list_n", "one_word", "yesno", "bullets", "translate", "two_sent"])
if k == "list_n":
n, th = rnd.randint(2, 5), rnd.choice(THINGS[l])
p = f"Wymień dokładnie {NUM_PL[n]} przykłady {th}, oddzielone przecinkami, nic więcej." if l == "pl" and n < 5 else \
(f"Wymień dokładnie {NUM_PL[n]} przykładów {th}, oddzielonych przecinkami, nic więcej." if l == "pl" else f"List exactly {n} {th}, separated by commas, nothing else.")
jobs.append((l, k, n, p))
elif k == "one_word":
p = rnd.choice(["Jednym słowem: jaki kolor ma niebo w pogodny dzień?", "Jednym słowem: jak nazywa się stolica Polski?", "Odpowiedz jednym słowem: jakie zwierzę miauczy?",
"Jednym słowem: jaka pora roku następuje po zimie?", "Jednym słowem: z czego robi się lód?", "Jednym słowem: najdłuższa rzeka w Polsce?"] if l == "pl" else
["One word only: what colour is the sky on a clear day?", "One word: capital of France?", "Answer in one word: which animal barks?",
"One word: what season comes after winter?", "In one word: what is ice made of?", "One word: the largest ocean?"])
jobs.append((l, k, 1, p))
elif k == "yesno":
p = rnd.choice(["Czy Ziemia krąży wokół Słońca? Odpowiedz tylko tak lub nie.", "Czy pingwiny potrafią latać? Odpowiedz tylko tak lub nie.",
"Czy woda wrze w 100°C przy normalnym ciśnieniu? Tylko tak lub nie.", "Czy Kraków leży nad Wisłą? Odpowiedz tak lub nie.",
"Czy 7 jest liczbą parzystą? Tylko tak lub nie.", "Czy wieloryb jest rybą? Odpowiedz tylko tak lub nie."] if l == "pl" else
["Does the Earth orbit the Sun? Answer only yes or no.", "Can penguins fly? Yes or no only.", "Is 7 an even number? Answer yes or no.",
"Is a whale a fish? Only yes or no.", "Does water boil at 100°C at sea level? Yes or no only.", "Is Paris in Italy? Answer yes or no."])
jobs.append((l, k, 1, p))
elif k == "bullets":
n, c = rnd.randint(2, 5), rnd.choice(CATS_PL if l == "pl" else CATS_EN)
p = f"Podaj dokładnie {n} krótkie wskazówki na temat: {c}. Każda w osobnej linii zaczynającej się od '- '. Nic więcej." if l == "pl" else \
f"Give exactly {n} short tips about {c}. Each on its own line starting with '- '. Nothing else."
jobs.append((l, k, n, p))
elif k == "two_sent":
c = rnd.choice(CATS_PL if l == "pl" else CATS_EN)
p = f"Wyjaśnij w maksymalnie dwóch zdaniach, czym zajmuje się dziedzina: {c}." if l == "pl" else f"In at most two sentences, explain what the field of {c} is about."
jobs.append((l, k, 2, p))
else:
src = rnd.choice(["Dzień dobry, jak się masz?", "Gdzie jest najbliższa apteka?", "Jutro pojadę pociągiem do Gdańska.", "Lubię czytać książki wieczorem.",
"Czy możesz mi pomóc z tym zadaniem?", "Ten obiad był naprawdę pyszny.", "Spotkajmy się o siódmej przed kinem."]) if l == "pl" else \
rnd.choice(["Good morning, how are you?", "Where is the nearest pharmacy?", "Tomorrow I will take the train to Gdańsk.", "I like reading books in the evening.",
"Can you help me with this task?", "That dinner was really delicious.", "Let's meet at seven in front of the cinema."])
p = f"Przetłumacz na angielski: „{src}”. Zwróć tylko tłumaczenie." if l == "pl" else f"Translate into Polish: \"{src}\". Return only the translation."
jobs.append((l, k, 0, p))
res = chat([[S(SYS_ASSIST[l] + (" Ściśle przestrzegaj ograniczeń formatu z polecenia." if l == "pl" else " Follow the format constraints exactly.")), U(p)] for l, k, n, p in jobs],
temp=0.7, max_tokens=250)
ok = 0
for (l, k, n, p), r in zip(jobs, res):
t, fin = r[0]
if fin != "stop":
continue
good = {"list_n": lambda: len([x for x in t.split(",") if x.strip()]) == n and "\n" not in t.strip(),
"one_word": lambda: len(re.findall(r"\w+", t)) == 1,
"yesno": lambda: re.fullmatch(r"(tak|nie|yes|no)\.?", t.strip().lower()) is not None,
"bullets": lambda: len([x for x in t.strip().splitlines() if x.strip()]) == n and all(x.strip().startswith("- ") for x in t.strip().splitlines() if x.strip()),
"two_sent": lambda: 1 <= len(re.findall(r"[.!?](\s|$)", t.strip())) <= 2,
"translate": lambda: 0 < len(t) < 200 and "\n" not in t.strip()}[k]()
if good:
emit("instruct", l, [U(p), A(t)], "teacher", {"constraint": k})
ok += 1
log("instruct kept", ok, "/", len(jobs))
# ---------------- humour
if want("humor"):
jobs = []
for _ in range(int(700 * a.scale)):
l = rnd.choice(["pl", "en"])
tp = rnd.choice(JOKE_TOPICS[l])
k = rnd.choice(["joke", "joke", "name", "rhyme", "pun"])
p = {("pl", "joke"): f"Opowiedz krótki, zabawny dowcip o {tp}.", ("pl", "name"): f"Wymyśl trzy zabawne nazwy dla kawiarni, sklepu albo firmy, która kojarzy się z żartami o {tp}.",
("pl", "rhyme"): f"Napisz zabawny, rymowany dwuwiersz o {tp}.", ("pl", "pun"): f"Wymyśl krótką grę słów albo żart słowny o {tp}.",
("en", "joke"): f"Tell me a short, funny joke about {tp}.", ("en", "name"): f"Come up with three funny names for a café, shop or company about {tp}.",
("en", "rhyme"): f"Write a funny rhyming couplet about {tp}.", ("en", "pun"): f"Make a short pun about {tp}."}[(l, k)]
jobs.append((l, k, p))
res = chat([[S(("Jesteś dowcipnym asystentem. Odpowiadaj krótko (do 5 zdań), naturalnie, poprawną polszczyzną, bez obraźliwych treści." if l == "pl" else
"You are a witty assistant. Answer briefly (up to 5 sentences), naturally, nothing offensive.")), U(p)] for l, k, p in jobs], temp=0.9, max_tokens=250)
for (l, k, p), r in zip(jobs, res):
t, fin = r[0]
if fin == "stop" and t:
emit("humor", l, [U(p), A(t)], "teacher", {"kind": k})
log("humor done", len(jobs))
for f in files.values():
f.close()
log("SHARD_DONE")
if __name__ == "__main__":
main()