Fix the data contract and baseline first, then compare the effect and cost of small adapter training.
Difficulty
Practical
Structure
2 core units · 10 chapters
CORE UNIT 1 / 2
Create JSONL training data
Fix the behavior to train and its error costs first, then verify sources, rights, personal data, schema, chat template, duplicates, and group splits to approve a reproducible SFT dataset.
Difficulty
Lab
Structure
Lessons 5 · Labs 2 · Assessment
Diagrams and tables: composed by the author using each lesson's official primary sources. Find the originals and review dates at the end of that lesson.
NEW HIRE ONBOARDING
Start in the order you would receive your first assignment
So that even a new hire with no prior IT background can follow along, we start with the situation, the task, the evidence, and when to report, before difficult definitions.
01
Read the situation in one sentence
When classifying customer inquiries into category, urgency, and reason JSON, design ordinary cases as well as conflicting categories, missing order numbers, and reference answers that put the case on hold as unverified.
02
Today's assignment
Fix the behavior to train and its error costs first, then verify sources, rights, personal data, schema, chat template, duplicates, and group splits to approve a reproducible SFT dataset.
03
Evidence that shows the work is complete
A split seed alone cannot prevent leakage within the same source family.
04
When to stop and ask a senior colleague
Set target proportions and passing thresholds for normal, boundary, refusal and insufficient-input cases before seeing results.
Unpack unfamiliar terms first
Data contract
Contract that pins the training goal, row schema, sources, rights, label rubric, validation, splits, and approval conditions as a version
JSONL
A record-oriented format that stores each line of UTF-8 text as an independent valid JSON value
Data leakage
A phenomenon in which the same source, answer, or strongly related information ends up in both the training and evaluation splits, inflating generalization scores
PREREQUISITE CHECK
Three things to check before reading
This is not a test of memorized answers. Think about each question first, then open the explanation to review the foundational concepts used in this course.
1If a JSONL file parses, is it automatically a good SFT dataset?
No. Parsing checks UTF-8, one JSON value per line and some syntax only. Separately validate task schema, chat template, source rights, privacy, label accuracy, duplicates, split leakage and independent evaluation.
2Can all public web text and internal support records be used for training?
No. Public access differs from the rights to train models on, modify, or redistribute content, and internal data must also be reviewed against its original collection purpose, consent, access, retention, and personal information in light of how it will actually be used.
3Does fixing the random seed eliminate data leakage between train and test?
It does not go away. A seed only helps reproduce the same split. Group original texts, summaries, and paraphrases from the same customer, document, or incident, and verify zero source and near-duplicate overlap.
TEXTBOOK GUIDE
Main text that covers each concept from its background to the criteria for judging it
We explain the material section by section so readers new to IT can connect causes and effects without memorizing terms.
CONCEPT FLOW
How the chapters connect
The chapters are not isolated short answers to memorize. Follow them from left to right to see how each chapter's concepts support the next decision.
1.Define the behavior to learn and the cost of failure before collecting rows→
2.Build lineage that tracks sources, rights, and personal information and supports deletion→
3.Verify the JSONL row schema and each model's chat template→
4.Connect label rubrics, duplicates, and coverage to automated checks and human review→
5.Promote datasets using group splits, manifests, regression checks and deletion rollback
Create JSONL training data: the overall map. If you lose track while reading the detailed explanations and chapters below, return to this sequence.
CONTROLLED EXPLANATION
Explore the order in which concepts build on each other
It does not start automatically. Play, or select the previous or next step, to see how the current concept connects to the next decision, step by step.
Current explanation · 1/5
Define the behavior to learn and the cost of failure before collecting rows
An SFT dataset is a reviewed set of examples showing which output behaviors the model should repeat for which inputs, rather than a document warehouse. Define the task outcomes, rubric, and abstention behavior first.
Distinguish storing current facts, providing retrieved evidence, and learning format and behavior.
Up next: Build lineage that tracks sources, rights, and personal information and supports deletion, where this standard continues to apply.
See the full step description
1. Define the behavior to learn and the cost of failure before collecting rows
An SFT dataset is a reviewed set of examples showing which output behaviors the model should repeat for which inputs, rather than a document warehouse. Define the task outcomes, rubric, and abstention behavior first. Distinguish storing current facts, providing retrieved evidence, and learning format and behavior.
2. Build lineage that tracks sources, rights, and personal information and supports deletion
Link each row to a source record and review decision that show where it came from, for which purposes it may be used for training·evaluation·redistribution, and whose personal data·secrets it contains. Public access is not the same as permission to train on, modify, or redistribute.
3. Verify the JSONL row schema and each model's chat template
Separate JSONL file rules from the SFT task schema, and check which token sequence and loss targets the exact tokenizer and chat template turn each role and content into. Keep to UTF-8 and one JSON value per line, but do not judge a row to be good training data just because it is valid JSON.
4. Connect label rubrics, duplicates, and coverage to automated checks and human review
After parsing succeeds, verify reference-answer meaning·consistency, label distributions·lengths, exact·near duplicates, and source contamination using automated reports and blind human review. Do not hide label disagreements with an arbitrary majority vote; classify them as rubric or boundary problems.
5. Promote datasets using group splits, manifests, regression checks and deletion rollback
Before row-random splitting, define duplicate clusters·customer·document·event·time groups to prevent leakage, then test frozen sets, versioned manifests, and recovery of affected artifacts. A split seed alone cannot prevent leakage within the same source family.
The text description below shows the same content without the animation. Your operating system's reduced-motion setting is also respected.Conceptual explanation 01
Define a dataset as a training behavior contract, not a collection of documents
A Supervised Fine-Tuning (SFT) dataset is not a repository for large amounts of text. Each row is a training signal demonstrating expected output behavior for a specific input. Converting an entire company-policy PDF into rows does not create a system that reliably answers using current evidence. RAG may be appropriate for frequently changing facts and source citations, while SFT is a candidate for adjusting repeated behaviors such as categories, JSON schemas, tone, and refusal rules.
Write training goals as observable acceptance criteria: categories within an approved enum, required urgency and reason fields, a hold when order IDs are missing, and no final refund approval. First run the base model on 100 production-like normal, boundary and failure cases, recording accuracy, format, critical recall and human corrections as the baseline. Without a baseline, you cannot distinguish training improvements from lost original capabilities.
An error taxonomy distinguishes wrong labels, omissions, unsupported additions, PII reproduction, unsafe compliance, format and language errors, and excessive refusal. High-harm classes such as money, permissions, and safety get independent gates that average scores cannot offset. When evidence is missing or labels conflict, provide examples of terminal behavior such as insufficient or escalate instead of an answer that plausibly picks one.
Build a Data-plan matrix covering normal, boundary, insufficient-information, refusal, and actual channel/language/length conditions. Set row targets from each cell's frequency, harm, and current failures, not a fixed number such as 100,000 rows. Start with a small pilot reviewers can read completely to check loading, templates, tokens, loss, training, and evaluation; add cases with new causes according to remaining failures.
Why does this happen?
Because the behavior to train and its failure costs must be defined first before sources, schema, labels, required coverage, and the evaluation set can be designed against a single standard.
When is it a problem?
If you scrape data first, rows of irrelevant text and unclear rights accumulate, and even if train loss falls, actual task errors cannot be explained.
Common beginner misconceptions
Adding many recent documents to SFT does not automatically replace versioned RAG and source citations, nor does it guarantee new general capabilities.
How to verify it yourself
Record the base model’s fixed normal, boundary, and failure set and critical gates, and link each planned row to the matrix cell or failure it strengthens.
Conceptual explanation 02
Approve source provenance and usage rights before rows
Being published on the web or shared by a colleague does not by itself grant rights to train on or redistribute material. Check the exact license and terms for commercial use, derivative works, redistribution and attribution, and prohibited uses. For internal material originally collected for other purposes, such as support conversations, email, and meetings, review individual and organizational expectations, contracts and policies, and consent. Do not put material that needs a judgment call into training on the assumption that it is probably allowed; quarantine it in rights_pending status.
The source registry holds the source ID, owner, collected date and revision, acquisition method, rights basis and allowed purpose, and reviewer and expiry. Rather than exposing full source paths, each dataset row links a limited source reference and a transform version. A hash helps identify the same file, but it does not prove legal permission or content accuracy. When sources and rows have a many-to-many relationship, make it explicit in a lineage table.
Distinguish human-written, crowdsourced, machine-generated, translated, and augmented rows. For synthetic outputs, record the generating model, prompt, and sampling settings, and whether a person has checked them against the source. Do not create a gold label merely because another model scored a model-generated answer as natural. Summaries, translations, and paraphrases made from the same source are not independent sources even if worded differently, so they share a duplicate cluster and split group.
A Dataset Card conveys purpose, sources, composition, license, language, size, collection, annotation, PII, bias, limitations, and intended/out-of-scope use. Hugging Face describes cards as context and license metadata for responsible use. A license tag does not replace source-specific rights review. Record rights-change triggers, review owners, and plans for affected releases and adapters.
Why does this happen?
Because a Dataset transforms and combines source material, track each source's allowed purposes and affected derived rows and artifacts to handle withdrawal and errors in practice.
When is it a problem?
Recording only the URL and license tag leaves the exact revision, internal consent, and training and distribution terms unknown, and makes adapters subject to deletion impossible to find.
Common beginner misconceptions
Open access, open-weight models, dataset card metadata, and existing hashes are not automatic approval of rights to train, use commercially, or redistribute.
How to verify it yourself
From a random row, trace back the exact source, rights decision, transform, split, dataset, and training artifact, and run a withdrawal simulation for one source.
Conceptual explanation 03
Handle personal information·secrets through automated detection, human review, and deletion lineage
Collect only necessary data first. Affiliations, dates and rare-event combinations can identify people even without names, and combining conversation turns can reveal masked values. Inventory emails, phone numbers, addresses, accounts, financial and health data, employee/customer IDs, and API keys, tokens and private URLs in code. Exclude fields unnecessary for the purpose before the redaction stage.
Microsoft Presidio can find PII candidates with rules·regular expressions·NER·checksums and custom recognizers, but its official guidance warns that automated detection cannot guarantee finding all sensitive information. Build fixtures by language·country and internal ID format, and combine secret scanners with entropy·known-prefix rules. For classes with many false negatives, have people compare high-risk·random samples against the originals.
Record redaction results in a restricted ledger with original spans, replacement types·rule versions, and reviewer decisions. Control mapping access and retention even when consistent pseudonyms are needed to preserve conversation meaning. Review both over-redaction that removes task signals and under-redaction that allows re-identification. Keep learner-visible JSONL and original-review storage behind different permission boundaries.
The deletion workflow uses source IDs to find rows and duplicate clusters, train/validation/test files, caches and snapshots, and adapters and merged models. Fully removing an individual row's influence from every artifact may require retraining, so the owner decides on risk, cost, and service actions. Run a sample deletion request, check query results and remaining copies, and roll back to the previously approved dataset or model. The NIST Privacy Framework serves as a reference for managing such data-processing privacy risks at the organizational level.
Why does this happen?
Because sensitive-data detection is probabilistic and context-dependent, and a dataset spawns many copies, caches, and artifacts, minimal collection and a deletion path are both required.
When is it a problem?
Marking data safe after a single regular-expression check can miss Korean names, contextual secrets, new secret formats and derived artifacts.
Common beginner misconceptions
Local training, asterisk redaction, or passing a PII scanner does not automatically resolve consent, access, retention, or re-identification risk.
How to verify it yourself
Inspect known fixtures and blind samples for each language, PII type, and secret type, and use a lineage query to check how deleting one source affects every row, split, cache, and artifact.
Conceptual explanation 04
Check JSONL file rules separately from the training row schema
The official JSON Lines (JSONL, one JSON value per line) description sets three basic requirements: UTF-8 encoding, a valid JSON value on each line, and a line terminator. Do not include a Byte Order Mark (BOM); a blank line is not a valid value. Store newlines inside strings as JSON escapes, not as actual record separators. A trailing newline is recommended so files can be safely concatenated.
Hugging Face Datasets documentation presents one JSON object per line as an efficient JSON representation. Successfully reading a file does not establish that its SFT schema is correct. The parser reports line numbers, byte/character positions and exceptions, and must not treat partial loading as silent success. Also check for encoding replacement characters and field-type inference changing between rows.
Version the schema for each task. For conversational SFT, define the messages array, each message’s role and content, allowed roles and turn order, at least one assistant target, and prohibition of empty content. For prompt-completion data, distinguish prompt and completion types and required values. Metadata may need source_ref, rights_state, language, labels, review status, and group IDs, but separate training-input fields from governance-ledger fields.
The schema validator checks additional fields, loader behavior that coerces nulls and numbers to strings, and nested content. Whether an answer within a valid structure matches its source, whether label priorities are correct, and whether PII is present require separate checks. Create golden sets of valid and invalid rows, and regression-test that expected error codes remain stable when changing parser or schema versions. Link the raw-file hash and validator report to the release manifest.
Why does this happen?
Because JSONL syntax, the columns and roles the trainer expects, and the correct task answer are different failure layers, and only separating them allows accurate recovery.
When is it a problem?
Checking only JSON.parse success lets training failures pass, including missing assistant targets, reversed roles, empty answers and unclear rights.
Common beginner misconceptions
A .jsonl extension or a successful read by the Hugging Face loader does not certify the SFT dataset, chat schema, or quality.
How to verify it yourself
Run BOM, blank, and broken JSON lines, wrong types and roles, empty targets, and valid fixtures line by line, and check the errors from the loader, schema, and task validator separately.
Conceptual explanation 05
Render the conversational format with the exact chat template and loss mask
TRL's official dataset format documentation distinguishes standard and conversational formats, as well as columns for each task type, such as language modeling, prompt-only, prompt-completion, and preference. Even with the same messages JSON, the trainer may apply loss to the full sequence, to completions only, or to assistant turns only. Check the supported formats and defaults for the exact TRL and Transformers versions and SFT configuration, and do not infer the training target from the dataset schema alone.
As Hugging Face chat-template documentation explains, a role/content list becomes one token sequence including control tokens. Models fine-tuned from the same base may use different role markers, and incorrect tokens can significantly harm performance. Save the exact tokenizer revision's apply_chat_template output and inspect system/user/assistant boundaries and end markers. Compare training data with serving prompts to verify they use the same contract.
Check for duplicate special tokens. If the template already inserts BOS and EOS and the tokenizer adds them again, the sequence may change. Verify that the model supports assistant start and end markers, tool turns, and system placement in multi-turn rows. Overlay the loss mask on tokens to see whether user and system content is being learned as target answers, and compare the configuration against the intended target: only the final assistant response or all assistant responses.
Build rendered-token length distributions and truncation reports. Rows whose final answer is cut by long system messages or history, or whose assistant response mostly exceeds max length, are not valid training signals merely because parsing succeeds. Similar character counts can produce different tokens by language·template. Regression-test text·token-ID·mask hashes on representative·long·multi-turn·empty/unsupported-role golden rows, re-evaluating dataset candidates after changes.
Why does this happen?
A causal model learns token sequences rather than JSON objects, and the loss mask determines which positions are actually updated.
When is it a problem?
Matching only the shape of messages still leaves other models' markers, duplicate special tokens, and truncated assistant targets, so the model fails to learn the expected behavior.
Common beginner misconceptions
Even if role names are the same (user and assistant), not every model and trainer uses the same template, special tokens, and loss scope.
How to verify it yourself
Render golden rows with the exact tokenizer/template and trainer configuration. Inspect tokens, masks and truncation, then compare them with the first user-request sequence at inference.
Conceptual explanation 06
Build semantic ground truth with an annotation rubric and independent review
An annotation guide does more than list labels. Define each class, inclusion and exclusion criteria, precedence when multiple classes fit, insufficient or conflicting sources, and out-of-scope behavior. Provide positive, negative, and borderline examples with different numbers and situations. For free-text answers, separate required facts, prohibited additions, tone, format, and refusal conditions in a rubric so reviewers can identify sentences needing correction.
Annotators need permission to view sources and sufficient context, as well as domain knowledge. Blind-review items that do not require identity to reduce personal bias, and do not present model-generated answers as authoritative references. Have at least two people independently review some overlapping samples to assess agreement and class-level confusion. Minimize personal information in disagreement notes and apply access and retention controls.
Do not settle disagreements by majority vote by default. Classify whether the source is ambiguous, rubric boundaries overlap, or the training goal itself allows multiple behaviors. The adjudicator records the final label, a reason code, and the guide change version. When the guide changes, re-review the same ambiguous samples and affected rows that were already approved. Which critical class split the reviewers and why matters more than a single agreement number.
The review workflow defines drafted, reviewed, approved, rejected, and quarantined states and keeps authors separate from reviewers. Aggregate the edit rate, reject and escalate counts, and the defect taxonomy by source and authoring method. If a particular synthetic prompt or provider shows a high error rate, do not just delete the rows; quarantine the entire batch. Every final gold row must be traceable back to its source, rubric version, and approval.
Why does this happen?
SFT learns repeated label patterns, so ambiguous or conflicting answers contaminate both model behavior and evaluation criteria.
When is it a problem?
If one person writes quickly and only checks parsing, conflicting policies for the same input and fluent but unsupported answers can enter the gold set.
Common beginner misconceptions
High reviewer agreement or approval by a model judge does not automatically settle source accuracy and rights, or replace independent human review of new situations.
How to verify it yourself
Inspect class-level disagreement and edit reasons in blind overlap samples. Repeat independent review on the same ambiguity set both before and after guide changes.
Conceptual explanation 07
Assess exact and near duplicates and coverage by source cluster
Find exact duplicates using raw-byte hashes and input/target hashes normalized for Unicode, whitespace, case, and punctuation. Separately inspect identical prompts with conflicting answers and identical answers attached to template-boilerplate questions. Sample whether dedup normalization erases meaningful code, ID, or numeric differences. Preserve duplicate-removal decisions and representative row IDs.
Near duplicates include reordered sentences and document chunks derived through translation·summarization·paraphrasing. Embedding similarity helps find candidates; it does not establish semantic identity. Prefer source-family·customer-event and generation-parent IDs as cluster keys, and have people review boundary pairs. Numerous synthetic rows do not count as independent coverage if they merely rephrase the same prompt·source.
Assess coverage by task matrix, not total row count. Show approved row and group counts by label; normal, edge, hold, and refusal cases; language, length, and channel; source type and time; and privacy/security risk. Copying the same row several times because a critical class is small increases its weight but adds no new situations. Collect sources with different causes from real failures, or manage class-balanced sampling transparently in the training config.
After automated reports, people read random, high-risk, longest/shortest and duplicate-boundary samples, plus samples by source and authorship method. If label distributions differ from production, distinguish intentional oversampling from distortion. Compare before/after matrices for filters that excessively remove particular dialects, languages or short refusals. Include candidate-versus-previous row, group and coverage differences in approval evidence.
Why does this happen?
Duplicates can overtrain particular patterns and create evaluations with overlapping sources; total row counts do not show real situational diversity.
When is it a problem?
Removing only exact strings leaves paraphrases, chunks, and synthetic families in both train and test, and rare classes are filled only with duplicated rows.
Common beginner misconceptions
High Embedding similarity does not always imply duplication, and many rows with balanced labels do not prove sufficient production coverage.
How to verify it yourself
Build clusters with normalized hashes·source parents·semantic candidates, then check unique groups·review passes per matrix cell and the before/after effects of removal.
Conceptual explanation 08
Block leakage with group and time splits and a frozen test
Hugging Face Datasets' train_test_split is a convenient way to split rows by size and shuffle setting. However, if the original text, summary, and paraphrase of the same ticket are separate rows, a random shuffle can send them to both train and test. When the model reproduces the meaning of answers it saw in training, scores exceed true generalization. Deciding what counts as one group comes before choosing a split function.
Scikit-learn GroupShuffleSplit provides a way to split indices by arbitrary domain groups. For support conversations, a customer or ticket thread can be the group; for documents, a revision family; for code, a repository or issue; and for speech, a speaker or recording session. Place all rows of a group in a single split. If a row has multiple sources, consider a conservative boundary that groups them by the largest connected component.
When change over time matters, use a time split: past data for training, the next period for validation, and the latest period as a frozen test. Use validation to choose schemas, data, hyperparameters, and checkpoints, and reserve the test set for comparing final candidates. The moment you add rows or change a prompt or threshold after seeing test failures, that test becomes development evidence. A new release needs a blind set that has never been accessed or the next time window.
After splitting, check exact and near duplicates and source and group overlap in both directions; put the release on hold if any count is nonzero. Check critical labels, languages, lengths, risk coverage, and group counts in every split. If group separation leaves a rare class out of the test set, expand collection periods or sources rather than copying training rows into the test set. Record the seed, algorithm version, group rules and mapping, split-file hashes, and test-access log in the manifest.
Why does this happen?
Rows with different wording can share answers from the same source or event, so row-level random splits can easily undermine independent generalization evaluation.
When is it a problem?
If you record only an 80:10:10 ratio and a seed, the same customer·document family may be scattered across all three splits, inflating the test score.
Common beginner misconceptions
Using a group splitter does not by itself guarantee a correct group definition, time boundaries, 0 near duplicates, or frozen test discipline.
How to verify it yourself
Calculate intersections of source, group, and duplicate IDs across train, validation, and test splits. Trace back selected groups to verify that all derived rows remain in only one split.
Conceptual explanation 09
Promote with a manifest·dataset card, regression checks, and deletion rollback
The release manifest holds the source snapshot·rights state, raw/clean row·group·split hashes, schema·conversion code, PII·secret scans, annotation guide·review report, tokenizer/chat template, rendered token·mask statistics, split algorithm·seed, and Dataset Card. Pin an immutable dataset version, not a mutable latest path, in the training config. When any item changes, rerun the affected downstream evaluations.
Judge each gate independently: 100% line parsing and schema compliance, zero unsupported roles and target truncation, critical-label thresholds, zero rights_pending or unreviewed PII, and zero source/group/duplicate overlap across splits. Also examine coverage, reviewer edits and agreement, frozen task metrics and safety versus the base, and regressions in original capabilities. Low training loss or high average accuracy does not offset privacy, rights, or critical-class failures. Do not lower thresholds after seeing results.
Use a small training run to verify loading, loss mask and memory, and the checkpoint and evaluation pipeline, and compare against the previous dataset with the exact base and config. Do not change model, data, and training variables at the same time. Collect actual corrections and new failures from a limited canary, but do not feed production input straight back into training rows without consent and review. Trace each failure to its root layer: source, schema, label, split, or training.
Rollback does not merely replace a JSONL file. Restore the previous dataset manifest, conversion·template, training config·adapter, and serving artifacts as a compatible bundle. Use lineage to find affected rows·caches·splits·artifacts in rights-revocation or PII-discovery samples, and test deletion·retraining or service-suspension decisions. Record owners, limitations, source·policy·model changes, and defect triggers. Close release only after retesting the same frozen·failure sets.
Why does this happen?
Because dataset changes alter token sequences, training results, and even privacy and rights, every input, code, review, and artifact must be managed as a reproducible, recoverable release.
When is it a problem?
Keeping only the final .jsonl filename and training loss leaves you unable to identify the model’s sources, template and split or determine what to roll back after errors or deletion.
Common beginner misconceptions
Passing every automated check and frozen score does not replace actual rights approval or beginner review, and a dataset card is not a legal certificate.
How to verify it yourself
Repeat clean regeneration and small training runs from the candidate manifest, and restore the previous compatible release and a source-deletion incident with the same hashes and failure set.
CONCRETE CASES
Check concepts in different situations
Before memorizing definitions, compare how these concepts appear on a personal PC and in real work.
Case 1 · Define the behavior to learn and the cost of failure before collecting rows
When classifying customer inquiries into category, urgency, and reason JSON, design ordinary cases as well as conflicting categories, missing order numbers, and reference answers that put the case on hold as unverified.
Key points to check here: Distinguish storing current facts, providing retrieved evidence, and learning format and behavior.
Case 2 · Build lineage that tracks sources, rights, and personal information and supports deletion
Each support ticket row keeps a restricted hash of the original record ID, the consent or license basis, PII scan and human review, the redaction version, and lineage for finding derived splits and artifacts when deletion is requested.
Key points to check here: Public access is not the same as permission to train on, modify, or redistribute.
Case 3 · Verify the JSONL row schema and each model's chat template
After parsing a messages row, check the system→user→assistant role·content and metadata schema, then compare control-token duplication·assistant loss mask·truncation in the exact tokenizer's apply_chat_template output against a golden fixture.
Key points to check here: Keep to UTF-8 and one JSON value per line, but do not judge a row to be good training data just because it is valid JSON.
Case 4 · Connect label rubrics, duplicates, and coverage to automated checks and human review
From 100 items labeled independently by two reviewers, identify category conflicts and missing reasons and adjudicate them, then cluster variants of the same ticket using normalized input and output hashes and embedding similarity, and manage each cluster as one representative group.
Key points to check here: Do not hide label disagreements with an arbitrary majority vote; classify them as rubric or boundary problems.
Case 5 · Promote datasets using group splits, manifests, regression checks and deletion rollback
Group the original·summary·translation·paraphrase of the same customer ticket together, split them into train from past months, validation from the next month, and a frozen test from the latest month, and check for a group overlap of 0 and critical class coverage.
Key points to check here: A split seed alone cannot prevent leakage within the same source family.
CHAPTER 1 / 5
Define the behavior to learn and the cost of failure before collecting rows
“Let's train the model on our documents” is not enough to design a dataset. Determine whether you want up-to-date answers about rules that change monthly, a fixed JSON format, or a particular tone·refusal behavior. Retrieval-Augmented Generation(RAG) may be a better fit for current facts and source citations, while Supervised Fine-Tuning(SFT, fine-tuning based on example answers) is a candidate for adjusting recurring formats, decision boundaries, and response style. Do not assume that row count alone can create a capability the base model lacks.
Express learning outcomes as observable outputs. Replace “respond kindly” with conditions parsers and reviewers can judge: approved category enums, required reasons, holding when evidence is insufficient and refusing personal-data requests. Measure the current base model on 100 production inputs for accuracy, format, refusal and human corrections. Before data collection, the owner approves which critical error classes must not be hidden by averages and the boundary between automatic handling and the human queue.
The Data matrix must include more than normal cases: short/long inputs, typos, mixed languages, missing required values, label conflicts, out-of-scope inputs, safety refusals, and adversarial wording. Set cell targets by real frequency and harm. Collect cases with different causes rather than changing only numbers in repeated sentences. Give rare critical classes separate recall gates that overall accuracy cannot offset.
The collection plan links each source to its owner, authoring and review method, permitted purpose, and retention. Model-generated synthetic rows are labeled with the generating model and prompt and with their human review, and are not mistaken for a representation of the real distribution. The pilot first tests the schema→template→tokenization→small training→task evaluation path at a scale people can read in full, such as 50 to 200 examples. Once the pipeline works, expand based on the observed failure types.
How to read the figure A dataset is a versioned release that chains goal, source, rights, label, schema, split and evaluation, not a single text file. The row count is what survives this contract, not the starting point.
To recap the key points
Distinguish storing current facts, providing retrieved evidence, and learning format and behavior.
Set target proportions and passing thresholds for normal, boundary, refusal and insufficient-input cases before seeing results.
How this connects in practice
When classifying customer inquiries into category, urgency, and reason JSON, design ordinary cases as well as conflicting categories, missing order numbers, and reference answers that put the case on hold as unverified.
CHAPTER 2 / 5
Build lineage that tracks sources, rights, and personal information and supports deletion
Being readable on the internet does not automatically grant permission for model training or redistribution of results. Check the source owner and author, exact license and terms, collection method, and conditions for commercial use, derivatives, and redistribution against the actual plan. For internal data, also confirm the original collection purpose, consent, and access policies between employees, customers, and the organization. When a legal judgment is needed, do not mark data as usable before the responsible review; keep it in quarantine.
Rather than putting only a URL that copies the full source text into each row, link the source record, collection date and revision, rights basis, allowed purpose, owner, and review status through a separate ledger. If a source is withdrawn or expires, or an error is found, you must be able to trace which rows, splits, dataset versions, and adapters are affected. Preserve the original hash, conversion code, and redaction decisions, but do not expose unnecessary identifying metadata in the learner-facing JSONL.
Minimize email, phone, addresses, account IDs, health and financial content, API keys, passwords, and tokens from collection onward. Tools such as Presidio use patterns, NER, and checksums to identify PII candidates, but do not guarantee finding all sensitive information. Supplement Korean names, internal identifiers, contextual secrets, and long secrets with custom rules, entropy, allowlists/denylists, and human review of risky samples. No detection is not proof of safety.
Redaction is not a one-time task of masking source text with asterisks. Look at quasi-identifier combinations that could point to the same person, repeated names within a conversation, and attachment metadata. Keep originals separate under least privilege·encryption·short retention and audit, and leave only the information needed for the purpose in training rows. Actually test a deletion workflow that, on a deletion request or rights change, traces and removes source→row→split→artifact and records the retraining·redeployment decision.
To recap the key points
Public access is not the same as permission to train on, modify, or redistribute.
Automated PII and secret scans do not replace human review or access, retention, and deletion controls.
How this connects in practice
Each support ticket row keeps a restricted hash of the original record ID, the consent or license basis, PII scan and human review, the redaction version, and lineage for finding derived splits and artifacts when deletion is requested.
CHAPTER 3 / 5
Verify the JSONL row schema and each model's chat template
The JSON Lines (JSONL, one JSON value per line) documentation describes UTF-8, a valid JSON value per line, and a line terminator as the basic requirements. Blank lines are not valid values, and actual newlines inside strings must be written as JSON escapes. Hugging Face Datasets also describes one JSON object per line, each a separate row, as an efficient JSON format. The parser returns the line number, byte position, and error reason, and does not silently discard the rest of the file because of one damaged line.
File format and training schema are different. TRL's official format guide shows that columns vary by task: text/messages for language modeling, prompt-only, prompt-completion and preference. If SFT aims to train assistant responses, check the trainer settings to determine whether loss applies to all messages or only completion/assistant turns. Specify required fields and types, allowed roles and ordering, empty content, unknown keys and metadata versions in the schema.
A chat row does not enter the model unchanged as an object array. As Hugging Face's chat-template documentation explains, roles and content become model-specific control-token sequences, and incorrect tokens can badly harm performance. Apply the exact base-model/tokenizer revision's template and inspect rendered text, token IDs, duplicate BOS/EOS tokens, and assistant start/end markers. Different training and inference templates can break deployed behavior even when row content is correct.
Measure length in rendered tokens, not characters or file bytes. Show whether truncation cuts the system instruction, the user question, or the assistant's correct answer, and hold rows in which a required answer is cut. Visualize the mask to show whether only the last assistant turn in a conversation is trained or every assistant turn is. Pin the exact JSONL bytes, schema and conversion code, tokenizer/template revision, and token statistics in the dataset manifest.
To recap the key points
Keep to UTF-8 and one JSON value per line, but do not judge a row to be good training data just because it is valid JSON.
Match the standard or conversational and language modeling or prompt-completion formats to the trainer version and loss settings.
How this connects in practice
After parsing a messages row, check the system→user→assistant role·content and metadata schema, then compare control-token duplication·assistant loss mask·truncation in the exact tokenizer's apply_chat_template output against a golden fixture.
CHAPTER 4 / 5
Connect label rubrics, duplicates, and coverage to automated checks and human review
Even answers that pass the schema can be wrong. In the annotation guide, document label definitions, inclusion and exclusion criteria, priorities, insufficient and conflict cases, and examples and counterexamples. Reviewers inspect source and target, choose correct, edit, reject, or escalate, and record a reason code. Independently label some overlapping samples to measure disagreement. If agreement is low, fix ambiguous tasks and rubrics and insufficient sources before blaming people.
Automated checks cover parsing/schema, roles/turns, empty values, rendered-token minima/maxima and truncation, label/language/source distributions, prohibited content, PII and secrets. Check critical outputs for enums, calculations, evidence and refusal rules as well as JSON schemas. Set thresholds before viewing reports, and aggregate failures by source, authorship, conversion and review stage rather than merely deleting failed rows.
Duplicates are not limited to identical text. Compare hashes after normalizing Unicode, whitespace, case and punctuation, and compare prompts and answers separately. Cluster near duplicates, template boilerplate, translations and synthetic paraphrases. Chunks derived from the same source document or customer event remain strongly related even if their sentences differ. Duplicate weighting can overtrain particular labels or tones and cause train/test leakage, so preserve cluster IDs in the manifest.
A Coverage report shows task-matrix cells, not merely total rows. Compare counts and review-pass results for normal, boundary, refusal, attack, language, length, channel, critical class, and source group. Simply oversampling rare classes may teach memorization, so review and add examples with new causes. Humans should read random, high-risk/high-loss, and automatically flagged samples, retaining edit rate and defect taxonomy as release evidence.
To recap the key points
Do not hide label disagreements with an arbitrary majority vote; classify them as rubric or boundary problems.
Do not count synthetic, translated, or paraphrased rows that repeat the same source meaning as independent diversity.
How this connects in practice
From 100 items labeled independently by two reviewers, identify category conflicts and missing reasons and adjudicate them, then cluster variants of the same ticket using normalized input and output hashes and embedding similarity, and manage each cluster as one representative group.
CHAPTER 5 / 5
Promote datasets using group splits, manifests, regression checks and deletion rollback
Hugging Face Datasets' train_test_split creates splits from a specified ratio and shuffles by default. However, a row-level shuffle can send near duplicates from the same customer, document, or case to both sides. Providing domain groups as a separate value, as with scikit-learn's GroupShuffleSplit, allows splitting by group. Using this feature does not by itself make the group IDs correct, so define the leakage unit based on the task.
For customer support, the group can be the customer or ticket thread; for documents, the document revision family; for code, the repository or issue; and for change over time, the month or release. To evaluate future behavior, a time split may be more realistic than a random split. Use train for training, validation for choosing settings and checkpoints, and the frozen test only for final comparison. If you revise rows, prompts, or hyperparameters after looking at the test, it has already become a development set, so you need a new blind test.
After splitting, recalculate exact and near duplicates and source/group overlap. Check label, language, length, and critical-class coverage in every split. If group separation removes a rare class, adjust the collection period or collection process rather than secretly copying rows. In the Dataset Card, record purpose, composition, sources, licenses, languages, size, collection, annotation, PII, bias, limitations, and intended and out-of-scope uses. Card metadata does not replace the rights review itself.
Pin source snapshots, row·group IDs and split hashes, schema·conversion, tokenizer/template, scan·review reports, seeds, and dataset cards in the release manifest. Candidates must independently pass parse·template, critical-label, rights·privacy, zero duplicate/leakage, and frozen-evaluation gates. If problems arise after canary training and base comparison, roll back to the previous dataset·adapter and use the same lineage query to verify deleted rows are absent from cache·splits·artifacts.
How to read the figure The unit of leakage comes before the split ratio. Group each source family into a single group, confirm that exact and near duplicates and group overlap across train, validation, and frozen test are 0, and if any gate fails, the dataset remains a candidate.
To recap the key points
A split seed alone cannot prevent leakage within the same source family.
A dataset candidate is promoted only after passing all quality, privacy, rights, coverage, and leakage gates.
How this connects in practice
Group the original·summary·translation·paraphrase of the same customer ticket together, split them into train from past months, validation from the next month, and a frozen test from the latest month, and check for a group overlap of 0 and critical class coverage.
INTERACTIVE LAB 1 / 2
Lab 1 · JSONL row, rights, and template contract lab
Enter values in the browser and check the execution results and the failure and recovery paths. No commands are ever sent to real equipment or the NAS.
Build a row contract from the goal, source, JSONL, template, and human review
Judge whether each row connects actual training behavior with rights, privacy, and rendered tokens, rather than merely being valid JSON on one line. The defaults intentionally fail.
Situation
Internet and customer-support sentences were collected into a text field, but it is unclear what should be learned, what usage rights exist, and which tokens are the target.
Goal
Enter one or more conversational JSONL rows directly and pass them through the observable behavior, source, PII, template, and review contract.
Prerequisites
Prepare training rows without sensitive data, an approved label schema, a source and rights ledger, and exact tokenizer and template fixtures.
Success criteria
Specific goals, the conversational format, valid role, content, and assistant targets, and all four pieces of governance, render, and review evidence are confirmed.
Choose the behavior to train and the row format the trainer will receive.
Enter an independent JSON object on each line, and check the role, content, and final assistant target.
Run the dataset row contract Then add missing source, privacy, template and human-review checks and reassess the same rows.
Evidence limits: The browser parser checks only the input text; it does not run the actual tokenizer or trainer, rights or PII systems, or sources. A passing screen does not replace raw JSONL and rendered tokens, review logs, or deletion tests.
INTERACTIVE LAB 2 / 2
Lab 2 · Dataset quality, leakage, and recovery promotion lab
Enter values in the browser and check the execution results and the failure and recovery paths. No commands are ever sent to real equipment or the NAS.
Promote a dataset with review, privacy, coverage, group leakage checks, and rollback
Assess independent data-release gates for quality·rights·privacy·leakage·reproducibility·recovery, not row counts and train loss. Defaults intentionally fail.
Situation
The candidate has 50,000 rows, but many were rejected in review, and 3 PII cases, 4 split overlaps within the same ticket family, and insufficient critical refusal coverage remain.
Goal
Combine human approval, critical quality, zero unresolved PII and secrets, zero group overlap, matrix coverage, manifest, failure attribution, and rollback into one release gate.
Prerequisites
Prepare an immutable source snapshot and JSONL, the exact validator and template, a duplicate/group map, split and review reports, a frozen test, and the previous compatible dataset and adapter.
Success criteria
All numeric and repeat gates pass, and the identical manifest, failure root cause, and recovery of the previous release, including source deletion, are confirmed.
Before seeing results, fix the human approval, critical label, and coverage targets, and zero PII and group overlap.
Enter clean-pipeline measurements, repeat counts, and manifest, failure, and rollback evidence.
Run Dataset promotion gates Then fix the stage that caused the failure and rerun the same raw snapshot and frozen test without lowering the pass line.
Evidence limits: This judges input values without running actual datasets, scanners, tokenizers, splitters or trainers. A passing screen does not replace raw reports, row/group hashes, frozen evaluations, rights/deletion records or rollback evidence.
KEY TERMS
Key terms in this unit
Data contract
Contract that pins the training goal, row schema, sources, rights, label rubric, validation, splits, and approval conditions as a version
JSONL
A record-oriented format that stores each line of UTF-8 text as an independent valid JSON value
Data leakage
A phenomenon in which the same source, answer, or strongly related information ends up in both the training and evaluation splits, inflating generalization scores
Data lineage
Traceability links from the original source through transformation, redaction, rows, splits, and datasets to training artifacts
UNIT WORKBOOK
Exercises and worksheets for applying concepts to new situations
Start by checking basic principles, then expand to practical workplace decisions. After submitting an answer, you can see why every option is correct or incorrect, not just the correct answer.
Basic Question 1
Which statement most accurately distinguishes a JSON Lines (JSONL) file from an SFT row contract?
Basic Question 2
What is the most complete way to check conversational SFT rows before training?
Apply Question 3
A dataset was built from support tickets, and the PII scanner reported 0 findings. What is the most appropriate next action?
Free text contains Korean names, internal customer IDs and rare events, and training and redistribution permission for some sources remains unverified.
Apply Question 4
Because critical refund labels were scarce, the original, summary, translation, and paraphrase of the same ticket were each added as new rows. What is the most appropriate quality treatment?
Capstone Question 5
What is the most complete plan for promoting Dataset candidate v3 to an SFT production candidate?
Requirements are 98% review approval, 95% critical-label quality, zero unresolved PII or secrets, zero split-group overlap, 90% matrix coverage, and source deletion and recovery of the previous release.
PERSONAL WORKSHEET
A learning worksheet you adapt to your own environment
Your input remains only on the current browser screen and is not stored or transmitted externally. Use categories and pseudonyms instead of actual sensitive information.
OFFICIAL SOURCES
Verify against official sources
Technical, compatibility, and model information reviewed: August 2026
Use a base baseline to prove the behavior that requires fine-tuning. Pin the exact model, template, data, and LoRA/QLoRA settings, then approve the adapter on checkpoint quality, regression, reproducibility, and rollback.
Difficulty
Lab
Structure
Lessons 5 · Labs 2 · Assessment
Diagrams and tables: composed by the author using each lesson's official primary sources. Find the originals and review dates at the end of that lesson.
NEW HIRE ONBOARDING
Start in the order you would receive your first assignment
So that even a new hire with no prior IT background can follow along, we start with the situation, the task, the evidence, and when to report, before difficult definitions.
01
Read the situation in one sentence
For a task that outputs customer inquiries as category·urgency·reason JSON, record base format compliance of 71% and critical refund recall of 82%. Keep the latest refund policies in RAG, and make only judgment boundaries and hold behavior SFT candidates.
02
Today's assignment
Use a base baseline to prove the behavior that requires fine-tuning. Pin the exact model, template, data, and LoRA/QLoRA settings, then approve the adapter on checkpoint quality, regression, reproducibility, and rollback.
03
Evidence that shows the work is complete
Pin checkpoint selection metrics and independent required gates before seeing results.
04
When to stop and ask a senior colleague
Pin the base license, revision, tokenizer, chat template, and deployment runtime support before starting.
Unpack unfamiliar terms first
LoRA
A parameter-efficient adaptation technique that freezes pretrained base weights and trains small low-rank update matrices on selected layers
QLoRA
A fine-tuning approach that passes gradients through a frozen quantized base to LoRA adapters while reducing base weight memory with NF4 or similar formats
Target module
Name and scope of the actual architecture layers into which the LoRA adapter is injected
PREREQUISITE CHECK
Three things to check before reading
This is not a test of memorized answers. Think about each question first, then open the explanation to review the foundational concepts used in this course.
1Is fine-tuning the easiest way to make a model answer from the latest documents with sources?
No. RAG may be easier to manage for frequently changing facts and source citations. Consider fine-tuning for recurring output behavior such as format, decision boundaries, tone and refusals on fixed inputs.
2Does QLoRA's 4-bit mean that the base·adapter·gradients·optimizer and all computation are 4-bit?
No. QLoRA represents frozen base weights in 4-bit precision to reduce memory, but compute dtype, adapters, gradients, optimizer states, and activations are separate. Measure exact settings and actual peaks at each stage.
3If training loss keeps falling, is the last checkpoint the best for production?
Not guaranteed. Train and validation loss are proxies, and critical refusals, general capability, and serving performance can worsen at the last checkpoint. Compare checkpoints against the base and previous adapter with the same frozen task, safety, and regression gates.
TEXTBOOK GUIDE
Main text that covers each concept from its background to the criteria for judging it
We explain the material section by section so readers new to IT can connect causes and effects without memorizing terms.
CONCEPT FLOW
How the chapters connect
The chapters are not isolated short answers to memorize. Follow them from left to right to see how each chapter's concepts support the next decision.
1.Before training, demonstrate the behavior to fine-tune and the base-model baseline→
2.Confirm the LoRA update, target modules, and rank in the actual trainable parameters→
3.Separate QLoRA's 4-bit storage·compute·adapter precision and memory peaks→
4.Turn template, loss mask, batch, and clean runs into an observable training contract→
5.Approve the best checkpoint through task and safety regression checks against the base and previous versions, plus rollback
LoRA·QLoRA fine-tuning: the overall map. If you lose track while reading the detailed explanations and chapters below, return to this sequence.
CONTROLLED EXPLANATION
Explore the order in which concepts build on each other
It does not start automatically. Play, or select the previous or next step, to see how the current concept connects to the next decision, step by step.
Current explanation · 1/5
Before training, demonstrate the behavior to fine-tune and the base-model baseline
Fine-tuning adjusts recurring output formats, judgments and refusal behavior for given inputs; it is not a universal way to insert current facts. First demonstrate why it improves on prompt, RAG and rule baselines, and establish the cost of failures.
Compare the base and prompt/RAG candidates on the same frozen task set.
Up next: Confirm the LoRA update, target modules, and rank in the actual trainable parameters, where this standard continues to apply.
See the full step description
1. Before training, demonstrate the behavior to fine-tune and the base-model baseline
Fine-tuning adjusts recurring output formats, judgments and refusal behavior for given inputs; it is not a universal way to insert current facts. First demonstrate why it improves on prompt, RAG and rule baselines, and establish the cost of failures. Compare the base and prompt/RAG candidates on the same frozen task set.
2. Confirm the LoRA update, target modules, and rank in the actual trainable parameters
LoRA trains small low-rank update matrices alongside frozen base weights, but efficiency is not an automatic quality guarantee; verify which rank and alpha are attached to which modules and the actual trainable parameters. Record rank·alpha·dropout·bias·modules_to_save and target-module lists in configs and logs.
3. Separate QLoRA's 4-bit storage·compute·adapter precision and memory peaks
QLoRA lowers weight memory by passing gradients through a frozen 4-bit quantized base into a LoRA adapter, but activations·gradients·optimizer state·workspace remain, so model size or VRAM alone does not guarantee that it will run. Record NF4·double quant·compute dtype and adapter dtype separately.
4. Turn template, loss mask, batch, and clean runs into an observable training contract
Fix how training rows become token sequences under the exact chat template and which assistant/completion tokens receive loss. Then verify learning rate, effective batch, steps, checkpoints and resume in a clean run. Compare training and serving tokenizers, templates, and special tokens against golden fixtures.
5. Approve the best checkpoint through task and safety regression checks against the base and previous versions, plus rollback
Do not automatically adopt the last checkpoint or the one with the lowest validation loss. Compare frozen task, critical, safety, original-capability, and operational metrics against the base and the previous adapter, then approve a deployable bundle and its recovery. Pin checkpoint selection metrics and independent required gates before seeing results.
The text description below shows the same content without the animation. Your operating system's reduced-motion setting is also respected.Conceptual explanation 01
Start fine-tuning as a behavior-change decision, not a GPU task
Fine-tuning is not a small version of pretraining a model from scratch. It adjusts specific output behavior by showing reviewed input-target pairs to a base model that already has language capabilities. Do not accept a request to “train on company documents” at face value: assign retrieval of current policies and source citation to Retrieval-Augmented Generation (RAG), strict JSON validation to schemas and code, and recurring classification boundaries, tone, and refusals to SFT candidates. Choosing the solution first can freeze changing facts in an outdated adapter or turn a deterministic problem into a harder probabilistic one.
Write goals as observable task outcomes, not “good answers.” Define conditions a parser and reviewer can judge, such as required inquiry category, urgency, and reason, a hold when information is missing, and a ban on confirming refunds without authority. On a frozen set with normal, boundary, conflict, and unsafe inputs, run the exact base, system prompt and few-shot, and RAG and rule candidates, and measure task success, critical recall, format, excessive refusals, and human corrections. Before seeing results, approve the minimum improvement the adapter candidate must achieve and the gates that must never regress.
SFT does not automatically create general capabilities absent from the base model or turn unverified labels into valid ones. If dataset rows are ambiguous, the model learns that ambiguity. A small adapter does not reduce your responsibility when source rights are missing or personal data remains. Accept only immutable versions that have passed dataset-release rights, privacy, schema, template, and label reviews, group-leakage checks, and frozen-test checks as training inputs. If you change test rows after seeing training results, create a separate data version and a new untouched test set.
Completion can include deciding not to train. Hold the adapter plan if the prompt baseline already passes critical gates or frequently changing sources make RAG cheaper to maintain. Fine-tuning adds evaluation, registry, serving and rollback responsibilities as well as training code. Consider expected improvement, GPU time, reviewer-correction savings and incident costs, and move to a pilot only if the owner can operate the change.
Why does this happen?
Because with the wrong method, even large amounts of data and GPU time will not fix freshness, evidence, or format problems and will only create new operational debt.
When is it a problem?
If you start with “the data was added” as the success criterion, you cannot judge improvement over the base model, critical regressions, or when to discard the adapter.
Common beginner misconceptions
Fine-tuning is neither a database that stores documents safely in a model nor a step that replaces all prompt engineering and RAG.
How to verify it yourself
On the same frozen task set, compare the goals of the base, prompt/RAG, and the planned adapter in a table, and name the failures only the adapter should fix and the independent mandatory gates.
Conceptual explanation 02
Pin the exact base, tokenizer, license, and serving path in one contract
Do not select a base candidate by parameter size alone. Review the target-language and task frozen baseline, instruct or base variant, context and chat template, architecture, license, acceptable use, source-model release conditions, and intended runtime. PEFT may inject target modules even when the production runtime cannot dynamically load adapters, and redistribution conditions may change after merging. Work backward from final execution to avoid unsupported training outputs.
The manifest records the repository ID, immutable commit·weight hash, config and tokenizer file hashes, chat_template, generation defaults, and code trust setting. “Latest main” or a mutable tag may later point to different weights. Check the local cache against the manifest hash as well, and preserve snapshots of the download source·license. Read the limitations and evaluation scope in the base model card, but do not stretch the card's wording into approval of quality·rights for your own tasks.
The tokenizer and template are part of adapter behavior. Even within the same architecture, instruct families may use different user and assistant control tokens. Render training rows with the exact template and compare serving-runtime token IDs against golden fixtures. Record duplicate BOS/EOS tokens, unsupported system roles, added special tokens, and pad-token choices. If you change the tokenizer vocabulary, specify how embedding and lm_head weights will be trained and saved. If you do not change it, record that in the manifest too.
A small compatibility smoke test runs through base load, template rendering, one forward pass, LoRA injection and backward, adapter save and reload, and production-like generation. This step confirms support for architecture layer names, quant kernels and dtypes, drivers, and runtime adapters. Success with the official minimal example is only a starting point; approve the training plan only after the same stack passes at the actual max length and batch size and through the deployment endpoint.
Why does this happen?
Because an adapter file does not contain the base parameters themselves, only changes relative to specific layers and token sequences, its meaning changes when the base or input contract changes.
When is it a problem?
Keeping only the model name means mutable revision·template changes make training irreproducible, and production may receive incorrect control tokens.
Common beginner misconceptions
Sharing the same 7B architecture or tokenizer class does not guarantee compatibility of weight revision·chat template·license and adapter targets.
How to verify it yourself
Confirm the base weight, config, and tokenizer/template hashes, the license, and the adapter load or merge path in the target runtime, using the manifest and golden token fixtures.
Conceptual explanation 03
Verify LoRA's low-rank update and frozen base on the actual parameters
The original LoRA paper freezes the pretrained model weights and injects trainable rank decomposition matrices into Transformer layers. Instead of changing the existing matrix W directly, it adds a low-rank update ΔW to the output, expressed by two small matrices. This is the key to reducing trainable parameters, gradients, optimizer state, and storage compared with full fine-tuning. Do not carry the reduction factor reported for a particular GPT-3 experiment in the paper over to other models, optimizers, or hardware; explain savings with your own run's trainable count and peak.
Rank r is the internal dimension of the update matrix. A higher rank provides more trainable parameters and expressive capacity, but it does not always improve task quality or eliminate overfitting. Alpha affects update scaling, and dropout·bias·initialization also change the results. When comparing candidates, change only the rank with the same dataset·token budget and, where possible, the same seed family, and review task·critical·general regression together with memory·step time.
After adapter injection, save a trainable-parameter report. Output total and trainable counts and ratios, per-layer target names, shapes and ranks, and modules_to_save; inspect requires_grad through model.named_parameters. After the first backward pass, check that base-parameter gradients are empty and optimizer groups contain only adapters. Do not rely solely on loss logs and miss unintended head or embedding training caused by wildcards, or runs with zero matched targets.
When default initialization is designed to be near a no-op, compare output with the base immediately after applying the adapter as a smoke test. Explain expected differences from new special tokens, modules_to_save, or bias training separately. After saving, reload the adapter in a fresh process and verify logits, generation, and trainable/inference modes on identical golden inputs. A working in-memory object does not prove the checkpoint is complete.
Why does this happen?
Because LoRA's advantages come from the scope of parameters actually changed, and a wrong target or optimizer group fundamentally changes training cost and results.
When is it a problem?
Trusting only the config file can let a run with 0 targets, missing layers, or a trainable base finish without verifying the claim that only a small adapter is trained.
Common beginner misconceptions
Using LoRA does not by itself guarantee the same quality as full fine-tuning, a fixed memory saving, or preservation of base capabilities.
How to verify it yourself
Record trainable counts and layer lists before and after injection, gradients and optimizer groups from the first backward pass, and save and fresh-reload results in the same manifest.
Conceptual explanation 04
Choose target modules, rank, and alpha through architecture-aware task comparison experiments
PEFT’s LoRA documentation gives examples targeting attention query·value layers by default and using all-linear for QLoRA-style training. Names and tensor grouping such as q_proj·v_proj·query_key_value differ by architecture. Check model.named_modules, official architecture code, and PEFT mappings, and record actual matched-layer counts. Mixture-of-Experts models separate shared·expert FFNs and routers, so do not directly copy a dense recipe.
Narrow attention targets use fewer parameters and less memory but may produce insufficient task adaptation. All-linear targets can learn more FFN updates, increasing capacity and cost. Include the target set, rank and alpha, trainable count, peak memory, tokens/s, and frozen task, critical and general regression tests in the comparison matrix. Separate experimental axes: changing targets, rank, data version and learning rate in one run prevents identifying which change caused the result.
Modules_to_save is an important contract that specifies modules to train·save in addition to adapter layers. If changing a classification head, new-token embeddings, or lm_head, verify why it is needed and how it is stored separately from the base. Bias options can also alter base-equivalence and merge behavior. Record rank·alpha·dropout·targets·bias·task type and base references in PEFT config, and check actual checkpoint parameter keys against it.
The selection criterion is not the largest configuration but the simplest candidate that passes every required gate. If rank 8 attention-only reaches 93% task success, 97% critical, and acceptable regression, while rank 32 all-linear reaches 94% task success but fails the general regression and memory limits, you can choose the former. If repetition variance overlaps the score difference, do not claim the more complex setting won; run additional seeds and a failure review.
Why does this happen?
Because target and rank change the trainable scope, memory, expressiveness, and checkpoint structure all at once, requiring architecture checks and controlled comparisons.
When is it a problem?
Copying community configurations can omit layers, train unintended modules, and cause high-rank costs to be mistaken for actual task improvements.
Common beginner misconceptions
All-linear targeting or a higher rank does not always mean a more complete LoRA; for small tasks and datasets it can cause larger regressions and overfitting.
How to verify it yourself
Compare matched-module·trainable-parameter reports alongside task·critical·regression·memory results for candidates with one factor changed at a time.
Conceptual explanation 05
Separate QLoRA's 4-bit base from actual compute·activation memory
The original QLoRA paper passes gradients through a frozen 4-bit quantized pretrained model into a LoRA adapter and manages memory with NF4, double quantization, and a paged optimizer. This approach greatly reduces base weight memory, but it is not a table showing that every model and GPU works at a particular size. Cite the paper's 65B·48GB result as a result of that study's model·sequence·batch·kernel and evaluation scope, and require exact workload measurements on your own hardware.
The Transformers bitsandbytes documentation describes 8-bit and 4-bit training support for extra parameters, and provides NF4 and a separate bnb_4bit_compute_dtype setting for training with a 4-bit base. Record quantization type, nested or double quantization, storage and compute dtypes, adapter dtype, libraries, CUDA, drivers, and hardware capabilities in the manifest. Insufficient BF16 support or operator fallback can affect speed and stability, so verify device placement and actual kernel execution.
The memory ledger includes quantized base weights and quant metadata, dequantization buffers, adapter parameters·gradients·optimizer state, activation, attention workspace, and allocator reserves. Activation is sensitive to sequence length·micro-batch·hidden size·layers; gradient checkpointing uses more compute to reduce memory. Packing can reduce padding waste, but check each packed sequence’s length and mask. Record separate peaks for load, first forward, backward, optimizer step, evaluation, and save.
Do not silently change targets during OOM recovery. Check one item at a time: whether reducing micro-batch and increasing accumulation preserves effective batch, whether shorter max length removes long-task coverage, and whether checkpointing·optimizer changes affect step time and convergence. After warm-up, measure peaks·tokens/s, host memory·offload I/O, and runs lasting at least 30 minutes. Hardware fit passes only after completing the target dataset, evaluation·save, and interrupted-checkpoint resume.
Why does this happen?
This is because QLoRA changes weight memory while other large training-memory items and hardware·kernel requirements remain, so simple model-B·VRAM tables often fail.
When is it a problem?
Setting max length·batch from the “4-bit” label alone can cause OOM during backward·evaluation·save, while offload stalls can push job duration beyond the target.
Common beginner misconceptions
QLoRA is not a method that trains the LoRA adapter and all computation in 4-bit, nor does it guarantee a specific 7B model on any 16GB GPU.
How to verify it yourself
Using a manifest of the exact quant, compute, and adapter dtypes and sequence, batch, and checkpointing settings, repeatedly measure peak memory, step time, completion, and resume at each step.
Conceptual explanation 06
Inspect chat template, loss mask, and truncation in the actual tokens
Hugging Face chat-template documentation explains that role/content lists become model-specific control-token sequences and incorrect tokens can substantially degrade performance. Render system/user/assistant conversations with the exact tokenizer revision and preserve rendered text and token IDs. Use golden fixtures to check duplicated BOS/EOS or end-of-message tokens, system-role and multi-turn support, and whether the serving runtime produces the same sequence.
TRL SFTTrainer’s assistant_only_loss can restrict loss to assistant responses in conversational datasets, provided the template supports generation spans. Also verify the completion-only default for prompt-completion datasets against the actual version and configuration. Mark each sample token as -100 or a target to check that user instructions and system policies are not being learned as model outputs. Do not assume that enabling a configuration option makes the mask cover the intended spans.
Measure length in rendered tokens, not raw characters. Record in a per-row report whether truncation cuts only long user context or also the final JSON brace or refusal conditions of the answer, and on which side truncation occurs. If even one target token is cut from critical output, hold the row and fix the chunking, max length, or data. When packing is enabled, check with a token map of a small known batch that example boundaries, position and attention behavior, and loss masks do not bleed into each other.
A dataset version includes not only the raw JSONL hash but also conversion code, tokenizer/template hash, max length, packing, and loss configuration. The same row is a different training input if any of these values change. Do not change the training and inference templates at the same time; re-evaluate a template candidate on the same frozen set against both the base and the previous adapter. Template mismatch is a classic deployment failure: it is not an adapter quality problem, yet a model that looks the same answers strangely.
Why does this happen?
A causal LM learns control-token sequences and label masks, not role objects, so if this conversion is wrong, even correct rows teach different behavior.
When is it a problem?
Looking only at raw JSON and train loss will not reveal user prompts being learned, target truncation·duplicated special tokens, or serving template mismatches.
Common beginner misconceptions
The mere presence of user and assistant roles in messages does not guarantee assistant-only loss or correct model-specific token serialization.
How to verify it yourself
Compare the rendered text, token IDs, loss mask, and truncation of golden conversations in both training and serving, and confirm 0 missing critical targets.
Conceptual explanation 07
Turn the learning schedule, effective batch, and clean run into observable experiments
Effective batch is micro-batch × gradient accumulation × data-parallel workers, not merely one GPU's micro-batch. Recording only epochs misses changes in optimizer steps and tokens seen caused by packing, drop_last, or world size. Put dataset rows, rendered tokens, micro/effective batch, accumulation, max_steps/epochs, warmup, scheduler, learning rate, and seed in the run manifest. Keep token budgets and evaluation intervals identical across candidates.
The pilot uses a small dataset in which a person can inspect every sample and output, and checks forward·backward·optimizer, evaluation, and save·fresh reload. In the full run, record training·validation loss, task metrics, critical gates, gradient norm·NaN/Inf, learning rate, tokens/s, peak allocated/reserved memory, skipped·truncated rows, and checkpoint hashes at the same global step. Even if loss decreases, stop on gradient explosion·throughput collapse or critical metric degradation.
Changing target modules, rank, learning rate, data version and maximum length together prevents identifying the cause of improvement. Hypothesize one major failure cause from the baseline configuration and change one axis. For final candidates, examine metric distributions and overlapping failures across clean runs to avoid dependence on one lucky seed. Frameworks and kernels may not guarantee complete bitwise determinism, so predefine tolerances and do not hide reproducibility warnings.
Checkpoints must also be tested for failure recovery. Restore the optimizer, scheduler, random state, and sample position from a mid-run checkpoint, continue training, and compare the result with an uninterrupted reference within tolerance. For disk-full, corrupt checkpoint, OOM, and evaluation failures, use status tracking and atomic publishing so a partial artifact is not mistaken for a release. An experiment becomes approvable evidence rather than a personal notebook only when the run can be replayed in a clean environment from a dependency lock and code, config, and data hashes.
Why does this happen?
Batch, steps, schedules, and data order jointly determine optimization. Recording only a few numbers prevents reproducible candidate comparisons and resumption after failures.
When is it a problem?
If only a screenshot of the final loss is kept, no one can tell which data, token budget, and learning rate produced the checkpoint, or whether the same run was resumed after an OOM.
Common beginner misconceptions
Fixing one seed or using the same configuration file does not automatically guarantee bitwise reproducibility across hardware and kernel differences or equal quality.
How to verify it yourself
Link the run manifest, per-step loss, task metrics, gradients, memory, throughput, clean repeat runs, and interrupted-resume results to the checkpoint hash.
Conceptual explanation 08
Select checkpoints by task, critical, and general-capability regressions relative to the base, not train loss
Training loss measures fit to next-token targets in seen rows, and validation loss is also a proxy for held-out token prediction. Production promotion gates on task success, schema compliance, critical-class recall, unsafe compliance, unsupported answers, over-refusal, and human corrections. Run the base model, prompt/RAG baseline, previously approved adapter, and each checkpoint on the same frozen set, decoding settings, and runtime. Include contamination and memorization probes to check for verbatim reproduction of dataset and test phrases.
Critical gates cannot be offset by averages. Even if overall task success increases by 2%p, a drop in refusal of unauthorized actions from 98% to 91% can justify a hold. The general-regression set covers capabilities agreed to be preserved from the base, such as language, instruction following, long inputs, code, and reasoning. Blind human reviewers compare output pairs using a rubric. If an automatic judge is used, retain its version, prompt, bias, and disagreement with humans as separate evidence.
Transformers Trainer can load the best checkpoint using an evaluation strategy and metric_for_best_model, but the task owner is responsible for metric selection. Apply must-pass gates separately from the single best metric, and verify that save and evaluation intervals compare the same checkpoints. Early stopping depends on validation noise, evaluation frequency, and patience, so preserve candidates from before the final checkpoint and inspect failure taxonomy by step.
Record confidence and limitations in the selection result. Put the mean and range across clean runs, critical failure count, improvement or regression versus the base, memory and latency, and reviewer corrections in one release table. Do not widen the allowed drop after seeing results. If a candidate fails, go back to data, target, or schedule causes and create a new run ID, and separate development validation from the final frozen test so the same test is not optimized repeatedly.
Why does this happen?
Because token loss hides the separate error costs of real tasks, safety, and original capabilities in a single value, production selection needs independent gates.
When is it a problem?
Automatically adopting the final or lowest-loss checkpoint can miss better task metrics at earlier checkpoints and later regressions in refusal behavior and general capabilities.
Common beginner misconceptions
A falling validation loss or preference by an automated judge does not guarantee factuality, safety, human task success, or the absence of data leakage.
How to verify it yourself
Compare the base, previous version, and all candidates blind on the same frozen set, and apply every predefined task, critical, regression, and operational gate.
Conceptual explanation 09
Close the release with an adapter bundle, canary, and rollback to the previous compatible stack
PEFT checkpoint documentation centers on adapter_model.safetensors and adapter_config.json; adapter state does not include base-model parameters. Config may contain base references·revisions, rank·alpha·targets, and other settings, but do not assume it saves all provenance automatically. Bundle exact base·tokenizer/template hashes, adapter-file hashes, PEFT·Transformers·TRL·bitsandbytes and driver versions, LoRA/quant/training config, dataset·code commits, and evaluation reports in the registry.
Load the bundle in a fresh environment and verify that the trainable adapter attaches correctly in inference mode and reproduces golden inputs and the frozen set. Dynamic adapter loading and merged deployment are separate artifacts. Compare logits, task results, critical cases, latency and precision before and after merging, and review base/adapter licenses and redistribution terms again. Record intended and out-of-scope uses, data scope, metrics, limitations, known failures and the owner in the model card.
After offline gates pass, observe schema failures, critical incidents, human correction·override, p95·memory, and adapter-load errors in shadow or limited canary using production-like templates·generation config. Define canary criteria, automatic stops, and the approval owner beforehand. Do not use user traffic merely to fill test counts or replace everything without monitoring. New base·data·policy·runtime versions are all re-review triggers.
Rollback is not simply deleting an adapter file. Reload the previous compatible base revision, tokenizer/template, runtime·quant·generation config, and approved adapter, verifying actual cache·worker replacement. Repeatedly test recovery on exact candidate-failing inputs and preservation of normal regression results within the recovery-time target. Trace affected runs·data sources through lineage and record hold·retrain·discard decisions to close the release.
Why does this happen?
Because an adapter depends on multiple external artifacts and runtimes, and production problems arise from that combination, it must be managed as a deployable, recoverable bundle.
When is it a problem?
Keeping only adapter_model.safetensors can allow loading to succeed after the base or template changes while behavior differs, preventing an exact return to the previous state.
Common beginner misconceptions
Being a small adapter or in safetensors format does not automatically guarantee provenance, license, quality, safety, or the equivalence of merge results.
How to verify it yourself
Check fresh loading, evaluation before and after merging, canary criteria, and, on rollback to the previous full stack, recovery from the same failure, normal regression, and recovery time.
CONCRETE CASES
Check concepts in different situations
Before memorizing definitions, compare how these concepts appear on a personal PC and in real work.
Case 1 · Before training, demonstrate the behavior to fine-tune and the base-model baseline
For a task that outputs customer inquiries as category·urgency·reason JSON, record base format compliance of 71% and critical refund recall of 82%. Keep the latest refund policies in RAG, and make only judgment boundaries and hold behavior SFT candidates.
Key points to check here: Compare the base and prompt/RAG candidates on the same frozen task set.
Case 2 · Confirm the LoRA update, target modules, and rank in the actual trainable parameters
Compare a candidate that attaches rank 8 only to attention q_proj and v_proj with an all-linear rank 16 candidate on the same dataset and steps, and use model.named_parameters and the PEFT trainable report to confirm that unintended parameters are frozen.
Key points to check here: Record rank·alpha·dropout·bias·modules_to_save and target-module lists in configs and logs.
Case 3 · Separate QLoRA's 4-bit storage·compute·adapter precision and memory peaks
For an NF4 base, BF16 compute, all-linear LoRA rank 16 candidate, measure batch 1 at lengths 1024 and 2048 after warm-up, recording peaks of 14.2GiB/20.8GiB and tokens/s. If OOM occurs, reduce only the length.
Key points to check here: Record NF4·double quant·compute dtype and adapter dtype separately.
Case 4 · Turn template, loss mask, batch, and clean runs into an observable training contract
Render 20 conversational rows and confirm that the assistant_only_loss mask covers only assistant spans and that target truncation is 0. Then run the 200-row smoke run clean twice and compare the identical settings, per-step metrics, and checkpoint loading.
Key points to check here: Compare training and serving tokenizers, templates, and special tokens against golden fixtures.
Case 5 · Approve the best checkpoint through task and safety regression checks against the base and previous versions, plus rollback
If step 400 has the lowest validation loss but fails the 95% gate with 91% critical refusal, make step 300 the candidate, since it stays within the allowed range (94% task, 97% refusal, general regression) despite slightly higher loss, and test the canary and rollback to the previous adapter.
Key points to check here: Pin checkpoint selection metrics and independent required gates before seeing results.
CHAPTER 1 / 5
Before training, demonstrate the behavior to fine-tune and the base-model baseline
Pretraining is a large-scale process that trains many model parameters on a broad corpus. Supervised Fine-Tuning (SFT) adjusts specific behavior by showing input·target examples to a model that already has capabilities. Do not automatically translate “add internal knowledge” into training. Separate frequently changing facts requiring sources, such as prices·policies, into RAG candidates; deterministically validatable formats into code·schema candidates; and recurring response structures·decision boundaries·refusals into SFT candidates.
First build a frozen evaluation set with production-like normal, boundary, insufficient-information and unsafe inputs, and run the exact base model. Record task success, critical-class results, schema compliance, unsupported answers, excessive refusals and latency. Compare simpler system-prompt, few-shot, RAG and rule baselines on the same set. If no observable target justifies the adapter's cost and operational complexity, putting training on hold is a complete decision.
Base selection includes language and task baselines, context, architecture, instruct status, tokenizer and chat template, licensing and acceptable use, redistribution rights, and target runtime as well as parameter count. Pin immutable revisions and weight hashes rather than recording only model IDs. Use a small official example to check the training library’s target-module names and actual hardware support for quantized loading, adapter saving, and serving.
Dataset and model releases are connected but have different gates. Use immutable datasets that passed rights, PII, label, and group-split checks, plus exact conversion/templates and frozen tests. Editing rows or thresholds after training starts in response to test results makes the test no longer blind. Create new data versions and development validation sets; reserve untouched tests for final candidate comparisons.
How to read the figure Fine-tuning starts not with the GPU but with the question of whether training is needed at all. Prove the base baseline, then pass the data, template, and adapter settings, the checkpoint comparison, and the recovery evidence in order.
To recap the key points
Compare the base and prompt/RAG candidates on the same frozen task set.
Pin the base license, revision, tokenizer, chat template, and deployment runtime support before starting.
How this connects in practice
For a task that outputs customer inquiries as category·urgency·reason JSON, record base format compliance of 71% and critical refund recall of 82%. Keep the latest refund policies in RAG, and make only judgment boundaries and hold behavior SFT candidates.
CHAPTER 2 / 5
Confirm the LoRA update, target modules, and rank in the actual trainable parameters
The original LoRA paper proposes keeping pretrained weights frozen and injecting trainable rank decomposition matrices into layers. Instead of updating the entire large weight W, it expresses the change ΔW as the product of two small matrices. This reduces the trainable parameters that need gradients and optimizer state, as well as adapter storage. Do not apply the reduction factor from the paper's particular GPT-3 setup to every architecture, optimizer, and hardware; verify it with actual reports and peak memory.
Rank r is one dimension of the update’s representational capacity. Increasing it adds trainable parameters and capacity, but does not imply monotonically improving task quality. Alpha affects update scaling; dropout·bias·initialization also affect results. Compare task validation and regressions under the same data·seed family·step budget to assess low-rank underfitting or high-rank memorization of noise. Do not change rank, targets, and learning rate simultaneously.
Target modules must match actual linear-layer names in the architecture. The official PEFT LoRA documentation targets attention query and value layers in its basic example and describes specifying all-linear for QLoRA-style training. Copying the name q_proj to every model may omit layers or cause errors. After adapter injection, save counts and shapes for each target, the trainable-to-total parameter ratio, and the requires_grad list. Check whether intended embedding and lm_head layers need separate modules_to_save entries.
Verify “frozen base” in the runtime state as well. After the first backward pass, check that the optimizer receives only adapter parameters and that no gradients appear in the base. Adding new special tokens may require an embedding resize and saving those rows; if the base tokenizer is left unchanged, record that nothing changed. Immediately after loading the adapter, smoke-test whether the initial output matches or stays close to the base as expected, to catch wrong initialization or module mapping early.
To recap the key points
Record rank·alpha·dropout·bias·modules_to_save and target-module lists in configs and logs.
Instead of guessing from the architecture name, inspect the injected layers and the trainable parameter report.
How this connects in practice
Compare a candidate that attaches rank 8 only to attention q_proj and v_proj with an all-linear rank 16 candidate on the same dataset and steps, and use model.named_parameters and the PEFT trainable report to confirm that unintended parameters are frozen.
CHAPTER 3 / 5
Separate QLoRA's 4-bit storage·compute·adapter precision and memory peaks
The original QLoRA paper describes backpropagating gradients through a frozen 4-bit quantized pretrained model into a LoRA adapter, and introduces NF4, double quantization, and a paged optimizer. Here, 4-bit refers to the memory representation of the base weights; it does not mean that all training computation and the adapter are 4-bit. The paper's 65B·48GB result comes from a specific model·kernel·sequence·batch and research setup, so do not turn it into a guarantee for consumer GPUs in general.
The official Transformers bitsandbytes documentation states that 8-bit and 4-bit training supports learning extra parameters, and shows NF4 for QLoRA with a separate compute dtype. Record load_in_4bit, quant_type, double quantization, storage and compute dtypes, device maps, and library and driver versions in the manifest. Limited BF16 support or different kernel and operator combinations can affect speed and stability, so verify capabilities and actual execution through profiler output and logs.
Reducing weight memory does not eliminate activations, which depend on sequence length, micro-batch size, hidden size, layer count, and checkpointing. Adapter gradients, optimizer states, dequantization buffers, and allocator fragmentation also remain. Instead of relying on tables saying “7B fits in 16GB,” create a manifest of the exact model and revision, sequence distribution, packing, micro-batches, gradient accumulation, gradient checkpointing, and optimizer. Measure peaks separately at load, first backward pass, optimizer step, and save.
When Out of Memory (OOM) occurs, do not lower multiple settings at once. First change micro-batch·max sequence·long packed samples, checkpointing, and optimizer settings one item at a time, and compare learning schedules again if the effective batch changes. CPU offload and paged methods are not magic fixes that hide failures; also measure step time·host memory·I/O stalls. Passing means repeatedly completing the target dataset with checkpoints that can be resumed, not one successful step.
To recap the key points
Record NF4·double quant·compute dtype and adapter dtype separately.
Measure actual peak memory and step time for each sequence length, micro-batch, accumulation, and checkpointing setting after warm-up.
How this connects in practice
For an NF4 base, BF16 compute, all-linear LoRA rank 16 candidate, measure batch 1 at lengths 1024 and 2048 after warm-up, recording peaks of 14.2GiB/20.8GiB and tokens/s. If OOM occurs, reduce only the length.
CHAPTER 4 / 5
Turn template, loss mask, batch, and clean runs into an observable training contract
A messages object is not passed unchanged into a causal model. A chat template converts roles·content into model-specific control tokens; Hugging Face documentation explains that incorrect control tokens can severely harm performance. Save apply_chat_template output and token IDs for the exact tokenizer revision, checking duplicate BOS/EOS and assistant start/end markers in golden rows. If training and serving use different templates, lower loss does not ensure the behavior reproduces on deployment inputs.
Make the loss scope explicit. TRL SFTTrainer provides assistant_only_loss for conversational datasets and a completion-only setting for prompt-completion data, but assistant masks have conditions such as the template supporting generation regions. Visualize, per sample, whether user and system tokens are trained, whether packing mixes example boundaries, and the label -100 mask. Before training, hold rows whose correct answer or refusal is truncated at the rendered max token length.
Calculate effective batch as micro-batch × gradient accumulation × data-parallel workers, and record the actual number of optimizer steps, warmup, scheduler, learning rate, epochs, max_steps, and seed. Packing can improve compute efficiency for short examples, but verify boundaries, attention, and loss masks in the actual trainer version. Comparison experiments keep the same dataset version, sample order, and token budget, and change only one axis at a time, such as target, rank, or learning rate.
A smoke run verifies forward and backward passes, optimizer steps, evaluation, adapter saving and loading, and resume, beyond successful parsing. Record NaN/Inf losses, gradient norms, learning rates, tokens/s, peak allocated and reserved memory, and skipped samples at every step. Run the same manifest several times in a clean environment to record the range of nondeterminism. PyTorch and kernels may not guarantee bitwise reproducibility, so judge by predetermined metric tolerances and artifact lineage rather than identical hashes.
To recap the key points
Compare training and serving tokenizers, templates, and special tokens against golden fixtures.
Record train loss, validation task metrics, gradients, memory, throughput, and checkpoint hashes at the same step.
How this connects in practice
Render 20 conversational rows and confirm that the assistant_only_loss mask covers only assistant spans and that target truncation is 0. Then run the 200-row smoke run clean twice and compare the identical settings, per-step metrics, and checkpoint loading.
CHAPTER 5 / 5
Approve the best checkpoint through task and safety regression checks against the base and previous versions, plus rollback
Training loss measures fit to seen rows, and validation loss is a proxy for held-out token prediction. Promotion uses schema and task accuracy, critical-class recall, hallucination and unsafe compliance, excessive refusal, and regressions in general capabilities. Blindly compare the base and prompt baseline, previously approved adapter, and candidate checkpoints on the same frozen set, decoding settings, and runtime. Put promotion on hold if any required safety, permission, or numerical gate fails, even if averages improve.
Transformers Trainer supports loading the best checkpoint using evaluation strategy and metric_for_best_model, but the default metric choice is not a task approval criterion. Test whether save/eval intervals align, whether both the best and latest checkpoints are preserved, and whether an interrupted run resumes with the same sample position, scheduler, and optimizer state. Detect overfitting not only through validation divergence but also through memorized training phrases, worsening rare classes, and loss of the base model's general instruction-following ability.
PEFT checkpoints primarily store adapter weights and adapter_config, not base weights. Reproduction therefore requires the base model’s immutable revision·hash, tokenizer·template·special tokens, PEFT/Transformers/TRL/bitsandbytes versions, LoRA config, dataset·code commits, and evaluation reports. Record purpose·data scope·metrics·limitations·license·out-of-scope uses in the model card. For merged artifacts, recheck before/after-merge evaluation and redistribution conditions.
After offline checks pass, observe actual format failures·human corrections·latency·memory and incidents in shadow or limited canary. Rollback restores a compatible base·tokenizer/template·runtime·generation config and the previous approved adapter, rather than merely removing an adapter file. Check recovery on identical failing inputs and replacement of caches·loaded adapters. Record the owner, re-review triggers, and base·data·policy change conditions in approval evidence.
How to read the figure Checkpoint 400, which has the lowest loss, is rejected because it fails two gates: critical safety at 91% and a general-capability regression of −3.1p. Only checkpoint 300, which passes every gate fixed before the results and returns to the previous adapter within 8 minutes, moves on to canary.
To recap the key points
Pin checkpoint selection metrics and independent required gates before seeing results.
Bundle adapter and base revisions, tokenizer and template, configuration, dataset, code and environment hashes, and a rollback run in one manifest.
How this connects in practice
If step 400 has the lowest validation loss but fails the 95% gate with 91% critical refusal, make step 300 the candidate, since it stays within the allowed range (94% task, 97% refusal, general regression) despite slightly higher loss, and test the canary and rollback to the previous adapter.
INTERACTIVE LAB 1 / 2
Lab 1 · LoRA/QLoRA configuration and memory contract lab
Enter values in the browser and check the execution results and the failure and recovery paths. No commands are ever sent to real equipment or the NAS.
Approve a fine-tuning plan using behavior, base, target, precision, and actual memory
Judge the behavior to be learned, the exact input contract, adapter injection, and end-to-end pilot evidence rather than a model B count and VRAM table. Defaults intentionally fail.
Situation
After reading a post saying 7B QLoRA works on 16GB, the layer names were copied without checking the base revision·loss target or the backward peak.
Goal
Link the LoRA or QLoRA candidate's purpose, base, dataset, template, targets, rank, precision, actual memory, and pilot into one planning gate.
Prerequisites
Prepare the base and prompt/RAG baselines, the approved dataset manifest, the architecture module report, the exact environment, and per-step peak logs after warm-up.
Success criteria
Select concrete behavior and verified targets, verify all six evidence items, and ensure the measured peak is at most 90% of available memory.
Select the behavior to fine-tune, the LoRA or QLoRA method, and the target scope confirmed in the actual architecture.
Enter rank·hidden·layer values and the measured peak, and check base·data·template·precision·trainable·pilot evidence.
Run fine-tuning plan gates Then strengthen the failing contract layer and rerun without lowering targets or passing thresholds.
Evidence limits: Adapter estimates are simplified educational values based on square projections and the number of selected targets, and they do not include bias, embeddings, MoE, or modules_to_save. The browser does not run a model or GPU, so the actual PEFT report, profiler, and checkpoint logs are the final evidence.
INTERACTIVE LAB 2 / 2
Lab 2 · Checkpoint quality, regression, and recovery promotion lab
Enter values in the browser and check the execution results and the failure and recovery paths. No commands are ever sent to real equipment or the NAS.
Promote checkpoints through task, critical, general-regression, operational and full-stack rollback checks
Judge independent gates against the base and previous versions and assess the deployable bundle, rather than choosing the lowest-loss or final checkpoint. The defaults intentionally fail.
Situation
The last checkpoint had the lowest validation loss, but permission refusals and general instruction-following degraded, and p95 missed the target.
Goal
Combine task, critical, and general regression checks, p95, clean repetitions, failure review, fresh reload, and recovery to the previous compatible stack into one release gate.
Prerequisites
Prepare raw outputs from the base, previous version, and checkpoints, the untouched frozen set, exact run and artifact manifests, a fresh environment, and a tested previous bundle.
Success criteria
All four metrics and 3 repetitions pass, and evidence of identical comparison, failure attribution, fresh reload, and full-stack rollback is confirmed.
Before seeing candidate results, pin the task and critical targets, the allowed general drop, and the p95 ceiling.
Enter candidate measurements·repetitions on the same frozen set, along with manifest·failure·fresh load·rollback evidence.
Run checkpoint promotion gates Then, instead of changing the loss criteria, fix the failure cause in the checkpoint, data, target, or serving, and reevaluate with a new run.
Evidence limits: The browser evaluates only entered numbers and does not run models, checkpoints, or latency measurements. Without actual raw outputs, run logs, artifact hashes, blind review, and fresh load and rollback records, this is not evidence for production approval.
KEY TERMS
Key terms in this unit
LoRA
A parameter-efficient adaptation technique that freezes pretrained base weights and trains small low-rank update matrices on selected layers
QLoRA
A fine-tuning approach that passes gradients through a frozen quantized base to LoRA adapters while reducing base weight memory with NF4 or similar formats
Target module
Name and scope of the actual architecture layers into which the LoRA adapter is injected
Effective batch
The number of examples reflected in one optimizer update, calculated by multiplying the micro-batch, gradient accumulation, and number of data-parallel workers
Regression gate
Independent criteria that decide whether a candidate worsens required task, safety, general-capability, or operational conditions beyond the allowed range relative to the base or previous version
UNIT WORKBOOK
Exercises and worksheets for applying concepts to new situations
Start by checking basic principles, then expand to practical workplace decisions. After submitting an answer, you can see why every option is correct or incorrect, not just the correct answer.
Basic Question 1
Which statement most accurately describes the core mechanism of Low-Rank Adaptation (LoRA)?
Basic Question 2
Which precision description is most appropriate to record as distinct items in a QLoRA training manifest?
Apply Question 3
After copying another model's LoRA config, the loss decreases, but you cannot tell whether the intended FFN layers were trained. What is the most appropriate next step?
The candidate architecture uses different module names from the community example, and one new special token has been added.
Apply Question 4
In conversational SFT, assistant_only_loss is enabled, but the end of the critical JSON answer is often missing. What should you check first?
Capstone Question 5
Which is the most complete plan for promoting a LoRA candidate checkpoint to production?
The predefined gates are 92% task success, 95% critical refusal, a general-capability drop of at most 3 percentage points versus the base, serving p95 at or below 1200ms, and recovery to the previous stack.
PERSONAL WORKSHEET
A learning worksheet you adapt to your own environment
Your input remains only on the current browser screen and is not stored or transmitted externally. Use categories and pseudonyms instead of actual sensitive information.
OFFICIAL SOURCES
Verify against official sources
Technical, compatibility, and model information reviewed: August 2026