Semantic Robustness of Source Code ModelsSemantic Robustness of Models of Source Code
The authors propose a k-transform robustness and adversarial training method for code models, and claim that on the code summarization task it improves the model's robustness to semantics-preserving transformation attacks.
The attacker (k-adversary) can select k transformations from a predefined set T of semantics-preserving transformations to form a sequence applied to the input program; some transformations take parameters. An attack is defined as successful if it changes the neural network's prediction. Attacks are performed at test time; gradient attacks require model gradients (white-box-style access), while random attacks only fill parameters randomly. The victim systems are code summarization models (seq2seq, code2seq).
- Neural networks on code (such as code summarization models) can have their predictions changed by semantics-preserving program transformations; the authors want to train models that are robust to such transformation sequences.
- Defines the k-adversary: enumerate k semantics-preserving transformations to generate a program sketch, then use a gradient method to fill the holes to maximize the loss; during training, sketches are pre-generated offline, and adversarial training is performed with a Madry-style robust optimization objective, while in practice only the weak k=1 adversary is used for training.
- On four Java/Python datasets and two architectures, seq2seq and code2seq, the authors state that adversarial training improved adversarial F1 under Q1G attacks (seq2seq up to +16.0, code2seq up to +7.9, Table 2), and that models trained with k=1 are also more robust to k=5 attacks.
- The authors state that future work could study other models such as graph neural networks and other code tasks (such as automatic refactoring); the experiments cover only the code summarization task, two architectures, and 8 transformations, and the Q5G evaluation randomly samples only 10 transformation sequences.
- Evaluated models
- seq2seqcode2seq
- Benchmarks
- c2s/java-smallcsn/javacsn/pythonsri/py150
- Metrics
- F1adversarial F1 (Q1R/Q5R/Q1G/Q5G)
The authors propose a semantics-preserving adversarial attack and adversarial training method for source code models, and evaluate robustness improvements across different programming languages and model architectures. The adversary defined by the authors can compose multi-step parameterized, semantics-preserving program transformations; the authors claim that their evaluation shows significant quantitative improvements in robustness.
Paper analysis
What problem does this paper attempt to solve?
The authors study the robustness of neural networks on code to sequences of semantics-preserving transformations, and propose a corresponding adversarial training method.
Core problem: whether code neural models can be trained to be robust to sequences of semantics-preserving program transformations.
- Problem setting: code models are being used for tasks such as code summarization (predicting the method name from the method body). The authors give an example: code2seq originally correctly predicts indexOfTarget on the Java code in Figure 1, but after adding a logging print statement the prediction becomes search; the authors also mention security scenarios such as malware classification.
- Difference from the image domain: the threat model for images is small perturbations imperceptible to humans, and code has no corresponding concept, so the authors adopt semantics-preserving transformations as the attack model—after transformation the program behavior must be the same as the original program.
- Shortcomings of existing work (as stated in the paper): Wang and Christodorescu only showed that transformations cause accuracy degradation and did not propose defenses; Yefet et al.'s attacks are limited to variable substitution or dead code insertion, and their defense is based on anomaly detection, without considering arbitrary transformations or adversarial training; Zhang et al. only do identifier renaming, and their defense is more like data augmentation than robust optimization.
- Threat model:
- Goal: change the neural network's prediction on the input program (untargeted, maximizing loss).
- Knowledge: gradient attacks require access to model gradients; random attacks only select parameters randomly.
- Capability: select k transformations from a predefined set T of semantics-preserving transformations to form a sequence applied to the program; the parameters of parameterized transformations (such as inserting print statements) are also chosen by the attacker.
- Victim system: code summarization models (seq2seq, code2seq).
- Paper proposes: a formal definition of k-transformation robustness, an implementation of the k-adversary (enumeration + gradient optimization), an adversarial training method based on robust optimization, and a scalable framework; the authors call this the first robust-optimization adversarial training method for code tasks.
What related research exists?
Related work covers three areas: attacks and defenses on code models, discrete adversarial attacks in NLP, and deep learning for code; there is also concurrent work by Bielik and Vechev.
Adversarial attacks and defenses for code models
- Wang and Christodorescu [35]—showed that standard transformations and refactoring cause accuracy degradation in deep code models; the paper notes that they did not propose a defense.
- Yefet et al. [37]—gradient attacks targeting variable name substitution or dead code insertion, and proposed a defense based on anomaly detection; the paper notes that they did not consider arbitrary program transformations or adversarial training. This paper's gradient fill-in-the-blank attack is adapted from that work.
- Zhang et al. [39]—used Metropolis-Hastings for adversarial identifier renaming; the paper notes that they did not consider other transformations, and that the defense is similar to data augmentation rather than robust optimization.
Concurrent work
- Bielik and Vechev [9] (concurrent work)—combined adversarial training, abstention, and AST pruning to train robust code models. The paper notes three differences: this paper's transformation space is richer (including parameterized dead code insertion); this paper uses a gradient attacker plus program sketches, whereas they use greedy search; this paper's training is more economical because it does not solve an ILP problem and does not train multiple models. A footnote in the paper states that this paper's preprint appeared earlier on arXiv.
Discrete adversarial attacks in NLP
- Word substitution and typo attacks such as HotFlip (Ebrahimi et al. [13]) [24, 26, 13, 40, 16]—this paper's gradient parameter search is of the same kind as HotFlip; the paper notes that the key difference between code and NLP is that after a program transformation the semantics must be preserved and the program must still work.
Deep learning for code and robust optimization
- AST path encoding in code2vec/code2seq (Alon et al. [4, 3]), and the token sequence model of Raychev et al. [29]—the sources of the two architectures tested in this paper; the code summarization task was proposed by Allamanis et al. [1].
- The robust optimization objective of Madry et al. [25]—this paper's adversarial training objective is adapted from it; the observation in vision and NLP that "training with a weak attacker suffices to defend against stronger attackers" [38, 25, 36, 18] is the basis for this paper's k=1 training design.
Baselines and benchmarks: the experimental baselines are normal training (Tr-Nor), data augmentation (Tr-Aug), and random-parameter adversarial training (Tr-Q1R); the benchmarks are the four code summarization datasets c2s/java-small, csn/java, csn/python, and sri/py150.
The authors position this paper as: considering a general attacker that can apply arbitrary sequences of parameterized transformations, and using robust optimization for adversarial training, rather than targeting only a single transformation or performing data augmentation.
How does the paper address this problem?
The authors define the k-adversary and k-robustness, implement the attack with "enumerate transformations + gradient hole filling", and then pre-generate sketches offline for adversarial training.
Overall approach: move the robust optimization objective of Madry et al. into the code domain—during training, minimize the worst-case loss caused by the k-adversary; control training overhead by pre-generating program sketches offline and training with only k=1.
Problem formalization
- A program is viewed as an AST, and a transformation t is a parameterized tree-to-tree function; only semantics-preserving transformations are considered; partially applying a transformation (without giving parameters) yields a program sketch—a program with holes at the leaves.
- The k-adversary's objective: maxq ∈ Qk L(w, q(x), y), i.e., maximize the loss over the set Q_k of transformation-and-parameter sequences of length k.
- Robust optimization objective: argminw E(x,y) maxq ∈ Qk L(w, q(x), y), i.e., minimize the worst-case loss caused by the k-adversary; a model satisfying this objective is called k-robust.
- The authors prove that the decision version of this maximization problem is PSPACE-hard (Appendix A, reduced from the DFA intersection emptiness problem), and contrast this with finding adversarial examples in the vision domain being NP-complete.
Implementation of the k-adversary (Algorithm 1)
- The search is split into two parts: enumerate transformation sequences t1..tk; for each sequence, partially apply it to obtain a sketch z[·], then use a gradient method to search for hole-filling parameters r.
- Gradient hole filling is adapted from Yefet et al.: first fill holes with a special token, replace the embedding lookup with multiplication of a one-hot vector and the embedding matrix to make the input layer differentiable, take a step in the direction of increasing loss, and take the token with the largest value in the updated vector as the replacement.
- Additional semantic constraints, e.g., different holes in a sketch must be filled with different replacement tokens.
Efficient adversarial training
- k=1 training: The enumeration overhead is |T|^k; the authors state that in practice training with k=1 suffices to remain robust to larger k, so each training point requires only |T| iterations; the authors state similar observations exist in vision and NLP.
- Offline pre-generated sketches: Transformations are defined on the AST while model inputs are token sequences or AST paths, and calling external analysis tools inside the training loop is expensive; therefore, before training, the full set of sketches Sx is pre-generated for each training program, and during training only the gradient attack on Sx is needed.
- Composite loss: To maintain performance on clean data, a composite loss λ·L + (1−λ)·Ladv is used, with λ=0.4 (selected by grid search).
- Periodic attack: The gradient attack is re-run to update hole filling every epoch for seq2seq and every two epochs for code2seq; for each mini-batch, one transformation with the highest loss over the whole batch is selected, rather than selecting the worst transformation per point.
Transformations and attacker variants
- 8 semantics-preserving transformations (Table 1, Appendix B): AddDeadCode, InsertPrintStatement, RenameField, RenameLocalVariable, RenameParameter, ReplaceTrueFalse, UnrollWhile, WrapTryCatch; all except UnrollWhile are parameterized, and each configuration produces only one hole.
- Two attacker variants: the random attacker QkR (random hole filling) and the gradient attacker QkG (gradient-selected parameters); Java transformations are based on Spoon, Python on Astor.
What experiments did the paper conduct?
Comparing 4 training methods on 4 code summarization datasets and 2 architectures, the authors state that Tr-Q1G has the best robustness under gradient attacks.
Experimental setup
- Task and metric: Code summarization (predicting the method name from the method body), with F1 as the metric; adversarial F1 refers to the F1 after each test point is attacked by the specified attacker.
- Models under test: seq2seq (2-layer BiLSTM, 512 units, based on the IBM implementation, trained for 10 epochs) and code2seq (the authors' official TensorFlow implementation, trained for 20 epochs); input/output vocabularies 15k/5k.
- Datasets: c2s/java-small, csn/java, csn/python, sri/py150; all have original sizes over 0.5M (Table 3), and for computational feasibility they are uniformly subsampled to train/validation/test = 150k/10k/20k.
- Training methods: Tr-Nor (normal training), Tr-Aug (data augmentation), Tr-Q1R (adversarial training with random parameters), Tr-Q1G (this paper's method, gradient 1-adversary).
- Attackers: Q1R, Q5R, Q1G, Q5G; because 8^5=32768 sequences are infeasible for Q5G, 10 sequences of length 5 are randomly sampled (Appendix C.5; Table 4 shows attack strength saturates when the number of samples increases from 10 to 50).
- Number of repetitions: Not reported in the paper.
Main results
Table 2: Normal F1 (Nor) and adversarial F1 under Q1G attack for the four training methods on the four datasets, with differences relative to Tr-Nor in brackets.
Swipe horizontally to read the table
Model Training c2s/java-small Q1G csn/java Q1G csn/python Q1G sri/py150 Q1G seq2seq Tr-Nor 23.3 17.2 16.2 22.0 seq2seq Tr-Aug 27.8 [+4.4] 21.4 [+4.3] 20.9 [+4.7] 24.0 [+2.0] seq2seq Tr-Q1R 27.5 [+4.2] 30.1 [+12.9] 29.8 [+13.5] 33.4 [+11.4] seq2seq Tr-Q1G 32.0 [+8.7] 32.8 [+15.6] 32.2 [+16.0] 37.1 [+15.1] code2seq Tr-Nor 24.6 19.6 21.0 23.7 code2seq Tr-Aug 23.4 [-1.2] 19.7 [+0.1] 20.8 [-0.2] 24.4 [+0.7] code2seq Tr-Q1R 28.1 [+3.5] 23.5 [+3.9] 22.5 [+1.6] 26.6 [+2.9] code2seq Tr-Q1G 31.6 [+7.0] 27.5 [+7.9] 23.8 [+2.8] 29.5 [+5.8] - The authors state that Tr-Q1G is more robust than all baselines under Q1G attack, especially on seq2seq; and state that averaged across datasets, the F1 gain of Tr-Q1G relative to Tr-Nor is about 6 (27%) (code2seq) and 14 (74%) (seq2seq).
- Exceptions: On code2seq, Tr-Aug is worse than Tr-Nor on c2s/java-small (-1.2) and csn/python (-0.2); on csn/python the gain of Tr-Q1G is only +2.8.
- On this basis the authors give an affirmative answer to Q1 (whether adversarial training improves robustness).
Robustness to the 5-adversary
- Table 5 and Figure 3 give results under the four attacks Q1R, Q5R, Q1G, Q5G; the authors state that Q1G is often stronger than Q5R, and that Tr-Q1G consistently outperforms Tr-Q1R under gradient attacks.
- Under Q5G attack all models degrade: e.g., on seq2seq, csn/java, Tr-Nor drops from 32.3 to 9.8 and Tr-Q1G from 37.8 to 29.7 (Table 5d); the authors state that the drop for Tr-Q1G is smaller.
- Appendix D states that except in one case, Tr-Q1G performs best under attack; from Table 5b, on c2s/java-small under Q5R, seq2seq Tr-Aug is 31.7, higher than Tr-Q1G's 31.3.
- On this basis the authors give an affirmative answer to Q2: k=1 training can improve robustness to k=5 attacks (limited to this combination).
Comparison of seq2seq and code2seq
- The authors state that code2seq has higher clean F1 but is similarly vulnerable, and the robustness gain from adversarial training is smaller: on the Python datasets under Q1G attack, the gap between Tr-Nor and Tr-Q1G is about 16 F1 points for seq2seq and only 2.8–5.8 for code2seq (Table 2).
- The authors speculate the reason is that code2seq makes predictions based on sampled AST paths, so a single transformation may affect multiple paths simultaneously.
Other ablations and analyses
- Single-transformation attacks (Table 1, normally trained models on c2s/java-small): the F1 drop caused by gradient attacks is mostly 2x–15x that of random attacks; InsertPrintStatement causes a drop of 10.2 for code2seq, and WrapTryCatch causes a drop of 9.4 for seq2seq.
- UnrollWhile used alone has no effect on seq2seq (∆F1 0.0/0.0); the authors state that it strengthens the attack when combined with other transformations.
- Q5G sample count (Table 4, csn/java, Tr-Q1G): with 10 samples the adversarial F1 is 29.7, and with 50 samples it is 27.4; the authors state that attack strength saturates quickly.
What are some points that can be further explored?
The authors propose directions such as studying other models and tasks; the experiments cover only code summarization, two architectures, and 8 transformations.
Limitations and future directions noted by the authors
- Sec. 2: More structured networks such as graph neural networks and tree-LSTMs; the authors state these are left for future experiments in the adversarial training setting.
- Sec. 2: The training method in this paper does not solve ILP and does not train multiple models; the authors state that in the future, the AST pruning of Bielik and Vechev could be incorporated into this paper's framework.
- Sec. 6 (Conclusion): Future work could study the impact of adversarial training on other models (such as graph neural networks).
- Sec. 6 (Conclusion): Future work could explore other code tasks and transformations, such as automatic refactoring.
- Sec. 3: The method is not tied to semantics-preserving transformations; the authors state that transformations introducing common programmer typos and bugs could also be defined.
Scope of experimental coverage
- The models under test are seq2seq (BiLSTM) and code2seq, 2 architectures in total (Sec. 5).
- The only task is code summarization; the datasets are c2s/java-small, csn/java, csn/python, sri/py150, uniformly subsampled to 150k/10k/20k (Sec. 5, Appendix C.1).
- The transformation set consists of 8 semantics-preserving transformations, each configured to produce only one hole (Sec. 5, Appendix B).
- The attacker covers k=1 and k=5; Q5G is approximated with 10 randomly sampled sequences of length 5, not an exhaustive enumeration of 32768 (Appendix C.5).
- The paper does not report the number of experimental repetitions or variance, nor does it report a human evaluation.
Summarize the main content of the paper
The authors define k-transformation robustness for code models and propose an adversarial training method, which they state improves robustness on the code summarization task.
An adversarial robustness paper for neural networks on code: it studies how to make code models resist transformation attacks that preserve program semantics.
- Problem: Code models are sensitive to semantics-preserving transformations—in Figure 1, code2seq's prediction changes from indexOfTarget to search after a logging print statement is added; the authors want models to be robust to such transformation sequences.
- Method: Defines the k-adversary (selecting k semantics-preserving transformations from the transformation set T and applying them to a program) and k-robustness; the attack is implemented by enumerating transformation sequences to generate program sketches, then filling holes with a gradient method adapted from Yefet et al.; training uses Madry-style robust optimization, controlling overhead by pre-generating sketches offline and training with only k=1, with a composite loss λ=0.4.
- Main results (code summarization task, 4 datasets, Table 2): Under Q1G attack, the adversarial F1 gain of Tr-Q1G relative to Tr-Nor is +8.7 to +16.0 for seq2seq and +2.8 to +7.9 for code2seq; the authors state that averaged across datasets this is about 14 (74%) and 6 (27%) points.
- Strong attacker: Models trained with k=1 are also more robust to k=5 gradient attacks, e.g., on seq2seq, csn/java under Q5G, Tr-Q1G is 29.7 and Tr-Nor is 9.8 (Table 5d); the authors state this answers Q2 (limited to the combination of k=1 training and k=5 attack).
- Exceptions: The robustness gain of code2seq is smaller than that of seq2seq, which the authors speculate is related to its AST path representation; in individual settings Tr-Aug is worse than Tr-Nor, and on c2s/java-small under Q5R attack Tr-Aug (31.7) is higher than Tr-Q1G (31.3).
- Authors' conclusion: The authors state this is the first robust optimization adversarial training work for code tasks, and future directions include other models such as graph neural networks and other tasks such as automatic refactoring.