Skip to content
ImagineWorld

Generating Python code

node_idnode-book_build-small-language-model_chapter-07-generating-python-code
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleGenerating Python code
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Part 3

Real-world use cases

T he two chapters in this part of the book get hands-on with real-world examples of SLMs specialized in Python code generation, protein structure generation, antibody generation for a target antigen, and crystal structure file generation. Examples in these chapters include performance assessment, model profiling, quantization, and validation.

7 Generating Python code

This chapter covers

  • The role specialized open source LLMs play in code generation
  • Optimizing and quantizing these LLMs to improve inference performance
  • Running these LLMs on a laptop after 4-bit quantization

In this chapter, we’ll apply the concepts covered so far to real-world, domain-specific LLMs, including optimization and quantization. We’ll focus on models tuned for Python code generation and programming assistance. Although most open source models in this category support multiple languages, we’ll use Python so you can readily judge the quality of the outputs.

Beyond closed-source, proprietary LLM-based code assistants, several popular open-source LLMs designed for coding tasks have been released. In this chapter, we’ll get into hands-on experimentation with some of these options, look at their pros and cons, and see how to optimize and, if needed, quantize them to run inference on commodity hardware (ideally on our laptops) while maintaining good performance. First, though, we’ll consider the present and future of human programmers in this era of coding assistants.

Given the availability of commercial and open-source copilots, many CEOs and other executives have predicted the obsolescence of programmers in favor of prompt engineers, or claimed that everyone (whatever their background) will become a software architect. How true is that? Let’s start with large generalist models. Several research efforts, such as SWE-bench (https://arxiv.org/abs/2310.06770), evaluate large commercial models such as GPT-4 and Claude 2 on real-world programming challenges based on real code. The paper focuses on Python (2,294 issues and related pull requests from GitHub repositories), but many benchmarks for other languages can be found online. Neither model scored well on these problems, even with knowledge retrieval. More prompt engineering helps little: even with a larger context, results can still be confused or random, at the cost of more processing power and the user’s time. Since the paper’s publication, many large and small models, with or without retrieval-augmented generation (RAG), have been benchmarked. The updated leaderboard is available at https://www.swebench.com/ (updated every Monday). Over time, new models and supporting techniques have improved results, but none of the benchmarked models can yet be used without expert human supervision (see figure 7.1).

dslm-fig-7.1-swe-bench-leaderboard.png

[!visual-conversion] Figure 7.1 — SWE-bench leaderboard (early 2025 snapshot) (p. 132)

SWE-bench Lite is a subset of SWE-bench that’s been curated to make evaluation more easily and more accessible (2025).

Several factors explain the modest performance. Resolving software engineering problems often requires coordinating changes across multiple functions, classes, and files, interacting with execution environments, and reasoning well beyond straightforward code generation. These are areas where humans still outperform ML models. And because these models are trained as generalists, they rarely match the depth of expertise that professional software engineers bring to complex programming tasks.

Dedicated models for programming tasks, such as Microsoft Copilot, are often more accurate and can handle more complex work than general-purpose models. Still, they can be costly for some organizations and require human oversight and guardrails to prevent data leakage. They may also lack transparency about where their training data comes from. These tools raise the same privacy, IP, and safety concerns discussed earlier in this book, especially when they rely on large, closed models.

Luckily for us, LLMs specialized for this kind of task are available, and specialization drastically reduces model size. We can see this in the industry’s growing move toward smaller, more focused coding LLMs that, despite having only a few billion parameters, match, and sometimes outperform, larger models on evaluation benchmarks. This isn’t surprising: if the main task is coding in one or a few programming languages, you can remove much of the irrelevant knowledge in large generalist models. A smaller, more focused data pool is easier to keep relevant, cheaper to train, and less likely to inadvertently include copyrighted or unauthorized data.

Back to the main question: Will generative AI replace human programmers? Probably not, even if models reach 98% to 100% accuracy on coding tasks. Coding is only one part of software development. It also involves investing in new things, understanding users’ requirements and needs, translating ideas into something buildable, and polishing the result. These steps require human judgment and cannot be reduced to next-token generation. In my opinion, software engineers will not shift into roles focused mainly on reviewing and verifying AI-generated code, even if generative models become highly accurate. These models can still be a big help, and I wouldn’t discourage professionals from using them. But domain knowledge is always needed to use them well: a good software engineer can become a better software engineer using a code assistant, but someone with little or no software engineering knowledge will not. Software engineering isn’t different from other domains when it comes to support from AI-based assistants.

7.2 Generating Python code with a Transformer architecture

Section titled “7.2 Generating Python code with a Transformer architecture”

Let’s get started. We’ll use an open source, pretrained code-generation model as our baseline and see what we get.

The first open source pretrained model we’ll consider is Salesforce’s CodeGen (https://arxiv.org/abs/2203.13474). It uses a standard Transformer architecture for conversational program synthesis: each problem is solved interactively in multiple steps, each consisting of a natural-language specification from the user and a synthesized subprogram from the system. Although better open source coding models are available, including CodeGen 2.0 and 2.5, CodeGen is still a useful example for this class of specialized LLMs because it highlights architectural choices that can require extra work beyond the typical use of Hugging Face Transformers, ONNX, and related libraries.

CodeGen is conceptually comparable to OpenAI’s Codex, the model that was behind GitHub Copilot when Salesforce released its own proposal. It offers two families of pretrained models: multi, trained to generate code in six languages (C, C++, Go, Java, JavaScript, and Python), and mono, trained to generate Python only. Each family includes four sizes: 350M (350 million parameters), 2B (2.7 billion parameters), 6B (6.1 billion parameters), and 16B (16.1 billion parameters). To show CodeGen’s scale at release, figure 7.2 compares the largest model with other open or closed source LLMs for the same task available at the time.

ModelSize
CodeParrot1.5B
PolyCoder2.7B
InCoder6.7B
Codex12B
CodeGen16.1B

[!visual-conversion] Figure 7.2 — Comparing the most popular code assistant LLMs’ sizes when CodeGen was released (p. 134)

As mentioned earlier in this chapter, we are focusing only on Python code generation, so any reference to CodeGen models in this section refers to the mono family.

Inference with the 350M pretrained model is fast, even before optimization. Benchmarks on a single NVIDIA T4 GPU average 0.8 s for requests that generate fewer than 50 tokens and 0.9 s for requests that generate 50 to 250 tokens. Still, the 350M model isn’t suitable for production; later in this chapter, we’ll discuss the quality of the generated results.

The 2B model is a more robust candidate (as are the larger versions). This model family can generate code that uses not only Python’s standard library but also third-party open source libraries. Even so, the 350M version is a good choice for explaining the concepts covered in this chapter.

The first Colab notebook for this chapter contains a complete, end-to-end example of optimizing inference for CodeGen 350M mono. We’ll use this smaller model to show that even a few hundred million-parameter model leaves room for inference optimization, and the same ideas apply to the larger mono models.

All the CodeGen checkpoints (mono and multi) are available on the Hugging Face Hub and via the Transformers library, so we can download the pretrained model and its tokenizer as usual:

import torch
from transformers import AutoTokenizer, CodeGenForCausalLM
device = "cpu"
model_id = "Salesforce/codegen-350M-mono"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = CodeGenForCausalLM.from_pretrained(model_id).to(device)
model.eval()

The only difference here is the use of CodeGenForCausalLM, Hugging Face Transformers’ auto class for CodeGen models.

This example doesn’t require hardware acceleration. We’ll assume the model and data are loaded and running on CPUs. The small CodeGen mono model works as follows:

prompt = "def hello_world():"
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
generated_ids = model.generate(input_ids, max_length=12)
print(tokenizer.decode(generated_ids[0],
skip_special_tokens=True,
pad_token_id=50256))

Given a prompt with a descriptively named function definition, it generates the function body as follows:

def hello_world():
print("Hello World")

This is one way to prompt the CodeGen models. It’s the only approach that works well for the 350M model, though others are possible. With the 2B and larger CodeGen models, you can also use pure natural-language prompts (English only), like this:

Create bar chart with matplotlib

That will generate something like this:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# create a DataFrame
df = pd.DataFrame({'sales': [10, 5, 6, 9, 7],
'sale_of_sales': [20, 10, 15, 25, 30]})
# plot the bar chart
df.plot(kind='bar', figsize=(10, 6), color='blue')
# Add title and labels
plt.title("Sales")
plt.xlabel("Month")
plt.ylabel("Sales")
# show the plot
plt.show()

You can also use a single-line comment, like this:

# Create empty tensor with PyTorch

That will produce a result like this:

tensor = torch.empty(1, dtype=torch.float32)

If you use a multiline comment

"""
Create a basic web app with Dash
"""

you will get something like this:

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objects as go
app = dash.Dash()
app.layout = html.Div([
html.H1('Dash App'),
html.Div([
dcc.Dropdown(
id='dropdown',
options=[
{
'label': 'New York City', 'value': 'NYC',
'label': 'Montreal', 'value': 'MTL',
'label': 'San Francisco', 'value': 'SF'
},
value='MTL'
),
dcc.Graph(id='graph', animate=True)
])
@app.callback(
dash.dependencies.Output('graph', 'figure'),
[dash.dependencies.Input('dropdown', 'value')])
def update_figure(selected_dropdown_value):
print(f"Selected dropdown value: {selected_dropdown_value}")
return {
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': 'Montreal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
if __name__ == '__main__':
app.run_server(debug=True)

You can also generate a function body from just its definition (any name, even if it’s not very descriptive) and an inline comment, which the model uses to generate the code:

def increment_elements(int_list):
"""
Return list with elements incremented by 1
"""

This generates something like the following:

def increment_elements(int_list):
"""
Return list with elements incremented by 1
"""
for i in range(len(int_list)):
int_list[i]+=1
return int_list

These models can also verify code and run user-written or model-generated code on input data:

int_list=[1, 3, 5]
>>> print(len(int_list))

That generates the following:

int_list=[1, 3, 5]
>>> print(len(int_list))
3

You can also implement unit tests, given some code and a comment as the prompt:

def create_empty_array(n, m):
arr = np.zeros((n, m))
return arr
#Write unit test for create_empty_array()

The model will generate unit tests for the code, following the guidance in the comment:

self.assertEqual(create_empty_array(2,3), [[0,0,0],[0,0,0]])
self.assertEqual(create_empty_array(5,4), np.zeros((5,4)))
self.assertEqual(create_empty_array(6,7), np.zeros((6,7)))
self.assertEqual(create_empty_array(3,4), np.zeros((3,4)))

Based on what you learned in chapter 6, you might expect to use Optimum to convert this model to ONNX and then quantize it. That’s correct now, but until early 2024, the CodeGen architecture wasn’t supported in Optimum—it was added only recently. Let’s first use Optimum to export the CodeGen model to ONNX and quantize it; later, we’ll look at an alternative approach for cases where Optimum doesn’t support a model’s architecture.

With Optimum installed for ONNX Runtime, the model can be downloaded from the Hugging Face Hub and converted to ONNX automatically:

from optimum.onnxruntime import ORTModelForCausalLM
model_id = 'Salesforce/codegen-350M-mono'
model = ORTModelForCausalLM.from_pretrained(model_id,
export=True,
provider="CPUExecutionProvider"
)

We are using the Optimum ORTModelForCausalLM class because CodeGen is a causal LM. We also specified the ONNX execution provider (CPUExecutionProvider in this example) at download time.

We can then save the model to disk:

from pathlib import Path
onnx_path = Path("onnx")
model.save_pretrained(onnx_path)

It can be now quantized dynamically through the Optimum API, as explained in chapter 6:

from optimum.onnxruntime import ORTQuantizer
from optimum.onnxruntime.configuration import AutoQuantizationConfig
dynamic_quantizer = ORTQuantizer.from_pretrained(model)
dqconfig = AutoQuantizationConfig.avx512_vnni(is_static=False,
per_channel=False)
model_quantized_path = dynamic_quantizer.quantize(
save_dir=onnx_path,
quantization_config=dqconfig,
)

The ONNX-converted model is 1.33 GB; the 8-bit quantized version is 346.22 MB.

Now let’s benchmark execution performance and see whether ONNX conversion and quantization improved latency and throughput. We’ll run a few hundred inference cycles for each of the three models and compare the results.

To keep the code clean and readable, we’ll use a Transformers pipeline to run inference with each CodeGen model version under test. Here’s the code to create the vanilla model pipeline:

from transformers import pipeline, GenerationConfig
generation_config = GenerationConfig(
pad_token_id=50256,
truncation=True,
max_length=12
)
pipe = pipeline("text-generation",
model=model,
tokenizer=tokenizer,
generation_config=generation_config
)

We also need to implement two simple utility functions to collect metrics during benchmark execution for all three model versions. First, we define the track_infer_time function, which measures the duration of a single inference run and is applied across the full benchmark cycle:

from contextlib import contextmanager
from time import perf_counter
@contextmanager
def track_infer_time(time_buffer):
start_time = perf_counter()
yield
end_time = perf_counter()
time_buffer.append(end_time - start_time)

The second utility is the BenchmarkInferenceResult class, used to collect metrics across benchmarks:

from dataclasses import dataclass
@dataclass
class BenchmarkInferenceResult:
model_inference_time: [int]
optimized_model_path: str

The benchmark code for the vanilla CodeGen model is then quite simple:

from tqdm import trange
PROVIDERS = {
("cpu", "PyTorch CPU"),
}
results = {}
inference_runs = 200
for device, label in PROVIDERS:
time_buffer = []
for _ in trange(inference_runs, desc=f"Tracking inference time (PyTorch vanilla model)"):
with track_infer_time(time_buffer):
pipe(prompt)
results[label] = BenchmarkInferenceResult(
time_buffer,
None
)

The code to benchmark the ONNX version of this CodeGen model is the same as for the original model. The only differences are the model you pass to the pipeline (the ONNX-converted version) and the provider tags you use to calculate and display inference metrics:

PROVIDERS = {
("CPUExecutionProvider", "ONNX CPU"),
}

Figure 7.3 shows the average inference time across hundreds of runs for both model versions. All benchmarks were run on a free Google Colab VM without hardware acceleration (Intel Xeon CPU with two virtual CPUs and 13 GB of RAM).

Average inference time (ms) for each provider

ProviderAverage inference time (ms)
PyTorch CPU1186.192727
ONNX CPU957.865782

[!visual-conversion] Figure 7.3 — Average CPU inference time for the vanilla CodeGen model in PyTorch vs. its ONNX-converted version (p. 141)

On our hardware, converting to ONNX reduced average inference time from about 1186 ms to about 958 ms. Figure 7.4 compares the two model versions on the same benchmark, showing latency (average and percentiles) and throughput. Running inference in ONNX format reduced latency and increased throughput.

MetricPyTorch CPUONNX CPU
Average_latency (ms)1186.192727957.865782
Latency_P501086.817074930.258778
Latency_P751293.8021721004.383695
Latency_P901365.1622111049.166195
Latency_P951418.5349961059.449770
Latency_P992003.6403281079.141317
Throughput0.8430331.043988

[!visual-conversion] Figure 7.4 — Latency and throughput metrics for the CodeGen 350M mono vanilla model vs. its ONNX-converted version (p. 141)

Figure 7.5 shows a box plot of inference duration across 100 runs for both model versions under test; individual run times are also shown.

dslm-fig-7.5-box-plot-showing-inference-run.png

[!visual-conversion] Figure 7.5 — Inference run times for 100 runs with the CodeGen 350M mono vanilla model and its ONNX-converted version (p. 142)

In this box plot, we can see that after converting to ONNX and applying the related optimizations, the standard deviation is smaller than for the original model. After moving to ONNX, duration is more consistent across runs.

By repeating the benchmark with the ONNX-quantized model (after swapping the quantized model into the pipeline and setting the provider tags), we can see further improvements: about a 60% reduction in average inference time (see figure 7.6).

Average inference time (ms) for each provider

Average inference time (ms) for each provider

ProviderAverage inference time (ms)
ONNX CPU923.130653
ONNX Quant CPU372.388912

[!visual-conversion] Figure 7.6 — Average CPU inference time for the ONNX CodeGen model and its quantized version (p. 142)

Figure 7.7 compares the two versions of the ONNX model on the same benchmark in terms of latency (average and percentiles) and throughput.

MetricONNX CPUONNX Quant CPU
Average_latency (ms)923.130653372.388912
Latency_P50853.977321351.197858
Latency_P75942.409447418.963405
Latency_P901000.723633446.840175
Latency_P951103.220258453.199262
Latency_P991713.538410461.910913
Throughput1.0832702.685365

[!visual-conversion] Figure 7.7 — Latency and throughput metrics for the CodeGen 350M mono ONNX model and its quantized version (p. 143)

Running inference with the quantized ONNX model reduced latency and increased throughput compared with the same benchmark on the vanilla CodeGen model.

NOTE All the figures in this section were generated with the open source Plotly library for Python (https://plotly.com/python/). I chose Plotly not only for its elegant visualizations compared with Matplotlib, but also for its built-in interactivity. The full source code for the CodeGen benchmarks and the visualizations in this section is available in the accompanying Colab notebook.

We’ve seen that exporting a model to ONNX and/or an ONNX-quantized version can significantly improve latency and throughput, even for small language models. But how do we assess how optimization and quantization affect the quality of the generated code? Section 7.2.3 will explore strategies for evaluating language model output for Python code generation.

7.2.2 Using ONNX with models not supported by Optimum

Section titled “7.2.2 Using ONNX with models not supported by Optimum”

Some LLM architectures aren’t yet supported by the Optimum package (for example, CodeGen models were still unsupported as of early 2024). In those cases, you can use the mid-level approach for ONNX quantization. After downloading a model from the Hugging Face Hub and saving it to disk, run the transformers.onnx script from the Transformers library as follows:

!python -m transformers.onnx —feature “causal-lm” —framework pt -export_with_transformers —model=local-pt-checkpoint onnx/

The —feature option sets the model category (causal-lm for CodeGen models; see the Transformers documentation for other models). The —model option specifies the directory where the downloaded checkpoints are saved.

After conversion, you can perform 8-bit quantization using the ONNX Runtime API;

import os
import onnx
from onnxruntime.quantization import quantize_dynamic, QuantType
def quantize_onnx_model(onnx_model_path, quantized_model_path):
onnx_opt_model = onnx.load(onnx_model_path)
quantize_dynamic(onnx_model_path,
quantized_model_path,
weight_type=QuantType.QInt8)
quantize_onnx_model(onnx_model_path, quantized_model_path)

Several open source Python packages, such as Hugging Face’s Evaluate and EleutherAI’s LLM Evaluation Harness (discussed in chapters 6 and 4, respectively), plus public datasets, are available for LLM evaluation. But generating unstructured outputs such as Python (or other) code calls for extra choices to make evaluation robust and meaningful.

In this section, we’ll walk through an approach based on the CodeGen 350M mono model and its ONNX-converted, 8-bit-quantized variants introduced in section 7.2.1, and which you can also apply to other LLMs specialized on Python code generation. The code comes from Amazon Science’s ReCode paper (https://arxiv.org/abs/2212.10264) and is shared in a Colab notebook for this chapter. I chose this approach because ReCode defines robustness metrics for code generation models by measuring worst-case behavior under different prompt perturbations (language models are sensitive to prompt changes). This provides a practical way to assess code quality for production use.

We’ll use OpenAI’s HumanEval evaluation dataset (https://github.com/openai/human-eval), introduced in “Evaluating Large Language Models Trained on Code” (https://arxiv.org/abs/2107.03374). HumanEval is also available on the Hugging Face Hub (https://huggingface.co/datasets/openai/openai_humaneval). It contains 164 Python programming problems, each with a function signature, docstring, body, and several unit tests. The comments and docstrings are in English. The dataset fields are as follows:

  • task_id—The identifier of the data sample
  • prompt—The input for the model, containing function header and docstrings
  • canonical_solution—A code solution for the problem in the prompt
  • test—A test function to validate the generated code for correctness
  • entry_point—The starting point for the tests

You can download this dataset via the Hugging Face Datasets API and then transform it into the format expected by the ReCode evaluation. Alternatively, you can download a ready-to-use JSON copy from the ReCode GitHub repo:

Terminal window
!mkdir -p datasets/nominal/
%cd ./datasets/nominal/
!wget https://raw.githubusercontent.com/amazon-science/recode/refs/heads/main/datasets/nominal/HumanEval.jsonl
%cd ../../

You can run the end-to-end evaluation on this test set with or without a GPU, but hardware acceleration is recommended. On an NVIDIA T4 GPU, the vanilla CodeGen 350M mono model takes more than an hour to run on all 164 test samples (adding the prompt to the answer and setting large maximum generation length). Because the full code is lengthy, we don’t include it here; instead, this section walks through the workflow so you can see how generated code is evaluated.

After downloading the CodeGen 340M mono model and its tokenizer from the Hugging Face Hub, split the HumanEval.JSON samples into individual JSON files, each containing the prompt for a single generation run. For each sample, first tokenize the prompt with the CodeGen tokenizer. Then generate code using the following configuration:

from transformers import GenerationConfig
generation_config = GenerationConfig(
pad_token_id=50256,
truncation=True,
max_length=1000,
max_context_length=1000,
use_cache=True,
return_dict_in_generate=True,
output_scores=True
)

After generating the code for a sample, we need to check that it is valid Python. Results that fail validation are not written to the results file. For this check, we use Python’s built-in ast package to parse the generated code into an abstract syntax tree (AST), as Python does before compiling to bytecode.

To see what an AST looks like, consider this simple example. Suppose the prompt for the generative model is

def hello_world():

and the generated body for this function is

print('Hello world')

You can get the latter’s AST via the ast class’s method. In the Colab code, it’s called from is_valid_python:

import ast
def is_valid_python(code):
try:
try:
pared_code = ast.parse(code)
except SyntaxError:
return False
except Exception as e:
print("Exception: ", e)
return False
return pared_code

The returned AST for the generated code looks like this:

<ast.Module object at 0x000001458A1D3880>
{'body': [<ast.Expr object at 0x000001458A22FA60>], 'type_ignores': []}
children: [<ast.Expr object at 0x000001458A22FA60>]\n
<ast.Expr object at 0x000001458A22FA60>
{'value': <ast.Call object at 0x000001458A22FA30>, 'lineno': 1,
'col_offset': 0, 'end_lineno': 1, 'end_col_offset': 20}
children: [<ast.Call object at 0x000001458A22FA30>]\n
<ast.Call object at 0x000001458A22FA30>
{'func': <ast.Name object at 0x000001458A22FA00>, 'args': [<ast.Constant
object at 0x000001458A22F9D0>], 'keywords': [], 'lineno': 1,
'col_offset': 0, 'end_lineno': 1, 'end_col_offset': 20}
children: [<ast.Name object at 0x000001458A22FA00>, <ast.Constant
object at 0x000001458A22F9D0>]\n
<ast.Name object at 0x000001458A22FA00>
{'id': 'print', 'ctx': <ast.Load object at 0x0000014589ABBC70>,
'lineno': 1, 'col_offset': 0, 'end_lineno': 1, 'end_col_offset': 5}
children: [<ast.Load object at 0x0000014589ABBC70>]\n
<ast.Constant object at 0x000001458A22F9D0>
{'value': 'hello world', 'kind': None, 'lineno': 1, 'col_offset': 6, 'end_
lineno': 1, 'end_col_offset': 19}
children: []\n
<ast.Load object at 0x0000014589ABBC70>
{}
children: []\n

In this case, there are six nodes in the tree. Generating an AST is a standard step in Python compilation. When you run a .py file, Python first converts the source to an AST and then to bytecode (a .pyc file). The Python virtual machine then interprets that bytecode. ASTs are also used for other purposes; for example, popular Python IDEs use them to parse files and understand code structure to power editor features. We can use ASTs in the same way to validate code generated by our LLMs.

After validating the generated Python code with an AST, we collect the results in a single JSON file to simplify evaluation. The final step depends on the HumanEval package, so we install it from source because it isn’t available through a Python package manager:

Terminal window
!git clone https://github.com/openai/human-eval
%cd human-eval
!pip install .
%cd ..

For each generated sample, we assess its correctness by executing the code and running its HumanEval test. As a safety measure to prevent malicious code execution, HumanEval comments out the line in execution.py that runs the generated code. In our Colab notebook, we override part of that code to enable the evaluation of code generated by our model. Use caution when running these evaluations.

We aggregate the results and save them to a JSON file along with the generated code. We also add a passed attribute with the value true or false.

Although the Colab notebook covers only the vanilla CodeGen 350M mono model, you can repeat the same evaluation process and code for its ONNX-exported and 8-bit quantized versions, and for other open source small language models for Python code generation.

7.2.4 Python code generation with better models

Section titled “7.2.4 Python code generation with better models”

When Salesforce released version 2.0 of the CodeGen models, it again offered the mono and multi families in four sizes each, roughly matching the first-generation sizes.

The latest generation is CodeGen 2.5, which comes in a single size—7 billion parameters for both the mono and multi versions. It features robust infill sampling (it can read text on both the left and right side of the current position), and it is optimized for fast sampling with FlashAttention, making it suitable for efficient serving and local deployment, including on personal machines. FlashAttention is an alternative to traditional self-attention that makes LLMs more efficient, enabling faster training and inference. Instead of repeatedly reading and writing keys, queries, and values from GPU HBM (large but relatively slow), it loads them once into SRAM (smaller but faster), fuses the attention operations, and then writes the results back.

All the CodeGen 1 and 2 models were released under the permissive Apache 2.0 license, and CodeGen 2.5 multi and mono use the same license. Note that the CodeGen 2.5 instruct model is available for research only, not for commercial use.

Generating Python code with the CodeGen 2.5 mono model works the same way as with the CodeGen 1 mono model discussed earlier in this chapter. First, download the model and tokenizer from the Hugging Face Hub:

from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "Salesforce/codegen25-7b-mono"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_id)

You can then generate code by invoking the generate method on the tokenized prompt:

text = "def hello_world():"
input_ids = tokenizer(text, return_tensors="pt").input_ids
generated_ids = model.generate(input_ids, max_length=128)
print(tokenizer.decode(generated_ids[0], skip_special_tokens=True))

As mentioned earlier, CodeGen 2.5 also works well for code infilling—filling in missing parts of an incomplete code snippet. It requires the prompt to follow this formatting convention:

  • Insert a <mask_1> token at the cursor.
  • Add a <sep> token to mark the boundary.
  • Insert another <mask_1> token to specify which mask to infill.

Here’s an example:

def format(prefix, suffix):
return prefix + "<mask_1>" + suffix + "<|endoftext|>"
+ "<sep>" + "<mask_1>"

Then generate the body of a Python function, as in the following example:

prefix = "def hello_world():\n "
suffix = " return greeting_message"

We need to format the prompt with our custom format function, tokenize it, and then invoke the model’s generate method:

text = format(prefix, suffix)
input_ids = tokenizer(text, return_tensors="pt").input_ids
generated_ids = model.generate(input_ids, max_length=128)
print(tokenizer.decode(generated_ids[0],
skip_special_tokens=False)[len(text):])

Other small language models for code generation have been proposed. One strong example is StarCoder2 (https://huggingface.co/bigcode/starcoder2-3b), a 3 billion-parameter model developed by BigCode, an open scientific collaboration focused on the responsible development and use of large language models for code, supported by ServiceNow, Hugging Face, and NVIDIA. Introduced in a 2024 paper (https://arxiv.org/abs/2402.19173), it was trained on 3+ trillion tokens from the Stack v2 dataset (https://huggingface.co/datasets/bigcode/the-stack-v2), covering code in 17 programming languages (including Python) plus curated natural language text from Wikipedia, arXiv, and GitHub issues. StarCoder2 uses grouped-query attention (proposed in a 2023 paper; https://arxiv.org/abs/2305.13245v3) to speed inference, and it has a 16,384-token context window with a 4,096-token sliding-window attention. Because it is not instruction-tuned, it is best suited to generating a function body when the function header is specified in the prompt, but the official GitHub repo (https://github.com/bigcode-project/starcoder2) includes tuning scripts.

You can generate code with StarCoder2 using Hugging Face packages in the usual way. First, download the model and tokenizer from the Hub:

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "bigcode/starcoder2-3b"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id,
device_map='auto',
torch_dtype=torch.bfloat16)
model.eval()

You can then generate code via the generate method of the AutoModelForCausalLM class on the tokenized prompt:

prompt = "def fibonacci(n):"
inputs = tokenizer.encode(prompt, return_tensors="pt").to(device)
outputs = model.generate(inputs)
print(tokenizer.decode(outputs[0]))

The Transformers pipelines are supported too:

from transformers import pipeline, GenerationConfig
generation_config = GenerationConfig(
do_sample=True,
use_cache=True,
temperature=0.2,
top_p=0.95,
max_length=12
)
pipe = pipeline("text-generation",
model=model,
tokenizer=tokenizer,
generation_config=generation_config)
result = pipe(prompt)
print(result[0]['generated_text'])

You can create an 8-bit quantized version of the model with Hugging Face’s Bitsandbytes library:

from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(load_in_8bit=True)
model_id = "bigcode/starcoder2-3b"
tokenizer = AutoTokenizer.from_pretrained(model_id)
quantized_model = AutoModelForCausalLM.from_pretrained(model_id,
quantization_config=quantization_config)
quantized_model.eval()

It is possible to make a 4-bit quantized version of the model the same way, just replacing the second line with the following:

quantization_config = BitsAndBytesConfig(load_in_4bit=True)

The companion Colab notebook for this chapter benchmarks inference performance for BF16 and 8-bit quantized versions of the StarCoder v2 3B model. The benchmark code is similar to the CodeGen example shown earlier, so I haven’t repeated it here. When you run the benchmark on a GPU, you’ll see that (thanks to the grouped-query attention implementation) the model delivers better throughput and latency than the CodeGen 350M and 2B mono models.

7.3 Coding assistance on commodity hardware

Section titled “7.3 Coding assistance on commodity hardware”

The CodeGen and StarCoder models discussed in section 7.2 showed good inference performance (with room for further optimization), making them suitable for deployment behind an API to enable code generation from client applications. It would also be useful to have one of these models running smoothly on a laptop as a coding assistant. In this section, we’ll verify an optimized small language model to run locally as a code assistant with acceptable performance. Our target laptop is a MacBook Air with an Apple M1 chip and 8 GB of unified memory. I chose one of the less powerful Apple M-series laptops to make things more challenging and to show that, even with this hardware, you can optimize inference and run useful, domain-specific SLMs smoothly. Our reference model will be StarCoder v2 3B.

If you browse the Hugging Face Hub, you’ll find several LLMs (including StarCoder v2 3B) already available in GGUF format. A natural way to try one of these quantized models for laptop inference is to use the Transformers API, just as you would with a standard FP32 or FP16 model:

from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "second-state/StarCoder2-3B-GGUF"
filename = "starcoder2-3b-Q2_K.gguf"
tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)
model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)

The only difference here is the filename of the quantized model checkpoint to download. GGUF offers multiple quantization options, so several quantized versions of the same model may be available.

Although the Hugging Face Hub can host GGUF models, and the Transformers library can download them, Transformers still can’t use models in quantized GGUF format. After a GGUF download completes, the model is automatically unquantized, and inference can run only in the original format. That puts us back at the start, because the original model is typically too large to run locally with limited CPU/GPU and memory.

The only workaround, if we want to go through the Transformers API, is to save the model to disk after downloading:

model_checkpoint_dir = 'starcoderv2-checkpoint-dir'
tokenizer.save_pretrained(model_checkpoint_dir)
model.save_pretrained(model_checkpoint_dir)

We can then apply a quantization technique to it.

But there are smarter options. llama.cpp (https://github.com/ggerganov/llama.cpp) is an open source C/C++ library and project that enables inference for several LLMs on a wide range of hardware, including devices without a GPU (such as laptops and mobile phones). GGUF is the binary file format used by llama.cpp.

To keep things simple, we will use llama-cpp-python (https://github.com/abetlen/llama-cpp-python), which provides Python bindings for llama.cpp and supports Apple’s Metal (MPS, Metal Performance Shaders) backend. To install it, you need Python 3.8+ and a C compiler for your machine (for example, Xcode on macOS). After creating a virtual environment, you can install llama-cpp-python from PyPI:

Terminal window
CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python

The preceding command builds and installs the library, including building and installing llama.cpp. You’ll also need the huggingface-hub library to download the model:

Terminal window
pip install huggingface-hub

Now that everything is set up, we can start coding to make the model available for local inference. First, we’ll import the required dependencies:

from huggingface_hub import hf_hub_download
from llama_cpp import Llama

Then we can download the model from the Hugging Face Hub:

model_name = "second-state/StarCoder2-3B-GGUF "
model_file = "starcoder2-3b-Q4_K_M.gguf "
model_path = hf_hub_download(model_name, filename=model_file)

The GGUF-converted model used in this example is Second State’s 4-bit K_M-quantized version of StarCoder v2 3B (https://huggingface.co/second-state/StarCoder2-3B-GGUF). After downloading it to your laptop, you can load it into memory using the llama-cpp-python library’s Llama class, as follows:

llm = Llama(
model_path=model_path,
n_ctx=3072,
n_threads=4,
n_gpu_layers=0
)

We’ve specified the local path to the model checkpoints, the context size (3,072 for StarCoder v2 3B), the number of CPU cores to use, and how many model layers to offload to the GPU (none in this example, since we want to run inference on the CPU only).

Next, we can set arguments for code generation, such as the maximum number of new tokens, a stop policy, whether to echo the prompt in the output, the decoding strategy, and other inference options:

generation_kwargs = {
"max_tokens": 20,
"stop": ["</s>"],
"echo": False,
"top_k": 1
}

Now we can set a prompt and run inference:

prompt = "def hello_world():"
res = llm(prompt, **generation_kwargs)

The preceding command outputs a dictionary in an OpenAI-compatible format:

{
"id": "cmpl-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"object": "text_completion",
"created": xxxxxxxxx,
"model": "./models/starcoder2-3b-Q4_K_M.gguf",
"choices": [
{
"text": "\n return 'Hello World!\n\n'",
"index": 0,
"logprobs": None,
"finish_reason": "length"
}
],
"usage": {
"prompt_tokens": 5,
"completion_tokens": 20,
"total_tokens": 25
}
}

To return only the generated text and omit the other response fields, use this command:

print(res["choices"][0]["text"])

The first time you run this code, it will be slower because it must download the model checkpoints locally. After that first run, you can generate code completely offline.

You can benchmark this local model’s performance the same way you did for the CodeGen models. Repeat the inference tests with the same configuration used for the smaller models, and you’ll see latency and throughput results like the following:

GGUF 4-bit K_M
Average_latency (ms) 432.545684
Latency_P50 432.409188
Latency_P75 436.077177
Latency_P90 438.191962
Latency_P95 438.622171
Latency_P99 440.215217
Throughput 2.311895

The overall performance (using only four threads and no GPU) is comparable to the 4-bit quantized CodeGen model, which is acceptable for local use. You can evaluate the generated code as explained in section 7.2.3.

So far, we’ve run inference from the CLI by executing a Python script with a prompt. You can also run in chat mode (llama-cpp-python provides an API for this). The library also includes a web server, so you can use llama.cpp-compatible models with any OpenAI-compatible client. This mode makes local models easy to integrate with an IDE for code completion and suggestions.

In this section, we’ve assumed the code-generation model we need is available from the Hugging Face Hub in GGUF format. But what if the model you want is available only in single or half precision, or it’s available in GGUF but the performance isn’t great? In those cases, after you’ve downloaded the source model checkpoints and supporting files locally, you can quantize the model and convert it to GGUF using the convert_hf_to_gguf.py script in the llama.cpp GitHub repo:

Terminal window
python llama.cpp/convert-hf-to-gguf.py <checkpoints_dir> --outfile
<output_file_name>.gguf --outtype <quantization_type>

The script requires the directory for the downloaded model checkpoints and files, a name for the target GGUF file, and the quantization type (see the llama.cpp docs for options). You can also upload the resulting GGUF model to the Hugging Face Hub. After quantization, repeat the steps from earlier in this section to generate code locally.

  • Specialized open source code-generation models can match generalist performance with fewer parameters.
  • CodeGen models support multiple programming languages, including Python-only code generation via the mono family.
  • Converting code generation models to ONNX can reduce average inference time by about 19% compared to standard PyTorch implementations.
  • 8-bit quantization of ONNX models can cut inference time by an additional 60% without sacrificing quality.
  • Models not supported by Optimum need a mid-level conversion with the transformers.onnx package and configuration by hand.
  • Abstract syntax tree (AST) parsing checks that generated Python code is syntactically correct before execution.
  • The HumanEval dataset contains 164 Python programming problems for evaluating code-generation models.
  • Code generation models support prompts such as function signatures, natural-language comments, and multiline docstrings.
  • StarCoder2 uses grouped-query attention to speed up inference while reducing computational overhead.
  • llama-cpp-python provides Python bindings for running GGUF models locally without a GPU.
  • Code infilling needs mask and separator tokens so the model understands the context.
  • 4-bit quantization cuts model size by about 75% while preserving acceptable code-generation quality.
  • Deploying code-generation models locally provides offline coding help without external APIs.
  • Apple’s Metal Performance Shaders (MPS) backend optimizes inference on Apple Silicon processors.
  • Evaluating code generation requires both syntactic validation and unit tests for functional correctness.
  • The ReCode evaluation framework provides robustness metrics for code generation under different prompt perturbations.