61 / 90

Day 61: Instruction Data Formats, Schemas & Token Boundary Alignment

Standardize Alpaca, ChatML, and ShareGPT schemas, align special token boundaries, and prevent prompt injection.

Models and Training 480 active minutes (8 hours)
01 120 min

Instruction Dataset Schemas: Alpaca, ChatML, and ShareGPT Multi-Turn Conventions

Agent-Assisted Exploration

Prerequisites

Completion of Day 60 foundational pre-training assessment and Python JSON data modeling.

Learning Objective

Master the structural schemas of instruction datasets, distinguishing between Alpaca single-turn format, ChatML role delimiters, and ShareGPT multi-turn conversational trees.

Instructions

Study source: within this activity's existing reading/practice time, use Hugging Face LLM Course: Fine-tuning LLMs, Chapter 11.2: Common Template Formats; Hands-on Exercise, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. 1. Inspect Stanford Alpaca schema: top-level keys 'instruction' (task description), 'input' (optional context), and 'output' (target response).
2. Contrast with ChatML markup format: structured text wrapped in explicit demarcation tokens (<|im_start|>system...<|im_end|>, <|im_start|>user...<|im_end|>, <|im_start|>assistant...<|im_end|>).
3. Analyze ShareGPT multi-turn schema: a list of message objects under 'conversations' with alternating 'from' ('human'/'gpt') and 'value' fields.
4. Understand why ambiguous plain text delimiters (such as 'User: ... Assistant:') suffer from prompt injection and delimiter hijacking, whereas dedicated boundary tokens enforce strict role sandboxing.

Practice & Prediction Log

Write a Python normalization function normalize_to_chatml(record) that detects whether a record is Alpaca format or ShareGPT format and returns a canonical list of message dictionaries [{'role': ..., 'content': ...}]. Test with both empty and populated 'input' fields.

Independent Mastery Criterion

Write a schema normalization pipeline that converts both Alpaca and ShareGPT records to verified ChatML message structures with 100% field compliance.

Authoritative Source Resources & Provenance

linking Apache-2.0

Hugging Face LLM Course: Fine-tuning LLMs

Author: Hugging Face course contributors | Original Source Link ↗

Relevant Section / Range: Chapter 11.2: Common Template Formats; Hands-on Exercise

Verified Version & Date: Public edition checked 2026-11-01; moving pages may change

Selection Rationale:

Sequenced templates, supervised fine-tuning and evaluation teaching with exercises/quizzes. LoRA method and memory claims are checked against the original paper, PEFT and the local parameter ledger, not accepted wholesale from Chapter 11.4.

Source Prerequisites:

Python, PyTorch, language-model training and the preceding chat-format lessons.

Safe Fallback (Offline Resilience):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

Compared Candidate Sources & Selection Analysis (2)
LoRA original paper ↗ compared_alternative [arXiv.org perpetual non-exclusive license / Open Access]

Retained for initialization and the low-rank method, not a beginner teaching sequence.

Hugging Face PEFT ↗ compared_alternative [Apache-2.0]

Retained for actual API and implementation defaults; reference documentation is not a complete teaching course.

linking Apache 2.0

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: README 'Data Release' (alpaca_data.json fields instruction, input, output)

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Pioneering instruction fine-tuning dataset schema establishing the instruction/input/output format widely used across open source LLMs.

Source Prerequisites:

LLM fine-tuning concepts, Python dictionary data structures.

Safe Fallback (Offline Resilience):

Standard Alpaca schemas and data transformation scripts are completely specified in lesson materials.

Compared Candidate Sources & Selection Analysis (2)

Pioneered academic instruction tuning across NLP benchmarks; Alpaca format provides the standardized single-turn JSON schema for consumer fine-tuning.

Databricks Dolly 15k Dataset ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive instruction dataset; Alpaca establishes the architectural schema archetype.

linking MIT

OpenAI ChatML (Chat Markup Language) Specification and Guide

Author: OpenAI Documentation Team | Original Source Link ↗

Relevant Section / Range: chatml.md: ChatML v0 message format (<|im_start|>role ... <|im_end|>)

Verified Version & Date: openai-python tag v0.28.1, last MIT-licensed release containing chatml.md (Verified: 2026-10-31)

Selection Rationale:

Standardized token delimiter schema (<|im_start|>, <|im_end|>) separating system, user, and assistant roles to prevent prompt injection and role confusion.

Source Prerequisites:

Tokenizer special token concepts, conversation tree data structures.

Safe Fallback (Offline Resilience):

Full ChatML delimiter specs, role headers, and token stream representations are embedded in the curriculum.

Compared Candidate Sources & Selection Analysis (2)
Anthropic Claude Prompt Engineering Guidelines ↗ compared_alternative [Proprietary Documentation]

Uses Human:/Assistant: plain text delimiters; ChatML provides formal token-level demarcation with dedicated boundary tokens.

Vicuna ShareGPT Multi-Turn Schema ↗ compared_alternative [Apache 2.0]

FastChat conversation template; ChatML is the universal token-delimited primitive.

02 120 min

Tokenizer Special Tokens, Delimiters, and Boundary Alignment

Independent Exploration

Prerequisites

Day 61 Activity 1 and Byte-Pair Encoding tokenization mechanics.

Learning Objective

Add new special tokens (<|im_start|>, <|im_end|>) to tokenizers, prevent sub-token fragmentation, and diagnose token boundary alignment hazards.

Instructions

1. Examine how standard tokenizers split unknown delimiter strings into multiple subword tokens when delimiters are not registered as special tokens.
2. Use tokenizer.add_special_tokens({'additional_special_tokens': ['<|im_start|>', '<|im_end|>']}) and inspect model embedding resize requirements.
3. Verify token boundary alignment: ensure special tokens are encoded as single discrete token IDs and decode cleanly without injecting spurious whitespace.
4. Diagnose the space-prefix issue in BPE: note how ' hello' vs 'hello' encode differently and ensure chat templates format newline and role separators consistently.

Practice & Prediction Log

Implement a test script that takes a tokenizer, adds '<|im_start|>' and '<|im_end|>', encodes '<|im_start|>user\nHello<|im_end|>', and asserts that the first and last tokens are the exact registered special token IDs of length 1 each.

Independent Mastery Criterion

Verify special token boundary integrity, ensuring zero sub-word fragmentation for ChatML delimiter tokens.

Authoritative Source Resources & Provenance

linking Apache 2.0

Hugging Face Transformers: Templates for Chat Models

Author: Hugging Face Documentation Team | Original Source Link ↗

Relevant Section / Range: Using apply_chat_template: add_generation_prompt

Verified Version & Date: Hugging Face Documentation (Verified: 2026-10-30)

Selection Rationale:

Widely adopted system for mapping list-of-dict messages into tokenized strings with tokenizer.apply_chat_template().

Source Prerequisites:

Python, Jinja2 template basics, Hugging Face PreTrainedTokenizer.

Safe Fallback (Offline Resilience):

Complete Jinja2 template implementations and boundary token unit tests are self-contained.

Compared Candidate Sources & Selection Analysis (2)
Axolotl Prompt Formats Guide ↗ compared_alternative [Apache 2.0]

Configuration-driven formatting framework; Hugging Face chat templates are the direct tokenizer-level standard.

vLLM Online Serving: Chat Template ↗ compared_alternative [Apache 2.0]

High-performance inference chat templating; HF chat templating is the training-time reference implementation.

linking Open Access

Llama 2: Open Foundation and Fine-Tuned Chat Models

Author: Hugo Touvron, Louis Martin, Kevin Stone, Peter Albert, Amjad Almahairi, et al. | Original Source Link ↗

Relevant Section / Range: Section 3.1 Supervised Fine-Tuning (SFT)

Verified Version & Date: arXiv:2307.09288v2 (Verified: 2026-10-30)

Selection Rationale:

Defines the standard LLaMA-2 instruction format ([INST] <<SYS>> ... <</SYS>> [/INST]) and analyzes token boundary alignment impact on generation stability.

Source Prerequisites:

Transformer architecture, RLHF/SFT pipelines.

Safe Fallback (Offline Resilience):

The LLaMA-2 prompt structure, token boundary rules, and comparative analysis are fully worked out in curriculum lessons.

Compared Candidate Sources & Selection Analysis (2)

Original foundation model paper without conversational chat tuning details; LLaMA-2 formalizes dialogue formatting.

Jiang et al. Mistral 7B ↗ compared_alternative [Open Access]

Adopts similar [INST] formatting; LLaMA-2 provides the foundational ablation on system prompt integration.

03 120 min

Multi-Turn Dialogue Serialization and System Prompt Conditioning

Agent-Assisted Practice

Prerequisites

Day 61 Activities 1 and 2, Jinja2 templating syntax.

Learning Objective

Render multi-turn conversational histories into linear token sequences using Jinja2 chat templates and implement safe conversation truncation that preserves system context.

Instructions

1. Formulate a Jinja2 chat template that wraps system, user, and assistant turns with ChatML delimiters (<|im_start|>role\ncontent<|im_end|>\n).
2. Study tokenizer.apply_chat_template(messages, tokenize=False/True) and understand how add_generation_prompt=True appends '<|im_start|>assistant\n' for inference.
3. Address the context-window overflow problem: when a multi-turn dialogue exceeds maximum sequence length (e.g., 2048 tokens), implement intelligent truncation.
4. Design truncation to strictly preserve the system prompt (turn 0) while pruning oldest user-assistant interaction turns first.

Practice & Prediction Log

Build a function truncate_dialogue(messages, max_tokens, tokenizer) that serializes messages with a ChatML template and prunes earliest user/assistant pairs until total encoded token length is <= max_tokens, keeping any system prompt intact.

Independent Mastery Criterion

Demonstrate intelligent conversation truncation that preserves system prompt integrity while strictly respecting sequence length limits.

Authoritative Source Resources & Provenance

linking MIT

OpenAI ChatML (Chat Markup Language) Specification and Guide

Author: OpenAI Documentation Team | Original Source Link ↗

Relevant Section / Range: chatml.md: ChatML v0 message format (<|im_start|>role ... <|im_end|>)

Verified Version & Date: openai-python tag v0.28.1, last MIT-licensed release containing chatml.md (Verified: 2026-10-31)

Selection Rationale:

Standardized token delimiter schema (<|im_start|>, <|im_end|>) separating system, user, and assistant roles to prevent prompt injection and role confusion.

Source Prerequisites:

Tokenizer special token concepts, conversation tree data structures.

Safe Fallback (Offline Resilience):

Full ChatML delimiter specs, role headers, and token stream representations are embedded in the curriculum.

Compared Candidate Sources & Selection Analysis (2)
Anthropic Claude Prompt Engineering Guidelines ↗ compared_alternative [Proprietary Documentation]

Uses Human:/Assistant: plain text delimiters; ChatML provides formal token-level demarcation with dedicated boundary tokens.

Vicuna ShareGPT Multi-Turn Schema ↗ compared_alternative [Apache 2.0]

FastChat conversation template; ChatML is the universal token-delimited primitive.

linking Apache 2.0

Hugging Face Transformers: Templates for Chat Models

Author: Hugging Face Documentation Team | Original Source Link ↗

Relevant Section / Range: Using apply_chat_template

Verified Version & Date: Hugging Face Documentation (Verified: 2026-10-30)

Selection Rationale:

Widely adopted system for mapping list-of-dict messages into tokenized strings with tokenizer.apply_chat_template().

Source Prerequisites:

Python, Jinja2 template basics, Hugging Face PreTrainedTokenizer.

Safe Fallback (Offline Resilience):

Complete Jinja2 template implementations and boundary token unit tests are self-contained.

Compared Candidate Sources & Selection Analysis (2)
Axolotl Prompt Formats Guide ↗ compared_alternative [Apache 2.0]

Configuration-driven formatting framework; Hugging Face chat templates are the direct tokenizer-level standard.

vLLM Online Serving: Chat Template ↗ compared_alternative [Apache 2.0]

High-performance inference chat templating; HF chat templating is the training-time reference implementation.

04 120 min

Independent Assessment: Production ChatML Normalization and Token Boundary Validator

Independent Mastery Assessment

Prerequisites

Day 61 Activities 1-3.

Learning Objective

Build a production-grade dataset validation and formatting pipeline that normalizes heterogeneous raw records, verifies special token delimiters, and detects schema corruption.

Instructions

1. Create a Python module ChatMLDatasetValidator.
2. Accept a mixed JSON/JSONL dataset containing Alpaca, ShareGPT, and raw ChatML formats.
3. Validate that every record contains valid role sequences (system prompt if present must be first, alternating user/assistant turns, non-empty content).
4. Apply ChatML tokenization and assert that delimiters occupy exactly single token IDs.
5. Output an audit summary reporting valid samples, malformed records filtered out, and token length distribution statistics.

Practice & Prediction Log

Run ChatMLDatasetValidator against a test batch of 10 records containing 2 malformed records (e.g. missing assistant response, consecutive user turns). Confirm that invalid records are caught and valid records are serialized correctly.

Independent Mastery Criterion

Deliver an independent validator identifying 100% of malformed dialogue schemas and formatting valid records without tokenization artifacts.

Authoritative Source Resources & Provenance

linking Apache 2.0

Stanford Alpaca: An Instruction-following LLaMA Model

Author: Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li, Carlos Guestrin, Percy Liang, Tatsunori B. Hashimoto | Original Source Link ↗

Relevant Section / Range: README 'Data Release'

Verified Version & Date: Stanford CRFM Release (Verified: 2026-10-30)

Selection Rationale:

Pioneering instruction fine-tuning dataset schema establishing the instruction/input/output format widely used across open source LLMs.

Source Prerequisites:

LLM fine-tuning concepts, Python dictionary data structures.

Safe Fallback (Offline Resilience):

Standard Alpaca schemas and data transformation scripts are completely specified in lesson materials.

Compared Candidate Sources & Selection Analysis (2)

Pioneered academic instruction tuning across NLP benchmarks; Alpaca format provides the standardized single-turn JSON schema for consumer fine-tuning.

Databricks Dolly 15k Dataset ↗ compared_alternative [CC-BY-SA 3.0]

Commercially permissive instruction dataset; Alpaca establishes the architectural schema archetype.

linking Apache 2.0

Hugging Face Transformers: Templates for Chat Models

Author: Hugging Face Documentation Team | Original Source Link ↗

Relevant Section / Range: Model training

Verified Version & Date: Hugging Face Documentation (Verified: 2026-10-30)

Selection Rationale:

Widely adopted system for mapping list-of-dict messages into tokenized strings with tokenizer.apply_chat_template().

Source Prerequisites:

Python, Jinja2 template basics, Hugging Face PreTrainedTokenizer.

Safe Fallback (Offline Resilience):

Complete Jinja2 template implementations and boundary token unit tests are self-contained.

Compared Candidate Sources & Selection Analysis (2)
Axolotl Prompt Formats Guide ↗ compared_alternative [Apache 2.0]

Configuration-driven formatting framework; Hugging Face chat templates are the direct tokenizer-level standard.

vLLM Online Serving: Chat Template ↗ compared_alternative [Apache 2.0]

High-performance inference chat templating; HF chat templating is the training-time reference implementation.