Salt la conținut

Ajustarea fină supervizată

IntermediarLectură: 5 min

Modelul preantrenat știe doar să continue texte. Dacă primește o instrucțiune, o continuă cu ce i se pare probabil, iar asta rareori este ce cerea instrucțiunea. Să luăm instrucțiunea „Words: rain, cake, jump Story:”, care cere o poveste cu aceste trei cuvinte. Modelul de pe pagina anterioară răspunde astfel.

Terminal window
python sample.py checkpoints/pretrain/model.pt "Words: rain, cake, jump Story:" -n 1 --tokens 120
Words: rain, cake, jump Story: "Wow, Mia! The cake is so yummy!" Mia and Ben are
surprised. They are curious to see the cake. They find out that the cake is gone. They see
a big cake behind them. The cake is empty. It is not safe. It is fun to stay inside. Mia
and Ben run to the kitchen. They find the cake inside. They look at the cake. They see a
big cake on the ground. It is a big cake, a cookie inside. The cake is red cake. "Wow,
look at this cake!" Mia says. "This cake is not

Textul începe la mijlocul unei povești, cu o replică, și folosește doar „cake”. Cuvintele „rain” și „jump” nu apar. Ajustarea fină supervizată (supervised fine-tuning, SFT) continuă antrenarea pe perechi formate dintr-o instrucțiune și răspunsul dorit, ca modelul să învețe să răspundă la instrucțiuni. Prin aceeași etapă trec și asistenții conversaționali, la care instrucțiunile sunt întrebări și cereri, iar răspunsurile sunt scrise sau verificate de oameni. Aici, instrucțiunile cer o poveste cu anumite cuvinte, trăsături sau un rezumat, iar răspunsurile sunt chiar poveștile.

La redare, playerul se încarcă de pe YouTube (detalii).

Episodul 8Ajustarea fină supervizată (supervised fine-tuning) a unui GPT miccapitolul „Ce schimbă ajustarea fină”

TinyStories-Instruct conține poveștile din prima versiune a setului TinyStories, fiecare însoțită de câteva dintre câmpurile următoare.

  • Features: trăsături ale poveștii, de exemplu Dialogue, BadEnding sau Twist.
  • Words: trei cuvinte care trebuie folosite.
  • Random sentence: o propoziție care trebuie să apară în poveste.
  • Summary: un rezumat de o propoziție.

Câmpurile apar în orice ordine, iar uneori rezumatul vine după poveste. Funcția parse desparte un document în câmpuri, iar instruction le rescrie mereu în aceeași ordine, cu Story: la final.

sft.py
FIELDS = ["Features", "Words", "Random sentence", "Summary"]
FIELD = re.compile(r"^(Features|Words|Random sentence|Summary|Story):", re.MULTILINE)
def parse(doc):
parts = FIELD.split(doc)
return {name: text.strip() for name, text in zip(parts[1::2], parts[2::2])}
def instruction(fields):
lines = [f"{name}: {fields[name]}" for name in FIELDS if name in fields]
return "\n".join(lines + ["Story:"])

Mai jos, cele două funcții sunt aplicate primului document din eșantionul de 60 de instrucțiuni.

print(docs[0].strip()[:500], "…")
print()
fields = parse(docs[0])
print(list(fields))
print()
print(instruction(fields))
after = sum(1 for d in docs if d.find("Summary:") > d.find("Story:") >= 0)
print()
print(f"Documente cu rezumatul după poveste: {after} din {len(docs)}")

Codul poate fi modificat și rulat direct în browser (Ctrl + Enter).

Fiecare exemplu de antrenare este format din tokenurile instrucțiunii, urmate de tokenurile poveștii și de <|endoftext|>, ca modelul să învețe și unde se termină o poveste.

sft.py
def build_examples(path, tokenizer, block_size, limit=None):
with open(path, encoding="utf-8") as f:
docs = [d for d in f.read().split(EOT) if d.strip()][:limit]
examples = []
for doc in docs:
fields = parse(doc)
if not fields.get("Story"):
continue
prompt = tokenizer.encode(instruction(fields))
story = tokenizer.encode(fields["Story"]) + [tokenizer.eot_id]
ids = (prompt + story)[: block_size + 1]
if len(ids) > len(prompt):
examples.append((ids, len(prompt)))
return examples

Exemplele mai lungi decât fereastra de context sunt tăiate la 257 de tokenuri, adică 256 de intrări și ținta ultimei poziții. Pe lângă exemplu, funcția păstrează și lungimea instrucțiunii, de care avem nevoie la pasul următor.

Exemplele au lungimi diferite, așa că fiecare lot este completat până la lungimea celui mai lung exemplu, cu tokenul [PAD]. Și pozițiile de completare (padding) au ținta -1.

sft.py
def make_batch(examples, pad_id, device):
longest = max(len(ids) for ids, _ in examples)
x = np.full((len(examples), longest - 1), pad_id, dtype=np.int64)
y = np.full((len(examples), longest - 1), -1, dtype=np.int64)
for row, (ids, prompt_len) in enumerate(examples):
x[row, : len(ids) - 1] = ids[:-1]
y[row, prompt_len - 1 : len(ids) - 1] = ids[prompt_len:]
return torch.from_numpy(x).to(device), torch.from_numpy(y).to(device)

Ultima poziție a instrucțiunii (cele două puncte de după Story) prezice primul cuvânt al poveștii, deci acolo încep țintele. Ultimul token al poveștii prezice <|endoftext|>. Exemplul de mai jos construiește un lot de trei exemple din eșantion, cu o variantă NumPy a funcției make_batch. Pentru cel mai scurt exemplu, afișează granița dintre instrucțiune și poveste, apoi finalul poveștii și începutul completării.

import numpy as np
from tokenizer import WordTokenizer, build_vocab
vocab, _ = build_vocab(["povesti.txt", "instructiuni.txt"], size=2000)
tokenizer = WordTokenizer(vocab)
# Primele trei documente care încap întregi în fereastră.
examples = []
for doc in docs:
fields = parse(doc)
prompt = tokenizer.encode(instruction(fields))
story = tokenizer.encode(fields["Story"]) + [tokenizer.eot_id]
if len(prompt + story) <= 257 and len(examples) < 3:
examples.append((prompt + story, len(prompt)))
def make_batch(examples, pad_id):
longest = max(len(ids) for ids, _ in examples)
x = np.full((len(examples), longest - 1), pad_id, dtype=np.int64)
y = np.full((len(examples), longest - 1), -1, dtype=np.int64)
for row, (ids, prompt_len) in enumerate(examples):
x[row, : len(ids) - 1] = ids[:-1]
y[row, prompt_len - 1 : len(ids) - 1] = ids[prompt_len:]
return x, y
x, y = make_batch(examples, tokenizer.pad_id)
print("Lungimi:", [len(ids) for ids, _ in examples], "-> lotul are forma", x.shape)
def show(row, positions):
for t in positions:
target = tokenizer.id_to_token[y[row, t]] if y[row, t] != -1 else -1
print(f" {t:>3} {tokenizer.id_to_token[x[row, t]]:<14} {target}")
# Cel mai scurt exemplu are și poziții de completare.
row = min(range(len(examples)), key=lambda r: len(examples[r][0]))
ids, prompt_len = examples[row]
print()
print("Poziția, intrarea și ținta, la granița dintre instrucțiune și poveste:")
show(row, range(prompt_len - 4, prompt_len + 3))
print()
print("Finalul poveștii și începutul completării:")
show(row, range(len(ids) - 4, min(len(ids) + 2, x.shape[1])))

Codul poate fi modificat și rulat direct în browser (Ctrl + Enter).

Restul fișierului sft.py seamănă cu preantrenarea.

sft.py
def random_batch(examples, pad_id, device):
picks = torch.randint(len(examples), (BATCH_SIZE,)).tolist()
return make_batch([examples[i] for i in picks], pad_id, device)
@torch.no_grad()
def estimate_loss(model, examples, pad_id, batches=20):
model.eval()
device = next(model.parameters()).device
total = 0.0
for _ in range(batches):
x, y = random_batch(examples, pad_id, device)
total += model(x, y)[1].item()
model.train()
return total / batches
def main(minutes):
torch.manual_seed(1337)
device = pick_device()
model, tokenizer, _ = load_checkpoint(os.path.join(CHECKPOINTS, "pretrain", "model.pt"), device)
block_size = model.config.block_size
train = build_examples(os.path.join(DATA_DIR, "instruct_train.txt"), tokenizer, block_size)
valid = build_examples(os.path.join(DATA_DIR, "instruct_valid.txt"), tokenizer, block_size, limit=5000)
print(f"{len(train):,} exemple de antrenare, {len(valid):,} păstrate pentru validare")
params = list(model.parameters())
optimizer = torch.optim.AdamW(
[
{"params": [p for p in params if p.dim() >= 2], "weight_decay": 0.1},
{"params": [p for p in params if p.dim() < 2], "weight_decay": 0.0},
],
lr=LR,
betas=(0.9, 0.95),
)
writer = SummaryWriter(os.path.join(RUNS, time.strftime("sft-%Y%m%d-%H%M%S")))
def evaluate(step):
losses = {"train": estimate_loss(model, train, tokenizer.pad_id),
"valid": estimate_loss(model, valid, tokenizer.pad_id)}
story = write(model, tokenizer, DEMO, max_new_tokens=120, with_prompt=False)
writer.add_scalar("loss/train", losses["train"], step)
writer.add_scalar("loss/valid", losses["valid"], step)
writer.add_text("sample", story, step)
writer.flush()
print(f"pasul {step:>5} | antrenare {losses['train']:.3f} | validare {losses['valid']:.3f}", flush=True)
print(textwrap.indent(textwrap.fill(story, width=86), " "), flush=True)
budget = minutes * 60
start = time.time()
step = 0
evaluate(step)
while time.time() - start < budget:
x, y = random_batch(train, tokenizer.pad_id, device)
_, loss = model(x, y)
optimizer.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optimizer.step()
step += 1
if step % 50 == 0:
writer.add_scalar("loss/batch", loss.item(), step)
print(f"pasul {step:>5} | pierdere {loss.item():.3f} | {(time.time() - start) / 60:.1f} min", flush=True)
if step % EVAL_EVERY == 0:
evaluate(step)
if step % EVAL_EVERY != 0:
evaluate(step)
writer.close()
save_checkpoint(os.path.join(RUN_DIR, "model.pt"), model, tokenizer, step=step)
print(f"gata: {step:,} pași, {(time.time() - start) / 60:.1f} minute")

Diferențele sunt puține. Antrenarea pornește de la modelul preantrenat, checkpoints/pretrain/model.pt, nu de la ponderi aleatoare. Rata de învățare este constantă și egală cu 2⋅10−42 \cdot 10^{-4}, o treime din valoarea maximă de la preantrenare, pentru că modelul scrie deja povești, iar pașii mai mici îi ajustează comportamentul fără să șteargă ce a învățat. Loturile sunt alcătuite din 48 de exemple întregi, alese la întâmplare, nu din ferestre tăiate din text. La fiecare evaluare, modelul scrie o poveste pentru aceeași instrucțiune de test, DEMO.

Terminal window
python sft.py 10

Mai jos este rezultatul ajustării de 10 minute din seria video a laboratorului, pe același laptop ca preantrenarea. Am omis o parte din linii.

76,875 exemple de antrenare, 4,999 păstrate pentru validare
pasul 0 | antrenare 2.468 | validare 2.443
"Please teach us! We are not so scary!" The dog barked and wagged its tail. The dog
looked at the dog and chased him. "I'm sorry, I didn't know what to do." But the dog
did not want to be brave. The dog did not want Tim to scare him. He knew he would be
brave. After a while, the dog ran off the swing. It was a happy dog with the dog. They
both hugged the dog and went back to play.
pasul 50 | pierdere 2.374 | 0.4 min
pasul 100 | pierdere 2.484 | 0.8 min
pasul 250 | antrenare 2.269 | validare 2.223
Once upon a time, there was a big dog. The dog liked to play games. He would run,
jump, and play with a ball. One day, the dog ran to the park. He saw a big tree. He
wanted to drink the bird. The dog tried to drink the bird's tail. The dog looked and
saw a new friend. The dog wanted to play too. The dog wanted to help the cat. The dog
barked. The dog took a toy ball and began to climb it. The dog was very happy. The dog
and the dog played together. They became
pasul 750 | antrenare 2.048 | validare 2.061
Once upon a time, there was a big park. In the park, there was a little dog. The dog
loved to play with the ball. One day, the dog saw a new friend. The new friend wanted
to play with the toy too. The new friend was so excited. The little dog started to
play with the new friend. They played together and had lots of fun. The end.
pasul 1341 | antrenare 1.954 | validare 1.926
Once upon a time, there was a big dog. The dog was very happy. He loved to play and
run around. One day, he noticed a new friend. The dog was a happy dog. The dog was
very happy with the dog. The dog played with the dog and played with it. One night,
the dog saw a new friend. The new friend was a happy dog. The dog was nice too. The
new friend helped the new dog. The new friend was happy too.
gata: 1,341 pași, 10.1 minute

Instrucțiunea de test cere un dialog, cuvintele „dog”, „happy” și „park” și o poveste despre un câine care își face un prieten nou în parc. La pasul 0, modelul preantrenat continuă instrucțiunea cu mijlocul altei povești. După 250 de pași, modelul scrie povestea de la început, cu un câine, un parc și un prieten nou. Pierderea pe validare scade de la 2,443 la 1,926. Poveștile rămân însă simple și repetitive („The dog played with the dog”), iar dialogul cerut apare rar.

Mai jos, modelul ajustat primește aceeași instrucțiune ca la începutul paginii.

Terminal window
python sample.py checkpoints/sft/model.pt "Words: rain, cake, jump Story:" -n 1 --tokens 120
Words: rain, cake, jump Story: One day, a little girl named Lily went outside to play. She
saw a big cake with lots of colors and leaves. Lily wanted to eat the cake, so she took a
walk and went outside. She saw a big cake cake and a tray on it. She put the cake inside
and went to sleep. When the cake was there, Lily saw lots of colors and colorful colors.
She liked the cake and the pictures. She thought it was a cake cake, so she decided to
take a flower home with her mom. When they got home, Lily had a great day with her mom.

Povestea pornește de la început, cu un personaj și o întâmplare, ca poveștile din setul cu instrucțiuni. Folosește însă tot doar „cake”, chiar prea des, iar „rain” și „jump” lipsesc. Promptul are forma instrucțiunilor de la antrenare: „Words: rain, cake, jump”, apoi „Story:” pe rândul următor. Spațiile și trecerile la rând nou dispar la tokenizare, așa că promptul poate fi scris pe un singur rând.

O singură poveste nu ajunge pentru o comparație. Pe pagina următoare scriem o măsură calculată pe multe instrucțiuni: proporția de cuvinte cerute care apar în poveste. Pe 50 de instrucțiuni de validare, modelul preantrenat folosește 6,0% din cuvintele cerute, iar cel ajustat, 36,7%, de șase ori mai multe. Majoritatea cuvintelor cerute tot lipsesc, iar acesta este punctul de plecare al etapelor următoare.