Code Understanding › Code Implementation: Bug Detection
Language AI HandbookAll chapters Code Understanding › Code Implementation: Bug DetectionSection view · Sections in this chapter6 / 13 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Let's implement a simple bug detection system using CodeBERT.
PythonIn [9]Expand
from transformers import RobertaForSequenceClassification, RobertaTokenizer
bug_model_name = "microsoft/codebert-base"
bug_tokenizer = RobertaTokenizer.from_pretrained(bug_model_name)
bug_model = RobertaForSequenceClassification.from_pretrained(
bug_model_name, num_labels=2
)
bug_model.eval()PythonIn [10]Expand
def detect_bug_score(code_snippet: str) -> float:
"""Return a defect probability score for a code snippet."""
inputs = bug_tokenizer(
code_snippet,
return_tensors="pt",
max_length=512,
truncation=True,
padding=True,
)
with torch.no_grad():
logits = bug_model(**inputs).logits
probs = torch.softmax(logits, dim=-1)
return probs[0, 1].item()PythonIn [11]Expand
code_pairs = [
{
"name": "Off-by-one in loop",
"buggy": """\
def sum_array(arr):
total = 0
for i in range(len(arr) + 1):
total += arr[i]
return total""",
"fixed": """\
def sum_array(arr):
total = 0
for i in range(len(arr)):
total += arr[i]
return total""",
},
{
"name": "Missing null check",
"buggy": """\
def get_length(s):
return len(s)""",
"fixed": """\
def get_length(s):
if s is None:
return 0
return len(s)""",
},
]
scores = []
for pair in code_pairs:
buggy_score = detect_bug_score(pair["buggy"])
fixed_score = detect_bug_score(pair["fixed"])
scores.append(
{
"name": pair["name"],
"buggy_score": buggy_score,
"fixed_score": fixed_score,
}
)ConsoleOut [12]Expand
Scenario Buggy Score Fixed Score Correct? ----------------------------------------------------------------- Off-by-one in loop 0.6104 0.6094 yes Missing null check 0.5974 0.6025 no
The base CodeBERT model without defect-specific fine-tuning assigns similar scores to both variants. In practice, a fine-tuned checkpoint trained on the Devign or CodeXGLUE defect datasets assigns clearly higher scores to the buggy variants. The structure of the pipeline is the same; only the weights change.
VisualizationOut [13]Expand

The chart makes the lack of discrimination visible. An effective detector would show clearly taller buggy bars for every scenario, but these gaps are tiny and the missing-null-check pair is reversed. Defect-specific fine-tuning is what turns the pairwise score gap into a useful signal.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!