Sub topic 6
Training data and memorized output
This chapter explains where an AI coding assistant's knowledge comes from, why it sometimes reproduces existing code word for word, and how to spot and handle that. It assumes you have used an AI coding assistant, can work with Git and code review, and know in general what open-source licenses are. It is general education, not legal advice. The law on training and output differs by country and is still changing.
Why training data matters for licensing
A code model is built by training on very large amounts of text and source code. Much of that code is public, and much of it carries a license: MIT, Apache-2.0, GPL, or a custom notice. Some of it carries no license at all, which under default copyright rules means "all rights reserved" rather than "free to use".
Two separate legal questions come out of this, and they are easy to mix up:
- Training. Was it lawful for the model's builder to copy the code and use it to train the model? This is mostly the model provider's problem. Courts and legislatures are still working it out, and the answer differs by jurisdiction.
- Output. When the model produces code for you, is that code a copy of, or derived from, someone's protected work? This is your problem as well, because you are the one who commits and ships the code.
This chapter focuses on the second question. A lawful training process does not automatically make every output safe to ship, and an unsettled training question does not automatically taint every output.
How a model learns, and how it can copy
A model does not store a library of files that it looks up. It learns numeric parameters (weights) that capture statistical patterns in the training text. When you prompt it, it predicts one token (a small chunk of text) at a time, based on your prompt and the tokens it has already produced.
Most of the time this produces new combinations of familiar patterns. Common idioms such as a for loop over a list, a standard null check or a typical REST handler appear in thousands of projects. Producing them is not copying any one source.
Sometimes, though, the model reproduces a long passage almost exactly. This is called memorization. It is more likely when:
- The passage appeared many times in the training data, for example a popular library function copied into many repositories.
- The passage is distinctive, such as unusual variable names, a specific comment or a license header.
- Your prompt closely matches the start of the original, such as a function signature plus the same docstring.
- The model is large, since larger models tend to memorize more.
- Sampling settings make the output more deterministic, which favors the most probable continuation.
Research on language models has shown that training text can be extracted from them with the right prompts. Providers apply mitigations such as filtering and duplicate removal, but none of them guarantees that verbatim output cannot happen.
What counts as copying
Copyright protects expression, not ideas. It does not protect functionality, algorithms as such, or very short and obvious snippets. A copyright claim usually needs the copied part to be original and substantial enough to matter. The rules differ between countries, and there is no fixed number of lines that is "safe".
These factors tend to matter when judging whether generated code infringes:
| Factor | Lower concern | Higher concern |
|---|---|---|
| Length | A few lines | Dozens of lines or a whole file |
| Originality | Obvious, standard approach | Creative structure, unusual naming |
| Constraints | Only one sensible way to write it | Many equally good ways, yet the same one was used |
| Identifiers and comments | Generic | Matches the original's names, comments, or typos |
| Source | Unknown or trivial | A specific, identifiable project |
Matching typos, odd comments or a copyright header inside the output are strong signs of memorization. A near-identical result is more worrying when the code is complex enough that two independent authors would not have written it the same way.
How memorized output carries license obligations
If the output reproduces protected code, the license on the original may apply to your use of it. The obligations depend on the license family, covered in the previous chapters.
- Permissive licenses (MIT, BSD, Apache-2.0) usually require that you keep the copyright notice and license text. Apache-2.0 adds requirements around notices and a patent grant. A model that strips the header gives you code without the notice you would need to preserve.
- Copyleft licenses (GPL, AGPL, LGPL) can require that a work incorporating the code be offered under the same or compatible terms, with source available to recipients. The details depend on how the code is combined and distributed, and AGPL extends this to network use.
- No license means you have no permission to copy at all, even though the code is publicly visible.
The risk is that the code arrives in your repository with no sign of where it came from. A developer who copies code from a GPL project knows it. A developer who accepts a suggestion may never learn that it was a near-copy. In most legal systems, ignorance does not remove the obligation, though it can affect remedies. This is why provenance habits, covered in a later chapter, matter.
Tool features that reduce the risk
Many assistants offer settings or features that target memorization. Names and behavior vary by vendor, so check current documentation rather than assuming.
- Public code filters. The tool compares suggestions against an index of public code and blocks or flags matches above a length threshold. These filters catch exact or near-exact matches but can miss reformatted or renamed copies.
- Reference or attribution display. Some tools show the source repository and license of a matched suggestion so you can decide whether to accept it.
- Data-use settings. Separate controls decide whether your prompts and code are used to train future models. That is a confidentiality question, covered in a later chapter, and it is distinct from memorization of other people's code.
A filter is a risk reducer, not a guarantee. Treat a "no match found" result as one piece of evidence.
Checking suspicious output yourself
You can add your own checks to the filters in the tool. Start with signals that suggest the output is not original.
- Look for embedded notices. Search the generated text for words such as
copyright,license,SPDX,Licensed under,GPLand author names. - Look for oddly specific details. Unusual comments, project-specific names, hard-coded URLs or email addresses suggest a source.
- Search for a distinctive line. Put a distinctive line or comment in quotes into a code search engine or your hosting platform's code search. An exact match in a named project is a strong signal.
- Use a scanner for larger pieces. Software composition analysis and snippet-matching tools compare your code with known open-source code and report license information. They are most useful on larger additions and pull requests.
- Rewrite when in doubt. If a distinctive block is important and you cannot clear it, write it yourself from the specification, not from the generated text. A rewrite based on understanding the problem is safer than light edits to a copy, since renaming variables does not remove copying.
A short script can do the first check automatically. This one scans files you pass on the command line for common license markers and reports the line numbers.
import re
import sys
from pathlib import Path
MARKERS = re.compile(
r"(copyright|licensed under|spdx-license-identifier|gnu general public|"
r"gpl|affero|all rights reserved)",
re.IGNORECASE,
)
def scan(path: Path) -> list[tuple[int, str]]:
hits = []
with path.open(encoding="utf-8", errors="ignore") as f:
for number, line in enumerate(f, start=1):
if MARKERS.search(line):
hits.append((number, line.strip()))
return hits
found = False
for name in sys.argv[1:]:
for number, text in scan(Path(name)):
found = True
print(f"{name}:{number}: {text}")
sys.exit(1 if found else 0)Run it as python scan_markers.py new_file.py other_file.py. It exits with status 1 if it finds anything, so you can also use it in a pre-commit hook. It has false positives, for example in your own headers, and false negatives, because a memorized passage may have no notice at all. It is a quick first filter and not a clearance process.
Common errors
- Assuming that generated means original. The model's output can be a near-copy even though you never saw the source.
- Assuming that public means free. Code visible on a public platform is still protected unless a license grants rights.
- Trusting the filter completely. Filters have thresholds and miss transformed copies.
- Editing a copy lightly and treating it as new. Renamed variables and reordered statements usually leave the protected expression intact.
- Ignoring the size of the risk. Most suggestions are short, generic and low risk. Spending review effort on everything equally wastes time. Focus on long, distinctive and central blocks, and on code in products you distribute.
- Mixing up training and output questions. Whether training was lawful does not decide whether a particular output may be used. Whether an output is clean does not settle training disputes.
What to do when you find a match
- Stop and do not merge the code yet.
- Identify the source project and its license, using the notices in the matched file and the repository's license file.
- Decide whether the license is compatible with your project and whether you can meet its conditions, such as keeping notices or releasing source.
- If you can comply, include the notice and attribution, and record the origin in your provenance notes.
- If you cannot comply, or the license is unclear, remove the code and write your own implementation.
- If the code is already released, tell your legal or compliance contact. Remediation might mean replacing the code, adding attribution or relicensing, depending on the facts.
Summary of the working model
- Models learn patterns, and sometimes reproduce long passages from training data.
- Reproduced passages can bring the original license's obligations with them, or no permission at all if the source had no license.
- Filters and scanners help, but they are partial. Your review is the last line of defense.
- Check what is long, distinctive and important. Document and attribute, or rewrite, whatever you cannot clear.
Exercise
An assistant generates a 60-line function for parsing a custom config format. It includes an unusual comment, "// TODO: ask Dmitri why this offset is 7", and a variable named dmitriFudge. Your tool's public code filter reported no matches. What should you do, and why does the filter result not settle the question?
Show answer
Treat the output as possibly memorized. The odd comment and the person-specific variable name are signs of copied code, and the length and distinctiveness raise the concern. Search for the comment text and identifier in code search, run a snippet-matching scanner, and identify any source and its license. If you find a source, check compatibility and comply with its conditions (for example keeping notices), or else rewrite the function from the specification. The filter result does not settle it because filters compare against a limited index with a length threshold, and can miss reformatted copies or code that is not in the index.
Exercise
A teammate says: "The model was trained on public GitHub code, so anything it outputs is free to use." Give two reasons this is wrong.
Show answer
First, public visibility does not grant a license, and much public code is under conditions (attribution, share-alike) or has no license at all. Second, whether training was lawful is a different question from whether a specific output copies protected expression. If an output reproduces a substantial, original passage, the original license obligations can apply to your use of it.
Exercise
You find that a generated 30-line helper matches an MIT-licensed project. Your project is proprietary. What can you do?
Show answer
MIT is permissive, so you can usually use the code in a proprietary product if you keep the copyright notice and the MIT license text with it. Add the notice, for example in the file header or a third-party notices file, and record the source in your provenance notes. If your team does not want that dependency or attribution burden, replace it with your own implementation.