Models that read source code are easy to fool. Renaming a variable or inserting a block of code that never runs can flip a vulnerability detector or a type predictor, even though the program's meaning is unchanged. The standard remedy, adversarial training, retrains the model on these worst-case edits. For code, it barely helps. On type inference, adversarial training alone raised robustness by only 0 to 7 points. Robustness moved substantially, from 52.1% to 67.0%, only when the program's syntax tree was also pruned to its task-relevant parts. That pruning was done by solving an integer program for every sample (Adversarial Robustness for Code).
This note proposes a cheaper, principled replacement for that pruning step. We would score each subtree of a program's syntax tree by how much it inflates the complexity of a tree-kernel similarity matrix, and then remove the highest-scoring subtrees. A tree kernel is a similarity measure that counts shared tree fragments between two programs. Pruning would run inside the adversarial training loop. As the attacker edits trees, the scores would be updated incrementally with the substructure caching developed for fast tree kernels, rather than recomputed from scratch. In two sentences, the idea is this. Adversarially inserted code has to pull a program toward the wrong label in structural-similarity space, so it should appear as a subtree whose removal sharply changes a kernel-complexity measure. Measuring this cheaply enough to use at every training step could supply the structural pruning that code adversarial training is known to need, without a solver.
Core Claim
We claim three things. First, a kernel-complexity score computed on abstract syntax trees (ASTs, the parser's tree representation of a program) can stand in for per-sample integer-program pruning. Second, used inside adversarial training, it should recover most of the robustness of the full pipeline of Bielik and Vechev at a fraction of the cost. Third, it should generalize better than attack-specific retraining to attack families not seen in training.
The closest work is KCES. KCES computes a kernel-complexity quantity from the Gram matrix of a two-layer graph network, using pseudo-labels from K-means. It prunes edges whose removal changes that complexity most, and it lifts Cora accuracy under Metattack to 82.99% from 53.12%. KCES differs from our proposal in four ways. It is training-free, it runs only as a preprocessor, it works on flat attributed graphs, and it was never tested on code. We move the idea to rooted ordered trees and to tree-fragment kernels, place it inside a minimax training loop, and make it tractable on dynamically changing inputs.
Method
Let $\phi(T)$ be the feature vector of a tree $T$ under a tree-fragment kernel. It counts contiguous paths and subtrees. From the typology in Mapping kernels for trees, we pick a path or tree shape with the contiguous constraint, because these scale quadratically rather than cubically. We approximate the kernel with $m$ landmark training trees, so that $\phi$ becomes an explicit $m$-dimensional vector. For a minibatch with Gram matrix $K$ and label vector $y$, define the complexity
$$C(K, y) = y^\top (K + \lambda I)^{-1} y,$$
where $\lambda > 0$ is a ridge constant. This is the norm of the kernel ridge interpolant, the quantity that governs kernel-model generalization bounds. It plays the same role as graph kernel complexity in KCES.
The score of a subtree $s$ in tree $T_i$ is $|C(K, y) - C(K^{(-s)}, y)|$. Here $K^{(-s)}$ is the Gram matrix after removing the fragments that $s$ contributes to $\phi(T_i)$. Removing $s$ changes a single row and column of $K$, so the score needs only a rank-two update to the inverse, not a full recomputation. At test time labels are unknown. Following KCES, we substitute the model's predicted label as a pseudo-label. We then prune the top $k\%$ of subtrees and abstain when the largest score exceeds a threshold calibrated on training data, in the spirit of the abstention used by Bielik and Vechev.
The complexity side of the work is to make these scores cheap under adversarial edits. The Extract algorithm of Mapping kernels for trees builds a table of unique substructures once and reuses it. It reports a 36x speedup over top-down recursion on 442 glycan trees. The open question, flagged in the research file, is whether such a table can absorb adversarial tree edits without being rebuilt. We will build an incremental version. An edit touches only the fragments rooted on the path from the edit site to the root. The update therefore re-hashes that path, adjusts fragment counts, and applies the rank-two update to the Gram matrix.
This is also where the related work divides into three roles. Fast and Scalable Adversarial Training of Kernel SVM motivates the goal of scalable kernel adversarial training. It trains in 19.28 minutes versus 594.90 on CIFAR-10 pairs. It supplies no method for our setting, because its random Fourier features exist only for shift-invariant kernels on vectors, not for discrete tree kernels. The subcubic tree edit distance results of Faster Weighted and Unweighted Tree Edit Distance constrain the design. The speedups they prove are sub-polynomial and give little practical benefit below 1,000 nodes, so we deliberately avoid edit-distance computation in the inner loop.
Research Program
The work has three parts. The first is the incremental substructure table and the complexity score. We will measure wall-clock cost per training step against the integer-program refinement of Bielik and Vechev and against rebuilding the table from scratch. We expect the speedup over glycans to be smaller, because code ASTs are far larger than 13.5-node sugar trees. Devign had to discard functions above 500 nodes, and we will report scaling up to and beyond that size.
The second part is a minimax loop. The attacker perturbs the tree and the pruner removes high-score subtrees. The model, a gated graph neural network for type inference or GraphCodeBERT with pruned token spans masked, is trained on the pruned adversarial tree. The attackers are optimized obfuscations with alternating optimization and randomized smoothing from Generating Adversarial Computer Programs using Optimized Obfuscations, and mined dead-code patterns from GraphCodeAttack.
The third part is analysis. We will check whether adversarially inserted subtrees actually concentrate in the high-score tail, as KCES found for adversarial edges. We will also test how the score behaves when the pseudo-label is wrong, which is exactly the case under a successful attack.
Baselines
The naive reference point is an undefended model trained on clean data. On JavaScript and TypeScript type inference, the gated graph network reaches 86.7% accuracy and 52.1% robustness (Adversarial Robustness for Code). On CodeXGLUE we use GraphCodeBERT on authorship attribution, where GraphCodeAttack reaches an attack success rate of 0.841 (GraphCodeAttack). We also use CodeBERT clone detection on BigCloneBench, at F1 96.5, and Devign defect detection, at 62.08% accuracy (CodeXGLUE).
The second baseline is adversarial training alone with the strongest attacker we have. This means alternating-optimization obfuscations, which gave about 16 points of robustness on Python summarization, or retraining on GraphCodeAttack patterns. It runs with the same attacker, the same number of attack steps, and the same epochs as our method. Beating it means higher robustness at matched clean accuracy.
The strongest existing method is the full pipeline of Bielik and Vechev: abstention, adversarial training, integer-program refinement, and a sequential ensemble. It reports 87.7% accuracy and 67.0% robustness on type inference. We will rerun it on their benchmark with identical attacks. We count our method as beating it if it matches 67.0% robustness within noise at substantially lower training cost, or exceeds it at equal cost. We report both the single-model and ensemble versions, because their ensemble costs about 10x training time.
A compiler-canonicalization baseline applies dead-code elimination and identifier normalization before adversarial training. It gets the same attacks and tuning budget. Two further baselines isolate the key ingredient. One prunes the same fraction of subtrees chosen at random. The other prunes the subtrees with the highest gradient saliency. A third ablation freezes the complexity scores computed before training instead of updating them incrementally. A fourth applies KCES unchanged to the AST viewed as a flat graph, which tests whether tree fragments matter. All baselines receive the same hyperparameter search budget, measured in GPU-hours.
Why not just…?
Why not just canonicalize the code with a compiler before training? This is the most serious threat. Alpha-renaming and elimination of trivially dead code neutralize the simplest attacks for free. Canonicalization cannot remove code guarded by opaque predicates, which are conditions a static analysis cannot prove false. It also cannot remove live but task-irrelevant code, which is what the integer-program refinement of Bielik and Vechev prunes. We will split attacks into those canonicalization removes and those it cannot. If canonicalization plus adversarial training matches our method on the second split, the kernel score adds nothing and we will say so.
Why not just run stronger adversarial training? Bielik and Vechev measured only 0 to 7 points from adversarial training alone. Srikant et al. do report about 16 points on summarization, but only against their own attack family. Our held-out-attack experiment, described below, tests whether that gain transfers to attacks never seen in training.
Why not just prune by saliency or at random? Saliency is computed by the very model being attacked. An attacker can therefore shape inserted code to look unimportant to it. The complexity score is instead computed from a fixed kernel over the training distribution. The matched-budget ablations settle this directly. KCES's own comparison, 82.99% against 75.28% for Jaccard pruning on Cora, suggests that structure-aware scores beat local heuristics, but that result comes from graphs, not code.
Proposed Experiments
The first decisive check replicates the type-inference benchmark of Bielik and Vechev. Our method must reach at least two-thirds of the robustness gain of the integer-program pipeline (52.1% to 67.0%) with a single model and without per-sample solving. We will report training time per epoch for both.
The second check trains against obfuscation attacks and tests against GraphCodeAttack patterns, and vice versa, on authorship attribution and Devign. The prediction is that complexity pruning degrades less than attack-specific retraining on the unseen family. That outcome would address the overfitting weakness of adversarial training.
The third check is an adaptive attacker who knows the pruning rule. This attacker adds a penalty on the complexity score of inserted code to the objective. If robustness collapses under the adaptive attack, the method is obfuscation rather than defense. Such a collapse would be the clearest reason to abandon the idea.
Throughout, we will report clean accuracy, robustness or attack success rate, abstention rate, and cost per step. We will also report the fraction of inserted subtrees caught in the top $k\%$ of scores, which directly tests the mechanism.
References
- Adversarial Robustness for Code
- KCES: Training-Free Defense for Robust Graph Neural Networks via Kernel Complexity
- Mapping kernels for trees
- Fast and Scalable Adversarial Training of Kernel SVM via Doubly Stochastic Gradients
- Faster Weighted and Unweighted Tree Edit Distance and APSP Equivalence
- Devign: Effective Vulnerability Identification by Learning Comprehensive Program Semantics via Graph Neural Networks
- Generating Adversarial Computer Programs using Optimized Obfuscations
- Adversarial Attacks on Code Models with Discriminative Graph Patterns
- CodeXGLUE: A Machine Learning Benchmark Dataset for Code Understanding and Generation