Experience
Projects
My Stack
Case studies
Contact me
Open my CV

·8 min read

Teaching CodeT5 to read renamed Python: a deobfuscator experiment

I wanted to know whether a small model could make renamed Python readable again, the way you want it when you inherit a minified or machine-renamed file you are allowed to audit. So I built the whole loop myself: a dataset, a synthetic obfuscator, a CodeT5 fine-tune, an evaluation script and a first-pass safety report. The honest result is a working pipeline and modest scores, plus one bug in my own data that taught me more than the model did.

Role
Creator and sole developer
Period
Jul 2025
Status
Experiment, one commit (27f5234, Jul 2025), no released model or weights in the repo
Stack
Python, PyTorch, Hugging Face Transformers, CodeT5, YARA, Bandit

The challenge

Obfuscated code removes the one thing a reviewer relies on: names. v41(v8, v17) tells you nothing, while train(train_dir, model_save_path) tells you a lot. I wanted to see how far a seq2seq model gets at restoring that information when the only training signal is pairs of renamed and original code.

There is no public set of such pairs that I could trust for this, so the challenge was really three problems in a row: make the data, make the training fit on a consumer GPU, and measure the result without fooling myself.

My responsibility

I did all of it alone, in one notebook and a handful of scripts:

  • Choosing the source corpus and cutting it into 10,000 snippets.
  • Writing the obfuscator that produces the training inputs.
  • Building the Hugging Face dataset, the training script and its loss tracking.
  • Writing the per-example evaluation and the metric plots.
  • Writing a separate checker that inspects the recovered code for risky constructs.
Note. The intended use is understanding and analysing code you have the right to inspect: your own legacy code, vendor code under an audit agreement, or samples in a lab. The model only rewrites text. It does not run anything.

How I approached it

extractreadpair up90/10 splitgenerategeneratecode-search-net-pythonfirst 10,000 snippetsclean_snippets10,000 .py filesobfuscate_coderegex rename to v0, v1, ...deobfuscation_dataset.jsonobfuscated + clean pairsCodeT5-small fine-tune5 epochs, fp16evaluate_model.pyBLEU, ROUGE per examplemalicious_checker.pykeywords, YARA, Bandit
Figure 1. The pipeline from public Python corpus to a reviewable report.

Building the pairs

The notebook loads Nan-Do/code-search-net-python, writes the first 10,000 functions to clean_snippets/, obfuscates each one into obfuscated_snippets/, joins the two folders into deobfuscation_dataset.jsonl and converts that to a Hugging Face dataset with train_test_split(test_size=0.1). Both folders hold 10,000 files in the repo, so the split is 9,000 training and 1,000 test pairs by construction.

The obfuscator

The whole thing is a regex and a dictionary:

python
tokens = set(re.findall(r'\b[_a-zA-Z][_a-zA-Z0-9]*\b', code))
keywords = {'def', 'return', 'class', 'if', 'else', 'elif', 'for',
            'while', 'try', 'except', 'with', 'import', 'from'}
tokens = [t for t in tokens if t not in keywords and not t.startswith('__')]
obf_map = {name: f'v{i}' for i, name in enumerate(tokens)}

It is cheap and it gives the model a clear task: map v89 back to train_dir. The mapping is built per file from a set, so the same name gets different numbers in different files and the model cannot memorise a global dictionary.

Training on a single consumer GPU

train.py fine-tunes Salesforce/codet5-small with Seq2SeqTrainer: learning rate 3e-4, 5 epochs, batch size 16 with gradient accumulation of 2, fp16=True, gradient_checkpointing_enable() and a 512 token window. A small LossTrackerCallback drives a tqdm bar and saves loss_curve.png. trainer.train(resume_from_checkpoint=True) lets me stop and continue, which mattered on a machine I also used for other things.

Scoring and a first safety pass

evaluate_model.py generates a prediction for each test example, scores BLEU, ROUGE-1 and ROUGE-L per example and appends a row to eval_metrics_log.csv. malicious_checker.py then looks at the recovered code. It checks 19 substrings (eval, exec, subprocess, base64, pickle, ctypes and so on), one YARA rule and a Bandit run, and renders everything as malware_report.html.

Story moments

The run that promised 23 hours

My first training attempt used the older version of the script, which survives as slow.py: batch size 8, fp16 only if CUDA is available. The screenshot I kept in the repo (time_required.png, taskbar dated 14 Jul 2025) shows what happened: PyTorch warned that no accelerator was found, and the bar read 7/5625 [01:47<23:41:50, 15.19s/it]. 5,625 matches 9,000 examples times 5 epochs divided by a batch of 8.

I did not wait. I moved to a CUDA setup (the README mentions a GPU such as an RTX 3060 Ti, the pins in requirements.txt say torch==2.5.1+cu121, and doc.txt is a log of my pip attempts at transformers 4.41.1 and 4.39.3 before settling on 4.37.2). I read the next screenshot as that GPU run, since the speed jumps about thirteen times (process_time.png). It shows 844/1405 [18:59<10:57, 1.17s/it], which is 1,405 steps for the larger effective batch. Nineteen minutes elapsed plus eleven to go puts the whole run near half an hour.

# time_required.png, CPU only, batch size 8
$ python train.py
7/5625 [01:47<23:41:50, 15.19s/it]
# process_time.png, GPU, batch 16 x 2
844/1405 [18:59<10:57, 1.17s/it]
{'eval_loss': 0.6858, 'eval_rouge1': 0.0854, 'eval_rougeL': 0.0768, 'epoch': 2.0}

The same screenshot shows the epoch 2 evaluation: loss 0.6858 but ROUGE-1 only 0.0854. At that point the loss looked healthy and the generated text did not, which is exactly why I wrote a separate per-example evaluation.

The obfuscator that broke the syntax

When I opened obfuscated_snippets/snippet_0.py next to its clean twin, the problem was obvious. The original line:

python
for class_dir in os.listdir(train_dir):
    if not os.path.isdir(os.path.join(train_dir, class_dir)):

became:

python
for v11 v64 v19.v137(v89):
    if v15 v19.v70.v27(v19.v70.v63(v89, v11)):

in turned into v64 and not into v15. The keyword set only covered 13 words, so in, not, as, is, None, and, or, lambda and pass were all renamed like ordinary variables. The regex also rewrites docstrings, comments and string literals, because \b matches words anywhere ('wb' became 'v10').

So the model was not learning to undo realistic obfuscation. It was learning to repair a broken word-substitution scheme. That does not make the experiment useless, but it changes what the scores mean: they measure recovery from my synthetic noise, not from tools people actually use. The fix is straightforward (use the keyword module and the tokenize module so only real identifiers change), and I have not made it in this repo.

Reading the target labels

While tracing tok_targets I noticed one more thing. The labels are copied straight from input_ids of a padding="max_length" tokenization, so padding tokens stay in the labels instead of being replaced by -100. compute_metrics does handle -100 on the way out, but nothing puts it in. By reading, that means the loss counts padded positions. I did not retrain to measure the effect, so I list it as a suspect rather than a finding.

Project journey

  1. Jul 2025

    Dataset

    10,000 snippets from code-search-net-python, split 90/10

  2. Jul 2025

    Synthetic obfuscation

    regex rename to v0, v1, ... per file

  3. Jul 2025

    First CPU run

    5,625 steps, 15.19 s/it, ETA 23:41:50 (screenshot, 14 Jul)

  4. Jul 2025

    GPU run

    1,405 steps at 1.17 s/it, epoch 2 ROUGE-1 0.0854

  5. Jul 2025

    Per-example evaluation

    740 rows in eval_metrics_log.csv

  6. Jul 2025

    27f5234

    initial commit, 16 Jul 2025, with the dataset and plots

Figure 3. The repo has a single commit, so the other dates come from my screenshots.

Beyond the launch

There was no launch: the repo is a lab notebook that happens to run. What came after is the checker, which I treat as the beginning of a workflow. malware_check.py loads the fine-tuned model, feeds it a test input, writes the output to a temp file, runs the keyword scan, YARA and Bandit, and renders the HTML. The test input is a made-up function with a base64 string and a subprocess.Popen call. The generated report in the repo flags subprocess, base64 and open(, the SuspiciousActivity YARA rule, and three Bandit messages.

I want to be fair about its limits. The keyword scan is substring matching, so evaluate matches eval and http matches almost anything. It produces a list of places to look at, not a judgement about intent. A real deobfuscation workflow also needs a deterministic step in front of the model, such as AST-based renaming, so that the model only has to guess names, not syntax.

The outcome

The numbers I can stand behind come from eval_metrics_log.csv:

BLEU

0score

ROUGE-1

0score

ROUGE-L

0score
Figure 4. Mean score over the 740 logged test examples.

The best single example reaches BLEU 0.665 and ROUGE-1 and ROUGE-L 0.764. The median ROUGE-L is 0.302, 51 examples score at least 0.5 and 144 score below 0.2. These are modest numbers. The rows are written by a thread pool in completion order, which is why model_eval_res.py sorts by Index before plotting.

What worked: an end to end pipeline that anyone can rerun from the notebook, a training loop that finishes in about half an hour on a single GPU, and a per-example log that lets me see where the model fails. What did not: the data generator, which is the first thing I would rebuild.

Read the notebook and the two training scripts, and tell me where you would fix the obfuscator first.

View on GitHub

Evidence

  • Repository: https://github.com/ddatunashvili/Deobfuscator (one commit, 27f5234, 16 Jul 2025).
  • Files I relied on: main.ipynb (dataset and obfuscator), train.py, slow.py, evaluate_model.py, eval_metrics_log.csv, malicious_checker.py, malware_check.py, malware_report.html, time_required.png, process_time.png.
  • Not verified: I did not retrain, and the trained weights are not in the repo (training wrote them to a drive outside it), so the scores come from the committed log only. The README names train_codet5_deob.py, which is not the file in the repo (it is train.py).

#python#machine-learning#codet5#code-analysis

Keep reading

Have a project in mind?