🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Code Generation: Models, Tokenization and Review

đŸŸĸ Free Lesson

Code Generation: Models, Tokenization and Review

Code Generation PipelineInputCommentDocstringPartial CodeCode LLMTokenize CodeAST-Aware ProcessingGenerate TokensCompletionFill-in-MiddleAutocompleteMulti-line GenOutputComplete FunctionBug FixRefactorDocumentation

What a code model knows that a chat model does not

A general language model trained mostly on prose can produce syntactically valid Python, and that fact misleads people into thinking code generation is solved. Correct syntax is the floor. Production code additionally requires knowledge of APIs that exist, conventions a repository follows, error handling the team expects, and interfaces that already have callers — none of which is recoverable from fluency alone.

Code-specialised models close part of that gap by training on repositories rather than documents: whole files instead of paragraphs, commit messages paired with diffs, issues paired with fixes, and the surrounding file structure that tells a model what a project imports and how it names things. The practical difference shows up in exactly those places. A general model invents plausible function names; a code model reaches for the one your dependency actually exports. Both will happily produce a function that works in isolation, but only one tends to produce code that fits into a codebase that already exists.

Three completion modes, three different jobs

How much context you provide before generation changes what the task is.

ModeGivenProducesTypical use
Left-to-rightPrefix onlyContinuationAutocomplete, boilerplate
Fill-in-the-middleCode before and afterInterpolationCompleting a body between signatures
Instruction to codeNatural-language specNew function or fileFeature work, test writing

Fill-in-the-middle is the mode that makes editors feel intelligent, because the closing brace and the return statement already exist and the model only has to bridge them. Most modern code models support it through special control tokens that mark the prefix, suffix, and insertion point.

python
from transformers import AutoModelForCausalLM, AutoTokenizer

class CodeModel:
    def __init__(self, name: str = "codellama/CodeLlama-7b-hf"):
        self.tokenizer = AutoTokenizer.from_pretrained(name)
        self.model = AutoModelForCausalLM.from_pretrained(name)

    def complete(self, prefix: str, max_new_tokens: int = 160) -> str:
        inputs = self.tokenizer(prefix, return_tensors="pt")
        out = self.model.generate(
            **inputs,
            max_new_tokens=max_new_tokens,
            temperature=0.2,
            top_p=0.95,
            do_sample=True,
            pad_token_id=self.tokenizer.eos_token_id,
        )
        return self.tokenizer.decode(out[0][inputs["input_ids"].shape[1]:],
                                     skip_special_tokens=True)

    def fill_middle(self, prefix: str, suffix: str, max_new_tokens: int = 160) -> str:
        prompt = f"<PRE> {prefix} <SUF> {suffix} <MID>"
        inputs = self.tokenizer(prompt, return_tensors="pt")
        out = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
        return self.tokenizer.decode(out[0][inputs["input_ids"].shape[1]:],
                                     skip_special_tokens=True)

Note the low temperature. Code has one correct answer far more often than prose does, so sampling diversity works against you; temperature near zero for completion, slightly higher when you deliberately want several candidate implementations to choose between.

Why tokenization is harder for code than for prose

Whitespace is meaningful in code and incidental in prose, and that single fact breaks naive tokenizers. Python's block structure lives in indentation, YAML and Markdown care about it too, and a byte-pair tokenizer trained on web text tends to glue leading spaces to words inconsistently. The model then has to reconstruct block structure from tokens that encode it irregularly, which is precisely where generated code breaks: an extra indent inside an if-branch, or a dedent that never happens.

Specialised pipelines address this directly. Some models add explicit indentation tokens; others normalise line endings and trailing whitespace before training so that the same construct always tokenizes the same way; still others operate over abstract syntax trees so that structural edits are expressed as tree operations rather than as string surgery. You do not need to build any of this yourself, but you do need to recognise the symptom: code that is correct line by line but structurally broken almost always failed at the tokenization-to-structure boundary, and the fix is a model or a prompt that makes indentation explicit rather than a clever repair script.

Prompts that produce code you can merge

Prompting for code is mostly about pinning down the contract before generation starts.

python
SPEC_PROMPT = """Write a Python function that satisfies this contract.

Contract:
- Signature: {signature}
- Inputs: {inputs}
- Must raise ValueError on invalid input, never return None silently
- No external dependencies beyond the standard library
- Include type hints and a docstring with one doctest example

Existing code you must fit with:
{surrounding}

Return only the function, no explanation, no markdown fences."""

def generate_with_contract(model, signature, inputs, surrounding):
    prompt = SPEC_PROMPT.format(signature=signature,
                                inputs=inputs,
                                surrounding=surrounding)
    return model.complete(prompt, max_new_tokens=400)

The elements that move the needle are the negative requirements — what must not happen — the explicit failure behaviour, and the surrounding code so the model matches local style instead of inventing its own. Requiring a doctest is the cheap trick that pays the most: it forces the model to commit to an example, which it then has to keep consistent with the implementation it writes.

Evaluating generation properly

Pass@k is the standard metric for a reason: it measures whether any of k sampled attempts is correct, which separates "the model cannot solve this" from "the model solves it unreliably." Reporting only pass@1 punishes models that are right often but not always, and reporting only pass@k hides the retries your users would have to make.

python
def pass_at_k(n: int, c: int, k: int) -> float:
    """n attempts, c correct, probability that at least one of k is correct."""
    if n - c < k:
        return 1.0
    return 1.0 - math.prod((n - c - i) / (n - i) for i in range(k))

print(pass_at_k(n=10, c=6, k=1))   # 0.60
print(pass_at_k(n=10, c=6, k=5))   # 0.99

Run these evaluations in a sandbox with real tests against real dependencies. Code that compiles, looks idiomatic, and fails on the first edge case is the default outcome of unchecked generation, and static metrics such as syntax validity will happily report success while your test suite would not.

The loop from generation to merged change

Generation is one stage of a pipeline, and the stages around it are what make the output trustworthy: gather the relevant files and conventions, generate against an explicit contract, execute tests and linters, feed failures back as concrete errors, and require human review before anything lands.

StageCatchesTypical cost
Context assemblyWrong API, wrong styleOne retrieval call
Generationn/a — produces the candidateOne model call
Tests and lintersSyntax, contract, style violationsSeconds
Feedback repairFailures the model can fix from the messageOne or two extra calls
Human reviewDesign, security, intentReviewer minutes

The feedback loop is where quality comes from. A failing test fed back with its assertion and traceback produces a corrected implementation in one extra call more often than not; a generic "it failed" produces a confident non-fix. Keep the repair loop bounded — three attempts, then escalate to a human — because models can also chase a broken assumption in circles.

Where generated code reliably goes wrong

Certain failures recur across models and years. Invented APIs: the model imports a module that almost exists, or calls a plausible method that was never added — pin dependency versions in context and verify imports mechanically. Shallow error handling: generated code catches exceptions and swallows them, because swallowing looks tidy; require explicit failure behaviour in the contract. Silent incorrectness on edge cases: empty inputs, unicode, None values, and large inputs are exactly where a confident implementation breaks, which is why property-based tests pair so well with generated code. And over-engineering: given a short task, models frequently produce abstractions, base classes, and configuration options nobody asked for, adding surface area that must be maintained.

The counterweight is the same in every case: give the model the real context, execute the real tests, and keep a human on the merge.

Common Mistakes

Accepting generated code that has never been executed

Fix: Run the tests and a linter in a sandbox before the code reaches review; syntax validity proves nothing.

Prompting with a one-line feature request and no surrounding code

Fix: Include the files it must fit into so imports, naming, and error conventions match.

Sampling with high temperature to get more creative code

Fix: Near-deterministic decoding for completion, and sample only when you want competing candidates.

Letting the repair loop run without a cap

Fix: Bound retries, then hand the failure to a human with the full error output.

Best Practices

  • State negative requirements explicitly: what must raise, what must not be silently ignored.
  • Require a doctest or example call so the model commits to observable behaviour.
  • Evaluate with pass@1 and pass@k together to see both reliability and capability.
  • Track generated-code acceptance rate per repository; a drop usually means context assembly regressed.

Key Takeaways

  • Syntax fluency is not correctness: fitting an existing codebase is what code models are really graded on.
  • Completion, fill-in-the-middle, and instruction-to-code are different tasks with different prompting needs.
  • Whitespace-significant syntax is where tokenization hurts most, and it shows up as structural rather than line-level bugs.
  • Pass@k separates capability from reliability; measure both before trusting a model in a pipeline.
  • Tests, bounded feedback repair, and human review are what turn generations into mergeable changes.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement