Papa Programmer
Lesson 08 of 36

Formatting data for training

9 min read

Optional

One example, one line

JSON Lines, or JSONL, stores one JSON object on each line of a file, and it is the usual home of Training dataExamples used to update a model's trainable parameters. The examples and labels should be appropriate and permitted for the task.. A program can read it a line at a time, so it works for files too big to load at once. It also lets a broken record be reported by line number.

A JSONL file is not one JSON array. Do not wrap the lines in square brackets or separate them with commas.

Two common shapes

Prompt and completion. Each record has the input and the output you want. For the classifier it is the message and its label.

json
{"text": "I cannot sign in", "label": "access"}

Chat messages. Each record is a list of turns, each with a role and its text. The roles are usually system, user and assistant. This is the shape for instruction and chat tuning.

json
{"messages": [{"role": "user", "content": "I cannot sign in"}, {"role": "assistant", "content": "access"}]}

Which names and roles are accepted depends on the library and the model. Check its documentation before you write the file, and keep field names the same in every record.

Building the file

The program below turns plain records into chat records and writes each as one line. It uses json.dumps, which handles quotes and special characters, so you never build JSON by joining strings.

python
import json

rows = [
	{"text": "I cannot sign in", "label": "access"},
	{"text": "Please explain my invoice", "label": "billing"},
]
system = "Label the support request as billing, access or technical."

lines = []
for row in rows:
	record = {"messages": [
		{"role": "system", "content": system},
		{"role": "user", "content": row["text"]},
		{"role": "assistant", "content": row["label"]},
	]}
	lines.append(json.dumps(record))

print(lines[1])
print(len(lines), "lines")

It prints:

text
{"messages": [{"role": "system", "content": "Label the support request as billing, access or technical."}, {"role": "user", "content": "Please explain my invoice"}, {"role": "assistant", "content": "billing"}]}
2 lines

Each record repeats the system message. That costs a few tokens per example, and it teaches the model to expect that instruction. If you leave it out of training, leave it out when you use the model too. A mismatch between the training format and the prompt used later is a quiet cause of poor results.

Validate before you train

Check the file with a small script. It should parse each line, check the shape, and name the line that fails. The program below runs it over three lines, and the third has a mistake.

python
import json

lines = [
	'{"messages": [{"role": "user", "content": "Cannot sign in"}, {"role": "assistant", "content": "access"}]}',
	'{"messages": [{"role": "user", "content": "Invoice question"}, {"role": "assistant", "content": "billing"}]}',
	'{"messages": [{"role": "user", "content": "App is slow"}, {"role": "assistant", "content": "technical"}',
]
roles = {"system", "user", "assistant"}

def check(number, line):
	try:
		record = json.loads(line)
	except json.JSONDecodeError as error:
		return f"line {number}: not valid JSON ({error.msg})"
	messages = record.get("messages") if isinstance(record, dict) else None
	if not messages:
		return f"line {number}: no messages"
	if any(m.get("role") not in roles or not m.get("content") for m in messages):
		return f"line {number}: bad role or empty content"
	if messages[-1]["role"] != "assistant":
		return f"line {number}: last message is not the assistant's"

problems = [p for p in (check(i, line) for i, line in enumerate(lines, start=1)) if p]
print(problems or "all lines ok")

It prints:

text
["line 3: not valid JSON (Expecting ',' delimiter)"]

The script finds the unclosed bracket on line 3 and says where it is. Real validators also count the records, flag duplicates, and report the longest example in tokens, because an example longer than the model's limit will be cut short. Running this before every training job takes seconds. The Lesson Cleaning data and checking quality covers the checks that need judgement.

Use the model's chat template

A chat template turns a list of messages into the exact text, with special marker tokens, that the model was trained to read. Different models use different markers. Use the template that ships with the model, through its tokenizer, and do not write the markers by hand. A hand-written marker that the model never saw in training can quietly lower quality. The Hugging Face chat templates guide explains how to apply one.

Keep the validation and test files in the same format

Write the validation and test sets in exactly the same shape. Then the same code reads all three, and differences in the score come from the model and not from the format.

One line, one exampleJSON Lines can be read a line at a time and reports errors by line number.
Match the formatUse the roles and template the model expects, in training and in use.
Validate firstA script that checks every line saves a long run from failing late.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools