LLaMoCo: Instruction Tuning of Large Language Models for Optimization Code Generation

## Abstract

Abstract Recent research explores optimization using large language models (LLMs) by either iteratively seeking next-step solutions from LLMs or directly prompting LLMs for an optimizer. However, these approaches exhibit inherent limitations, including low operational efficiency, high sensitivity to prompt design, and a lack of domain-specific knowledge. We introduce LLaMoCo, the first instruction-tuning framework designed to adapt LLMs for solving optimization problems in a code-to-code manner. Specifically, we establish a comprehensive instruction set containing well-described problem prompts and effective optimization codes. We then develop a novel two-phase learning strategy that incorporates a contrastive learning-based warm-up procedure before the instruction-tuning phase to enhance the convergence behavior during model fine-tuning. The experiment results demonstrate that a CodeGen (350M) model fine-tuned by our LLaMoCo achieves superior optimization performance compared to GPT-4 Turbo and the other competitors across both synthetic and realistic problem sets. The fine-tuned model and the usage instructions are available at https://anonymous.4open.science/r/LLaMoCo-722A .

## 1 Introduction

Nowadays, Large Language Models (LLMs) are posing a profound impact on human society (Floridi & Chiriatti, ; Lund & Wang, ). Through text generation, LLMs exhibit extraordinary prowess in natural language understanding and adeptness in solving complex tasks (Biswas, ; Lund & Wang, ; Biswas, ). This prompts a research question: Can LLMs even handle the challenging Optimization problems that are usually difficult for humans to address? This forms the core of our study in this paper.

In the literature, several existing works have been developed to explore the possibilities of solving optimization problems using LLMs. A typical way is to iteratively prompt LLMs to output better solutions through a multi-turn conversation with LLMs (Yang et al., ; Guo et al., ; Liu et al., , ).
Typically, they leverage LLMs through an iterative process, sometimes incorporating the concept of in-context learning. This involves the steps of presenting the LLMs with a set of initial or current best-so-far solutions and iteratively requesting LLMs to generate potentially superior solutions.
While showing certain effectiveness in solving optimization tasks, these solution-to-solution approaches have several limitations: 1) the scale of target optimization tasks (e.g., the number of variables, historical solutions and newly generated solutions) is constrained by the context window length of LLMs; 2) the iterative process typically involves hundreds rounds of conversations, consuming multitudinous resources; and 3) due to the LLMs’ sensitivity to prompt design, it is nontrivial to provide coherent prompts for LLMs to guarantee ideal outputs.

Figure: Figure 1: Conceptual overview of LLMs as optimizers. Left: optimization through iteratively prompting LLMs for better solutions (solution-to-solution style), such as OPRO (Yang et al., ). Middle: optimization through directly prompting LLMs for an optimizer with code implementation, such as OptiMus (AhmadiTeshnizi et al., ). To ensure rational output, the prompts should include hints about the type of problem and the suggested optimizer. Right: our LLaMoCo, which first tunes general LLMs on a problem-code instruction set, then can be used to generate proper optimization code given the formatted problem prompts.
Refer to caption: x1.png

An alternative way is to directly prompt LLMs for optimization programs, namely a piece of executable code that either reuses existing optimization toolboxes (AhmadiTeshnizi et al., ) or combines multiple high-performing optimizers to create a novel one (Pluhacek et al., ). It could be more efficient than the solution-to-solution methods for two reasons: 1) only a simple or few rounds of conversation are necessary for generating codes; and 2) the prompts and the generated codes do not include solution information, making it compatible as the problem scales. However, it remains crucial to carefully craft prompts to ensure logical coherence of the generated codes. For example, OptiMus (AhmadiTeshnizi et al., ) integrates hints about the optimizer to be generated directly into the prompts, necessitating a deep understanding of optimization techniques and expertise in the field. Additionally, using the LLMs pre-trained on a wide range of corpus currently falls short in generating a customized optimizer tailored to a specific optimization problem instance. This limitation is identified as the lack of domain-specific expert knowledge (Zhao et al., ), which also extends to other intricate tasks with structured data, such as knowledge-base question answering and semantic parsing (Jiang et al., ; Xie et al., ).

In this paper, we propose LLaMoCo, a novel framework that fine-tunes general-purpose Large Language Models for optimization Code generation. Different from the above approaches that are sorely based on prompt engineering, our LLaMoCo fine-tunes the LLMs on a well-formatted instruction set comprising code-to-code pairs of problem prompts and executable optimization programs. Once the training is completed, the fine-tuned model can be generalized to unseen optimization problems, i.e., crafting an optimizer based on the specific problem structure. Our LLaMoCo holds the following advantages against the preliminary works. 1) The solution information-free setting, where an optimization program is generated in a single round of conversation, makes it easier to handle large-scale problems with higher efficiency than the solution-to-solution methods. 2) The stipulated prompt protocol for users to describe their optimization problems minimizes the domain knowledge and efforts required for prompt design. 3) The fine-tuned LLMs by our LLaMoCo provide users with more robust and expert-level optimizers than those obtained by directly using general code-generating LLMs. In Figure 1, we illustrate the difference between LLaMoCo and existing approaches that leverage LLMs for optimization.

However, achieving expert-level LLMs for optimization tasks presents certain challenges. To overcome these challenges, we contribute to the following aspects: 1) We establish the first instruction set for fine-tuning LLMs as expert-level optimizer generators. This instruction set offers meticulously crafted problem descriptions and corresponding well-performing optimizer implementations selected from a wide spectrum of advanced optimizers, refined through extensive benchmarking with fine-grained hyper-parameter search; 2) We put forth a two-phase adaption strategy, which first enhances the latent space representation of a given problem instance through contrastive learning (Hadsell et al., ), followed by the conventional sequence-to-sequence loss for instruction tuning. Such design significantly accelerates the convergence of fine-tuned LLMs, resulting in superior performance; 3) LLaMoCo has been meticulously designed for user-friendliness. Users can focus on the optimization problem itself following a stipulated prompt protocol, and then the prompt is automatically constructed and fed into the LLMs fine-tuned by our LLaMoCo.

Our benchmark experiments reveal the remarkably robust optimization performance of our LLaMoCo, surpassing existing methods. Notably, we show that instruction tuning of a relatively small LLM, e.g., CodeGen-$350$M (Nijkamp et al., ), on domain-specific tasks can yield substantial performance enhancements, even surpassing the very large and powerful models like GPT-$4$ (Achiam et al., ). Moreover, we provide in-depth analyses of the proposed two-phase adapting strategy, the sensitivity to training data distribution, and the zero-shot generalization performance.

In summary, our contributions are four folds:
1) Introduction of LLaMoCo, the first instruction tuning framework for adapting general-purpose LLMs for generating expert-level optimizers. 2) Establishment of the large-scale instruction set on optimization domain, providing copious code implementation of advanced optimizers at instance level (Section 3.1). 3) Development of a novel two-phase training strategy that reinforces the latent space representations of the prompts through efficient contrastive warm-up training, boosting the subsequent instruction tuning performance (Section 3.2). 4) Demonstration of LLaMoCo’s superior optimization performance against existing LLM-based optimizers. The fine-tuned LLMs exhibit remarkable zero-shot generalization ability to realistic optimization tasks, with certain efficiency and code robustness (Section 4).

## 2 Related Works

### 2.1 Fine-tuning LLMs

Pre-trained Large Language Models (LLMs) can be refined by additional parameter updates on specific tasks through a fine-tuning process. We introduce two prominent fine-tuning strategies: Instruction Tuning (IT) (Ouyang et al., ) and Alignment Tuning (AT) (Christiano et al., ; Ziegler et al., ), each serving distinct purposes. Generally, IT involves fine-tuning pre-trained LLMs using a moderate collection of formatted task instances (Wei et al., ). The fine-tuning process typically includes two steps: 1) prepare instruction-formatted training examples by associating a task description with each task instance, which aids LLMs in understanding tasks through the instructions (Sanh et al., ); and 2) leverage the prepared instruction set to fine-tune LLMs using a sequence-to-sequence supervised loss (Gupta et al., ). By incorporating a well-established task-specific instruction set, IT can be an effective approach to inject domain-specific knowledge into general LLMs. This enables the transfer of LLMs to specific experts in domains like medicine (Singhal et al., ), law (Huang et al., ) and finance (Zhang et al., ).

Differently, AT aims to correct unexpected behaviors of LLMs by aligning the models with human values and preferences (Ouyang et al., ; Ziegler et al., ). A practical algorithm for AT is the Reinforcement Learning from Human Feedback (RLHF) (Ziegler et al., ), which firstly estimates a reward model on a human-preference data collection via maximum likelihood. It then uses the learned reward model to provide feedback and post-trains the LLMs through Proximal Policy Optimization (PPO) (Schulman et al., ). A recent work named Direct Preference Optimization (DPO) (Rafailov et al., ) first reparameterizes the reward function based on the parameters of the pre-trained LLMs, saving the modelling and training of the reward function. DPO is mathematically equivalent to RLHF but is even more efficient, which is widely adopted in the latest LLMs such as Mistral 8x7B (Jiang et al., ).

### 2.2 LLMs for Code Generation

The task of generating code from natural language descriptions is both exciting and inherently complex (Zan et al., ; Chen et al., ).
Although general-purpose LLMs such as GPT (Brown et al., ), Llama $2$ (Touvron et al., ) and Mistral (Jiang et al., ) show competitive performance on the widely used LLM benchmarks including HumanEval (Chen et al., ), MBPP (Austin et al., ) and DS-$1000$ (Lai et al., ), their performance on a particular task may still be limited. Recent efforts have focused on developing Large Language Models (LLMs) specifically tailored for code generation. These models are either trained exclusively on code, such as AlphaCode (Li et al., ) and StarCoder (Li et al., ), or fine-tuned from general LLMs, like Codex (Chen et al., ) and Code Llama (Roziere et al., ). Notably, Codex shows that a $12$B LLM can solve $72.31\%$ of complex programming tasks posed by humans. This success has led to the emergence of various Code LLMs, such as CodeGen (Nijkamp et al., ) that factorizes a potentially long specification into multiple steps to enhance program synthesis, and Code Llama that increases Llama $2$ models through a cascade of fine-tuning steps. Other models such as Phi-$2$ (Javaheripi et al., ), InCoder (Fried et al., ) and CodeGeeX (Zheng et al., ) have also gained great attention.

### 2.3 LLMs as Optimizers

Optimization plays a crucial role in numerous science and engineering fields but poses significant challenges. Unlike simpler tasks such as language understanding that can be easily handled by humans, optimization tasks can hardly be solved by humans without efficient algorithms. The underlying complexity of solving optimization problems tests the reasoning and generalization abilities of LLMs. Recently, there are several works that explore the potential use of LLMs as optimizers (Yang et al., ; Pluhacek et al., ; Yang et al., ; Guo et al., ), mostly based on prompt engineering and sometimes in an in-context learning way (Min et al., ). Typically, these methods consider a set of candidate solutions to be improved. LLMs receive prompts containing these solutions and their objective values to propose improved ones. This process iterates until a termination condition is reached. Moreover, several studies introduce additional instructions, such as the mutation and crossover operations, to the naive prompts. This enables LLMs to mimic human-developed evolutionary operators, thereby achieving improved performance. (Liu et al., , ; Lehman et al., ; Chen et al., ). However, these approaches have limitations in efficiency due to the need for extensive iterations. In contrast, several studies consider prompting LLMs directly for optimization programs, focusing on either creating new optimizers (Pluhacek et al., ) or leveraging the combination of existing ones (AhmadiTeshnizi et al., ). To the best of our knowledge, all the aforementioned works focus on prompt engineering of pre-trained LLMs, and the area of fine-tuning general LLMs with optimization-domain knowledge remains unexplored.

## 3 LLaMoCo

We introduce LLaMoCo, the first instruction tuning framework for adapting general-purpose LLMs as optimizers. It operates on a code-to-code basis, whereby, given anoptimization problem where its objective function and constraints are described using Python or LaTeX codes, the fine-tuned LLMs would generate a code implementation of an optimizer for solving this problem (illustrated in the right of Figure 1). In Section 3.1, we introduce how to establish a high-quality instruction set that comprises expert-level knowledge about solving optimization problems. Based on the proposed instruction set, we design a novel two-phase instruction tuning strategy to smoothly boost the performance, which is detailed in Section 3.2.

### 3.1 Construction of Instruction Set

Task synthesis. An optimization problem can be mathematically formulated as follows:

$$ $\displaystyle Minimize:$ $\displaystyle\quad f(x),\quad x=(x_{1},x_{2},...,x_{D})$ $\displaystyle s.t.:$ $\displaystyle\quad g_{i}(x)\leq 0,\quad i=1,...,M_{g}$ $\displaystyle\quad h_{j}(x)=0,\quad j=1,...,M_{h}$ (1) $$

where $f(\cdot)$ is the objective function, $x$ is a $D$-dimensional vector denoting a solution, $g_{i}(\cdot)$ and $h_{j}(\cdot)$ denote $M_{g}$ inequality constraints and $M_{h}$ equality constraints respectively. Without loss of generality, we assume a minimization problem where the optimal solution $x^{*}$ attains the minimum objective value, adhering to all specified constraints.

The main concern in this context is how to create an adequate amount of problem instances that possess both high quality and diversity, which is crucial for instruction tuning (Sanh et al., ; Zhou et al., ). Since it is not feasible to gather all types of optimization problems that arise in realistic scenarios, we opt for a more feasible approach by generating synthetic problem instances. Specifically, we collect a basic function set $\digamma$ comprising many different optimization problems and a basic constraint set $\Omega$ comprising a wide variety of constraints from the well-known optimization benchmarks (Boyd & Vandenberghe, ; Wu et al., ; Guo et al., ). Following the methodology of Mohamed et al. (), we synthesize a new objective function based on $K$ basic functions in $\digamma$ through two different paradigms as given by Section 3.1. 1) Composition: this involves a linear combination of the $K$ basic functions on the complete decision space, where each $w_{i}$ is uniformly sampled in $[0,1]$. 2)  Hybrid: we randomly decompose $x$ into $K$ segments $s_{1}$ to $s_{K}$. The $K$ basic functions then operate on these $K$ segments, respectively, and the final objective function is the summation of these basic functions’ values on the corresponding decision subspace.

$$ $\displaystyle Composition:$ $\displaystyle\quad f(x)=\sum_{i=1}^{K}w_{i}\cdot f_{i}(x)$ $\displaystyle Hybrid:$ $\displaystyle\quad f(x)=\sum_{i=1}^{K}f_{i}(x[s_{i}])$ (2) $$

More concretely, we obtain a problem instance by three steps: 1) Firstly, we indicate the problem dimension $D$, the search bounds for each dimension (e.g., $-10\leq x_{i}\leq 10$), and the number of basic functions $K$; 2) Secondly, if $K=1$, we randomly select a basic function in $\digamma$ as $f(x)$, otherwise, we apply Composition/Hybrid paradigm to synthesize $f(x)$; and 3) Lastly, we randomly select a group of constraints $\{\{g_{i}\},\{h_{j}\}\}$ in $\Omega$. Note that step 3) is optional, as some optimization problems may not have constraints.

In this work, we generate $3$k problem instances without constraints, denoted as $P_{\rm{nc}}$, and another $3$k problem instances with constraints, denoted as $P_{\rm{c}}$. The complete set $P$ is the union of $P_{\rm{nc}}$ and $P_{\rm{c}}$, consisting of $6$k instances. These instances showcase different characteristics of global landscapes, including unimodal or multimodal, separable or nonseparable, and symmetrical or asymmetrical. They also exhibit various local landscape properties, such as distinct properties around different local optima, continuous everywhere yet differentiable nowhere, and optima situated in flattened areas. This guarantees that the generated instances comprehensively mirror various realistic problems.

Knowledge gathering. In our study, the term ‘knowledge’ refers to expertise on how to deal with an optimization problem, which involves identifying a well-performing optimizer and configuring its hyper-parameters. After synthesizing the task set, we conduct exhaustive benchmarking to determine one effective optimizer for each instance $p\in P$. Concretely, we filter a wide range of optimizers from the published literature (Stork et al., ; Zhan et al., ), competitions (Wu et al., ; Mohamed et al., ; Turner et al., ), and benchmarks (R.Turner & D.Eriksson, ; Guo et al., ). The $23$ selected optimizers form an algorithm pool, which covers various algorithm families, including Evolutionary Algorithms (e.g., GA (Holland, ; Clune et al., ; Wang et al., ), DE (Storn & Price, ; Xu et al., ; Biswas et al., ; Ye et al., ), PSO (Kennedy & Eberhart, ; Gong et al., ; Wu & Wang, ; Lu et al., ) and ES (Hansen & Ostermeier, ; Ros & Hansen, ; Hansen, ; He et al., )), Bayesian Optimization (Snoek et al., ; Wang et al., ), Local Search strategies (Kirkpatrick et al., ; Van Laarhoven et al., ; Xiang et al., ; Fontes et al., ), and Numerical Optimization methods (Kraft, ; Conn et al., ; Powell, ; Bollapragada et al., ).
To determine the most effective optimizer among our algorithm pool for each instance $p$, we employ a two-step process. Firstly, we perform a grid search to identify the best configuration for each optimizer on $p$ (conducted multiple times to reduce the impact of variance). Subsequently, we select the optimizer that yields the best performance among all the configured optimizers. The selected optimizer and its configuration are implemented as a piece of Python code, serving as the knowledge of the desired optimizer’s implementation for instance $p$. Refer to Appendix A for details of those selected optimizers (configurations, implementations etc.) and the benchmarking process.

Figure: Figure 2: Input-output example of our instruction set. For a given problem (red box), diverse task descriptions in Python/LaTeX formats construct the prompt (yellow box). The code implementation of an effective optimizer is provided as the answer (green box).
Refer to caption: x2.png

Enhancement with diverse task descriptions. Recent studies suggest that enhancing the diversity of the task descriptions for each task instance can lead to additional generalization gains for the instruction-tuned LLMs (Sanh et al., ; Wei et al., ; Chung et al., ). We hence augment each problem instance in $P$ by rephrasing the writing style of its objective function and constraints. Specifically, we invited a total of $500$ university students majoring in computer science to write Python or LaTeX codes for describing a variety of optimization problems.
Different writing patterns are observed during this process. Based on these different patterns, for each problem instance $p\in P$, we can obtain a number of rephrased versions for describing its objective function and constraints in either Python or LaTeX code. Refer to Appendix B for the detailed rephrasing process and the different writing styles we have found.

After the data augmentation, we obtain the final instruction set by transforming each instance $p$, along with its rephrased versions, into a text prompt $q$ (input), and setting the source code of the selected optimizer with configurations as the answer $a$ (output). This results in an instruction set $\mathbb{I}$ comprising $32570$ pairs of input-output examples $(q,a)$, where an input-output example is illustrated in Figure 2.

### 3.2 Two-Phase Instruction Tuning

Contrastive warm-up. A key observation during the instruction set construction process in Section 3.1 is that: even two prompts $q_{m}$ and $q_{n}$ are very different to each other (e.g., they adopt different descriptions of the same problem), they can share the same desired optimizer $a$. On the contrary, for two prompts hold similar descriptions, the selected optimizers may differ. This phenomenon challenges the convergence of the models during fine-tuning. An appealing approach to alleviate this issue is to adopt contrastive learning to align the latent space representation for different prompts that share the same semantics. Such contrastive learning task has shown its effectiveness in several code understanding scenarios (Guo et al., ).
In LLaMoCo, we adopt constrastive learning (Hadsell et al., ) to warm up the LLMs before instruction tuning.

The workflow of the loss calculation is illustrated in Figure 3. Given an anchor prompt, we collect its similar
prompts and dissimilar prompts within a mini-batch, which are then applied to calculate the positive and negative sample loss, respectively. Specifically, for the decoder-only LLMs adopted for code generation tasks in this paper, we activate the Transformer layers (Vaswani et al., ) and regard the output embedding of the final self-attention block as latent space representation for the prompt $q$.

Figure: Figure 3: The workflow of contrastive warm-up strategy. Given an anchor problem prompt, we collect its similar prompts and dissimilar prompts within a mini-batch. The positive and negative sample losses are calculated on the latent space representations.
Refer to caption: x3.png

In LLaMoCo, we measure the distance between two prompts $q_{m}$ and $q_{n}$, denoted as $G(q_{m},q_{n})$, by considering the cosine similarity between their latent space representations $\overrightarrow{o}(q_{m})$ and $\overrightarrow{o}(q_{n})$:

$$ $G(q_{m},q_{n})=\frac{1}{2}\left(1-\frac{\vec{o}\left(q_{m}\right)\cdot\vec{o} \left(q_{n}\right)}{\left\|\vec{o}\left(q_{m}\right)\right\|\left\|\vec{o} \left(q_{n}\right)\right\|}\right)$ (3) $$

The above distance $G(q_{m},q_{n})\in[0,1]$. Then, the contrastive loss of $q_{m}$ and $q_{n}$, denoted as $L_{\rm{cl}}(q_{m},q_{n})$, is as

$$ $L_{\rm{cl}}=\begin{cases}G(q_{m},q_{n})&a_{m}=a_{n}\\ \max(0,\varphi-G(q_{m},q_{n}))&a_{m}\neq a_{n}\end{cases}$ (4) $$

where $a_{m}$ and $a_{n}$ are the corresponding designated optimizer of $q_{m}$ and $q_{n}$, respectively, $\varphi$ is a margin parameter. By minimizing $L_{\rm{cl}}$, we could efficiently pull together the representations of two prompts which share the same desired optimizer yet have different forms, and vice versa. In LLaMoCo, we consume a small number of epochs to warm up the fine-tuning of LLMs by $L_{\rm{cl}}$ and then instruction-tune the LLMs with the normal language modelling loss for next-token prediction (Wolf et al., ). We note that the contrastive warm-up phase does not require context generation, hence the time cost is relatively smaller compared with the subsequent instruction tuning phase. We validate the effectiveness of this contrastive learning phase in Section 4.3.

Balanced data sampling. The instruction set $\mathbb{I}$ exhibits certain imbalance in the distribution of data. Notably, we observe that several optimizers dominate on thousands of problem instances, while the others only outperform on a few problem instances. Dealing with imbalanced data poses a challenge during the process of fine-tuning models (Batista et al., ; Zhao et al., ). To address the issue, we follow the example-proportional mixing strategy (Raffel et al., ) to re-balance the data distribution in $\mathbb{I}$. Each data pair $(q,a)$ is sampled with a probability $\rho$ as:

$$ $\rho(q,a)=\frac{1}{N_{a}\times N_{q,a}}$ (5) $$

where $N_{a}$ denotes the number of optimizers in the gathered algorithm pool, $N_{q,a}$ denotes the number of instances whose desired optimizer is $a$. In this way, the number of sampled pairs dominated by each optimizer is approximately equal in each training epoch. Note that we apply this strategy in both the contrastive warm-up phase and the instruction tuning phase. The approach aids in avoiding biased training of the LLMs and enables them to effectively learn the knowledge from minority instances.
In addition, a homogeneous mini-batch sampling strategy is applied, due to the space limitation, it is presented in Appendix C.

## 4 Results and Discussions

### 4.1 Experimental Setup

Fundamental models. We adopt CodeGen-Mono ($350$M), Phi-$2$ ($2.7$B) and Code Llama ($7$B) as fundamental models and fine-tune them on our instruction set. The reasons are two-fold: 1) these models show robust programming language reasoning and code generation ability, serving as a good start point for the code-to-code scenario in our work; 2) the relatively small model size helps to reduce computational resources required for training and deploying.

Training settings. For generating the task set $P$, the problem dimension $D$ for each $p_{i}$ is randomly chosen from $[2,50]$, and the number of components $K$ is randomly chosen from $[1,5]$. We randomly split the instruction set $\mathbb{I}$ into a training set $\mathbb{I}_{\rm{train}}$ with $30$k input-output pairs and a test set $\mathbb{I}_{\rm{eval}}$ with the rest examples. For our two-phase instruction tuning, we deploy $5$ epochs of contrastive warm-up and $20$ epochs of instruction tuning for all fundamental models. Specifically,
we first apply SGD (Amari, ) with a fixed learning rate $5\times 10^{-4}$ in the contrastive warm-up phase, alongside $\varphi=0.3$. Then, we apply AdamW (Loshchilov & Hutter, ) to optimize the LLMs in the instruction tuning phase. During the initial $1$k iterations, the learning rate gradually increases from 0 0 to $5\times 10^{-4}$ in a linear manner. Subsequently, it decreases to 0 0 according to a cosine schedule. The batch size in both phases is set to $4$. Note that we fine-tune the CodeGen-Mono ($350$M) with full parameters, but apply LoRA (Hu et al., ) to fine-tune the larger Phi-$2$ ($2.7$B) and Code Llama ($7$B) models, with the rank $r=8$, scaling factor $\alpha=32$, and a dropout rate of $0.05$. All experiments are performed on a platform with an Intel(R) Xeon(R) Gold $6348$ CPU, $504$GB RAM and a Nvidia A$800$ ($80$GB) GPU. Upon the settings, the training duration for CodeGen is one day, whereas Phi-$2$ and Code Llama require $2.5$ days and $4$ days of training, respectively.

Competitors. We include two solution-to-solution approaches, OPRO (Yang et al., ) and LMEA (Liu et al., ), which prompt pre-trained LLMs (e.g., GPT-$4$ Turbo) repeatedly to generate and improve solutions for the given problems. Compared to OPRO, LMEA additionally engineered its prompt with an explicit indication of using some evolutionary operators to let LLMs act as an evolutionary optimizer for performance boost. We also include three general LLMs for code generation, namely Code Llama-$7$B (Roziere et al., ), Llama $2$-$70$B (Touvron et al., ), and GPT-$4$ Turbo (Achiam et al., ). We prompt these three general LLMs with the same format as in our instruction set $\mathbb{I}$ to generate an optimizer for each problem instance. The configurations of the competitors are set by default according to the corresponding references.

**Table 1: Results of different approaches in terms of Code Error Rate (Err.), Code Recovery Cost (Rec.), Optimization Performance (Perf.), and Computational Overhead (Comp.) on the unconstrained problems ($\mathbb{I}_{\rm{eval}}/P_{\rm{c}}$), constrained problems ($\mathbb{I}_{\rm{eval}}/P_{\rm{nc}}$), and all test problems ($\mathbb{I}_{\rm{eval}}$), where “-” denotes that the approach does not generate code (it follows a solution-to-solution paradigm).**
| Testset | Metrics | Prompt for Solution | Prompt for Optimizer | Our LLaMoCo |  |  |  |  |  |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| OPRO | LMEA | GPT-$4$ Turbo | Code Llama-$7$B | Llama2-$70$B | LLaMoCo-S | LLaMoCo-M | LLaMoCo-L |  |  |
| $\mathbb{I}_{\rm{eval}}/P_{\rm{c}}$ | Err. $\downarrow$ | - | - | 43.333% | 98.184% | 99.673% | 5.437% | 4.414% | 4.697% |
| Rec. $\downarrow$ | - | - | 9.942% | 67.857% | 62.232% | 9.684% | 10.101% | 9.947% |  |
| Perf. $\uparrow$ | 29.499% | 20.350% | 71.783% | 14.089% | 18.922% | 85.360% | 86.412% | 85.810% |  |
| Comp. $\downarrow$ | 115k | 249k | 3.4k | 1.7k | 1.5k | 2.3k | 2.3k | 2.3k |  |
| $\mathbb{I}_{\rm{eval}}/P_{\rm{nc}}$ | Err. $\downarrow$ | - | - | 39.944% | 90.474% | 99.521% | 5.697% | 6.130% | 5.977% |
| Rec. $\downarrow$ | - | - | 16.463% | 44.938% | 49.202% | 11.861% | 10.443% | 10.584% |  |
| Perf. $\uparrow$ | 4.514% | 7.541% | 75.678% | 46.968% | 22.460% | 77.576% | 79.718% | 83.404% |  |
| Comp. $\downarrow$ | 115k | 249k | 3.5k | 2.0k | 2.0k | 2.5k | 2.5k | 2.5k |  |
| $\mathbb{I}_{\rm{eval}}$ | Err. $\downarrow$ | - | - | 41.667% | 95.156% | 99.617% | 5.580% | 5.434% | 5.509% |
| Rec. $\downarrow$ | - | - | 13.072% | 57.001% | 55.717% | 10.826% | 10.349% | 10.461% |  |
| Perf. $\uparrow$ | 17.821% | 14.762% | 74.248% | 29.717% | 20.579% | 81.843% | 83.369% | 83.451% |  |
| Comp. $\downarrow$ | 115k | 249k | 3.5k | 1.9k | 1.7k | 2.4k | 2.4k | 2.4k |  |

Performance metrics. When evaluating the performance of LLMs for optimization, we consider four metrics: 1) the code error rate, which indicates the proportion of problems for which the LLMs generate optimization codes with bugs (lower values are preferable); 2) the code recovery cost, which measures the proportion of lines of code that need to be corrected in order to fix the bugs in the erroneous codes (lower values are preferable); 3) the average optimization performance on the test problems (higher values are preferable); and 4) the average computational overhead for solving a problem, which is determined by the number of tokens used for both the input and output of LLMs (lower values are preferable). These four metrics could provide a comprehensive evaluation on existing baselines and our LLaMoCo in aspects of code generation robustness, optimization performance and runtime complexity. The detailed calculations for these metrics can be found in Appendix D.

**Table 2: Performance comparison on realistic problems.**
| Metrics | OPRO | GPT-$4$ Turbo | LLaMoCo-S |
| --- | --- | --- | --- |
| Err. $\downarrow$ | - | 79.483% | 4.168% |
| Rec. $\downarrow$ | - | 22.985% | 7.426% |
| Perf. $\uparrow$ | 73.995% | 59.174% | 87.227% |
| Comp. $\downarrow$ | 241k | 3.6k | 2.5k |

### 4.2 Performance Analysis

We use LLaMoCo-S(mall), -M(edium) and -L(arge) to denote the fine-tuned CodeGen-Mono ($350$M), Phi-$2$ ($2.7$B) and Code Llama ($7$B) models on $\mathbb{I}_{\rm{train}}$, respectively.

Performance on test sets. First, we evaluate the performance of our fine-tuned LLMs and the competitors on three test sets, $\mathbb{I}_{\rm{eval}}/P_{\rm{c}}$, $\mathbb{I}_{\rm{eval}}/P_{\rm{nc}}$, and $\mathbb{I}_{\rm{eval}}$ that represent the unconstrained task set, constrained task set, and the complete set mixing unconstrained and constrained tasks, respectively, each with $5$ independent runs. The results in terms of the four metrics are reported in Table 1, which show that:

1) The LLMs fine-tuned by our LLaMoCo framework consistently achieve superior performance, which validates that instruction tuning the general LLMs with moderate expert-level knowledge would gain substantial performance reinforcement in optimization. For example, LLaMoCo-L fine-tuned on the Code Llama ($7$B) demonstrate an optimization performance boost from $29.717\%$ to $81.843\%$ on $\mathbb{I}_{\rm{eval}}$.

2) Although LLaMoCo-S is fine-tuned from a relatively small fundamental model, it achieves competitive performance to those of LLaMoCo-M and LLaMoCo-L. This may reveal a potential marginal effect in instruction tuning, since the data scale should match the capacity of the model.

3) The solution-to-solution approaches OPRO and LMEA achieve unsatisfactory performance on our complex optimization task sets. Considering the tremendous tokens these approaches consume to solve one optimization problem through iteratively prompting solutions, both the efficacy and efficiency (as shown in the ‘Perf.’ and ‘Comp.’ rows of Table 1) of them require further improvement.

4) Among the three ‘prompt for optimizer’ models we compared, the GPT-$4$ Turbo dominates the other two, which shows the powerfulness of a general-purpose LLM with high capacity. Nevertheless, it still underperforms our domain-specific LLaMoCo. Our models effectively reduce the error rates and the required recovery efforts for generating the codes of an optimizer through the instruction tuning. Meanwhile, note that the Code Llama ($7$B) model achieves better overall performance than the Llama $2$ ($70$B) model in our experiments. The above observations validate that, although LLMs with larger capacity may show strong performance for solving general tasks, a smaller model could be sufficient to be fine-tuned as a domain-specific task solver.

Zero-shot performance on realistic problems. We introduce a realistic optimization problem set collected by Kumar et al. () to further evaluate the zero-shot generalization performance of the LLMs fine-tuned by our LLaMoCo. This problem set serves as an ideal testbed for our framework for two reasons: 1) an optimizer that performs very well on synthetic benchmark suites may not provide robust performance on real-world problems, and 2) this set of problems shows very different structures compared to our synthetic problem set $P$. These problems come from various real-world scenarios including the industrial chemical process, mechanical engineering, and the power system, many of them feature high-dimensional problem spaces and complicated constraints. As an illustration, we test OPRO, GPT-$4$ Turbo and our LLaMoCo-S on these realistic problems (integrate their problem definitions into our formatted prompts) for $5$ independent runs. The results in Table 2 demonstrate the best generalization performance and hence the practical availability of our LLaMoCo.

### 4.3 Ablation study

Diversity enhancement. To improve the generalization of the fine-tuned LLMs in LLaMoCo, we enrich the task descriptions for each problem instance by augmenting the description of its objective function and constraints with Python or LaTeX codes of different writing styles. We illustrate the effect of this procedure in the left of Figure 5 by showing the optimization performance of six LLaMoCo-S models trained on pure Python, pure LaTeX and Python+LaTeX data, with or without the diversity enhancement by rephrasing. The results show that providing multi-lingual descriptions of optimization problems significantly boosts the generalization performance, while rephrasing each description with multiple writing styles further enhances the final training results.

Contrastive warm-up.
The contrastive warm-up phase in our proposed two-phase instruction tuning strategy (see Section 3.2) aims to reduce the cross-modal ambiguity by aligning the latent space representations of different prompts that share the same desired optimizer. We illustrate the training curves and performance gain curves on $\mathbb{I}_{\rm{eval}}$ with or without the contrastive warm-up during the instruction tuning phase in Figure 4, where LLaMoCo-S is applied as a showcase. The results show that incorporating such a contrastive warm-up strategy aids in accelerating the convergence of the subsequent instruction tuning. Furthermore, it is advantageous for the LLMs to generate accurate codes and enhance the overall optimization performance.

Figure: Figure 4: Effectiveness of the contrastive warm-up strategy on training curves (Left) and performance gains (Right).
Refer to caption: x4.png

Figure: Figure 5: Effectiveness of the diversity enhancement strategy (Left) and the data distribution balancing strategy (Right).
Refer to caption: x6.png

Balanced data sampling. In LLaMoCo, we address the imbalanced data distribution (caused by dominate optimizers) through performing example-proportional sampling on $\mathbb{I}_{\rm{train}}$. To investigate its effectiveness, we train two LLaMoCo-S models on $\mathbb{I}_{\rm{train}}$, with or without the data balancing strategy, respectively. The optimization performance of the two models is presented in the right of Figure 5, by separately considering the majority instances (which request the dominating optimizers), the minority instances (which request the others), and the overall instances of $\mathbb{I}_{\rm{eval}}$. The results consistently show that keeping a balanced training data distribution significantly boosts performance.

### 4.4 Open-Ended Discussion: Is GPT-4 a True Optimization Expert?

Considering the competitive performance of GPT-$4$ on optimization tasks, as shown in Table 1, we delve into whether GPT-$4$ can be deemed as a genuine optimization expert. Upon viewing the optimization codes generated by GPT-$4$ for both the test and the realistic problem set, a noteworthy pattern emerges. GPT-$4$ consistently leans towards generating a specific numerical optimizer, SLSQP (Kraft, ), for almost all tested problems. While SLSQP is a classical solver for convex quadratic programming and is included in our chosen advanced optimizers, our benchmarking results identify that on a proportion of tested problems, it underperforms the others such as the Vanilla DE (Storn & Price, ). To investigate further, we experiment by providing GPT-$4$ with a hint to use Vanilla DE to solve these specific problems. Surprisingly, GPT-$4$ successfully outputs a code implementation of DE and achieves competitive results. This observation suggests that while GPT-$4$ may have included sufficient domain knowledge on how to solve optimization problems, it still exhibits an underfitting issue concerning how to solve a ‘particular’ problem. This underscores the importance of the LLaMoCo framework for fine-tuning general LLMs to fit the task of generating an appropriate optimizer tailored for specific problem instances.

## 5 Conclusion

We introduce LLaMoCo, the first instruction-tuning framework to adapt general LLMs to function as expert-level systems to solve optimization problems. To achieve this, we meticulously construct an instruction set with more than $30$k demonstration examples and then employ a novel two-phase instruction tuning strategy to fine-tune a series of LLMs. The results show that our models consistently outperform existing approaches. Notably, we observe that a relatively small LLM is sufficient to be tuned as an expert-level optimization code generator superior to GPT-$4$. As a preliminary exploratory research endeavour, LLaMoCo certainly has limitations, such as the need to augment the instruction set with more instances to enhance generalization performance. Additionally, we consider enhancing the LLMs fine-tuned by LLaMoCo through further alignment tuning as a promising future direction.

## Impact Statements

This paper presents work whose goal is to advance the field of Machine Learning. There are many potential societal consequences of our work, none of which we feel must be specifically highlighted here.

## Appendix A Benchmarking for Knowledge Gathering

### A.1 Optimizer Pool and The Used Assets

To match each problem instance in the generated problem set $P$ with an appropriate optimizer with corresponding code implementation, we construct an optimizer pool $\Lambda$ which integrates 23 well-performing optimizers from various algorithm families. These selected optimizers can be divided into two groups considering their compatibility for constraint handling. We briefly list the two groups as below:

Unconstrained group $\Lambda_{uc}$: Simulated Annealing (Kirkpatrick et al., ), Vanilla PSO (Kennedy & Eberhart, ), Vanilla DE (Storn & Price, ), Dual Annealing (Xiang et al., ), SAMR-GA (Clune et al., ), SEP-CMA-ES (Ros & Hansen, ), BIPOP-CMA-ES (Hansen, ), DEAP-DE (Fortin et al., ), Vanilla BO (Snoek et al., ), GLPSO (Gong et al., ), MMES (He et al., ), LA-MCTS (Wang et al., ), MadDE (Biswas et al., ), sDMS-PSO (Wu & Wang, ), AMCDE (Ye et al., ), NSA (Fontes et al., ).

Constrained group $\Lambda_{c}$: SLSQP (Kraft, ), Trust-Constr (Conn et al., ),
COBYLA (Powell, ), L-BFGS-B (Morales & Nocedal, ), HECO-DE (Xu et al., ), DTPSO (Lu et al., ), GA-TDX (Wang et al., ).

We benefit from open-source libraries, including DEAP (Fortin et al., ), PyPop7 (Duan et al., ), evosax (Lange, ), SciPy (Virtanen et al., ) and Scikit-Optimizer (Louppe & Kumar, ) etc., for the easy implementation of the selected optimizers. We list the codebases we adopt for the implementation of these optimizers and their licenses in Table 3. We note that the development and deployment of our framework strictly follow those licenses.

**Table 3: Used assets and their licenses**
| Asset | Codebase | License |
| --- | --- | --- |
| DEAP-DE (Fortin et al., ) | DEAP (Fortin et al., ) | LGPL-3.0 License |
| Vanilla PSO (Kennedy & Eberhart, ) |  |  |
| SAMR-GA (Clune et al., ) | evosax (Lange, ) | Apache-2.0 license |
| BIPOP-CMA-ES (Hansen, ) |  |  |
| Simulated Annealing (Kirkpatrick et al., ) |  |  |
| SEP-CMA-ES (Ros & Hansen, ) | PyPop7 (Duan et al., ) | GPL-3.0 license |
| MMES (He et al., ) |  |  |
| LA-MCTS (Wang et al., ) |  |  |
| NSA (Fontes et al., ) |  |  |
| Dual Annealing (Xiang et al., ) | SciPy (Virtanen et al., ) | BSD-3-Clause license |
| SLSQP (Kraft, ) |  |  |
| COBYLA (Powell, ) |  |  |
| Vanilla BO (Snoek et al., ) | Scikit-Optimizer (Louppe & Kumar, ) | BSD-3-Clause License |
| GA-TDX (Wang et al., ) | advanced-global-optimizers<br>[https://pypi.org/project/advanced-global-optimizers/](https://pypi.org/project/advanced-global-optimizers/) | MIT License |
| Vanilla DE (Storn & Price, ) |  |  |
| MadDE (Biswas et al., ) |  |  |
| AMCDE (Ye et al., ) |  |  |
| HECO-DE (Xu et al., ) |  |  |
| GLPSO (Gong et al., ) |  |  |
| sDMS-PSO (Wu & Wang, ) |  |  |
| DTPSO (Lu et al., ) |  |  |

### A.2 Benchmarking Process

The benchmarking process aims to find an appropriate configured optimizer for each problem instance $p\in P$. To this end, for each optimizer $\Lambda_{k}\in\Lambda$, we span a grid-search configuration space $C_{k}$ based on its tunable hyper-parameters, which is listed in Table 4. Take DEAP-DE (Fortin et al., ) as an example, it has three hyper-parameters and each of them has 5 optional values (pre-defined by us). We hence span the $C_{k}$ of DEAP-DE as a configuration space comprising $5\times 5\times 5=125$ configurations, each denoted as $C^{j}_{k}$. We now establish the target of our benchmarking process:

$$ $\mathop{\arg\max}\limits_{\Lambda_{k}\in\Lambda,C^{j}_{k}\in C_{k}}\mathbb{E} \left[eval(p,\Lambda_{k},C^{j}_{k})\right]$ $$

where $p$ denotes the tested problem instance, $eval$ denotes the final optimization performance by calling $\Lambda_{k}$ with configuration $C^{j}_{k}$ to solve $p$, and $\mathbb{E}$ denotes the expectation of the optimization performance, which is unbiased-estimated by $5$ independent runs in this work. For constrained problems, we benchmark $\Lambda_{c}$, while for unconstrained problems we benchmark $\Lambda_{nc}$. We note that the benchmarking process for each problem instance may encounter execution failures, e.g., some optimizers in $\Lambda_{c}$ can not handle equality constraints, some optimizers in $\Lambda_{nc}$ are incompatible with non-convex problems, BO optimizers are extremely time-consuming on high-dimensional problems. When failures occur, the corresponding $eval(p,\Lambda_{k},C^{j}_{k})$ is set to 0 0. After benchmarking $\Lambda$ on $P$, we provide a configured optimizer $a(\Lambda_{k},C^{j}_{k})$, and the corresponding code implementation as the desired optimizer for each $p$.

**Table 4: Configurations and the hyperparameter tuning settings of the optimizers.**
| Type | Algorithm | Parameters | Search range |
| --- | --- | --- | --- |
| GA | SAMR-GA<br>(Clune et al., ) | NP | [10, 20, 50, 100, 200] |
| elite_ratio | 0.0 |  |  |
| sigma_init | [0, 0.5, 1] |  |  |
| sigma_meta | [1, 2, 3, 4, 5] |  |  |
| sigma_best_limit | [0.0001, 0.001, 0.1] |  |  |
| GA-TDX<br>(Wang et al., ) | beta | [0.1, 0.2, 0.3, 0.4, 0.5] |  |
| gamma | [1, 3, 5, 7, 9] |  |  |
| m | 1e10 |  |  |
| NP | [10, 20, 50, 100, 200] |  |  |
| DE | Vanilla DE<br>(Storn & Price, ) | NP | [10, 20, 50, 100, 200] |
| F | [0, 0.5, 0.9] |  |  |
| Cr | [0, 0.5, 0.9] |  |  |
| mutation | {best1, best2, rand2, current2rand,<br>current2best, rand2best2} |  |  |
| bound | {clip, periodic, reflect, rand} |  |  |
| DEAP-DE<br>(Fortin et al., ) | NP | [10, 20, 50, 100, 200] |  |
| F | [0.1, 0.3, 0.5, 0.7, 0.9] |  |  |
| Cr | [0.1, 0.3, 0.5, 0.7, 0.9] |  |  |
| HECO-DE<br>(Xu et al., ) | F${}_{0}$ | 0.5 |  |
| Cr${}_{0}$ | 0.5 |  |  |
| A${}_{\rm{rate}}$ | [2, 4, 6, 8] |  |  |
| H${}_{\rm{m}}$ | [1, 3, 5] |  |  |
| NP${}_{\rm{m}}$ | 12 |  |  |
| NP${}_{\rm{min}}$ | 40 |  |  |
| lamda | [10, 20, 30, 40] |  |  |
| n${}_{0}$ | [1, 2, 3] |  |  |
|  | gamma | [0.05, 0.1, 0.2] |  |
| MadDE<br>(Biswas et al., ) | p | [0.09, 0.18, 0.27, 0.36] |  |
| P${}_{\rm{qBX}}$ | [0.01, 0.1, 0.2, 0.3, 0.5] |  |  |
| F${}_{0}$ | 0.2 |  |  |
| Cr${}_{0}$ | 0.2 |  |  |
| A${}_{\rm{rate}}$ | [1.3, 1.8, 2.3, 2.8 ,3.3] |  |  |
| H${}_{\rm{m}}$ | [5, 10 ,15, 20] |  |  |
| NP${}_{\rm{m}}$ | [2, 4, 6, 8] |  |  |
| NP${}_{\rm{min}}$ | 4 |  |  |
| AMCDE<br>(Ye et al., ) | F${}_{0}$ | 0.2 |  |
| A${}_{\rm{rate}}$ | [1.6, 2.1, 2.6, 3.1, 3.6] |  |  |
| H${}_{\rm{m}}$ | [5, 10, 15, 20] |  |  |
| NP${}_{\rm{m}}$ | [3, 6, 9] |  |  |
| NP${}_{\rm{min}}$ | 4 |  |  |
| Gn | 5 |  |  |
| pbc${}_{1}$ | [0.4, 0.5, 0.6] |  |  |
| pbc${}_{2}$ | [0.4, 0.5, 0.6] |  |  |
| pw | [0.1, 0.2, 0.3] |  |  |
|  | pr | [0.005, 0.01, 0.05] |  |
|  | pls${}_{\rm{succ}}$ | 0.1 |  |
|  | pls${}_{\rm{fail}}$ | 0.0001 |  |
| PSO | Vanilla PSO<br>(Kennedy & Eberhart, ) | NP | [10, 20, 50, 100, 200] |
| phi${}_{1}$ | [1, 2, 3] |  |  |
| phi${}_{2}$ | [1, 2, 3] |  |  |
| GLPSO<br>(Gong et al., ) | pm | [0.01, 0.1, 0.2] |  |
| NP | [10, 20, 50, 100, 200] |  |  |
| nsel | 10 |  |  |
| w | 0.7298 |  |  |
| c${}_{1}$ | 1.49618 |  |  |
| sg | 7 |  |  |
| rho | [0.1, 0.2, 0.3] |  |  |
| sDMS-PSO<br>(Wu & Wang, ) | w | [0.729, 0.271, 0.5] |  |
| NP | [33, 66, 99, 198] |  |  |
| c${}_{1}$ | [1.49445, 3., 0.75] |  |  |
| c${}_{2}$ | [1.49445, 3., 0.75] |  |  |
| m | [1, 3, 5] |  |  |
| R | [5, 10, 15] |  |  |
| LP | [5, 10, 15] |  |  |
| LA | 8 |  |  |
| L | 100 |  |  |
| L_FEs | 200 |  |  |
| PSO | DTPSO<br>(Lu et al., ) | p | [0.1, 0.5, 0.9] |
| sigma | [0.25, 0.5, 0.75] |  |  |
| gamma | [0.25, 0.5, 0.75] |  |  |
| u${}_{1}$ | [0, 0.5] |  |  |
| u${}_{2}$ | [0, 0.5] |  |  |
| c${}_{1,1}$ | [0, 1.711897] |  |  |
| c${}_{1,2}$ | [0, 1.711897] |  |  |
| c${}_{2,1}$ | [0, 1.711897] |  |  |
| c${}_{2,2}$ | [0, 1.711897] |  |  |
| ws | 0.9 |  |  |
| we | 0.4 |  |  |
| NP${}_{\rm{init}}$ | [50, 100, 200] |  |  |
| radius | [0.05, 0.1, 0.2] |  |  |
| ES | SEP-CMA-ES<br>(Ros & Hansen, ) | n_individuals | [10, 20, 50, 100] |
| c_c | [1, 2, 3, 4, 5] |  |  |
| sigma | [0.1, 0.3, 0.5] |  |  |
| BIPOP-CMA-ES<br>(Hansen, ) | NP | [10, 20, 50, 100] |  |
| elite_ratio | [0.2, 0.5, 0.7] |  |  |
| sigma_init | 1 |  |  |
| mean_decay | 0 |  |  |
| min_num_gens | [10, 30, 50] |  |  |
| popsize_multiplier | [1, 2, 3, 4, 5] |  |  |
| MMES<br>(He et al., ) | a_z | [0.05, 0.1, 0.2] |  |
| c_s | [0.1, 0.3, 0.5] |  |  |
| ms | [2, 4, 6] |  |  |
| n_individuals | [25, 50, 100] |  |  |
| n_parents | [25, 50, 100] |  |  |
|  | sigma | [0.1, 0.3, 0.5] |  |
| BO | Vanilla BO<br>(Snoek et al., ) | acq_func | [LCB, EI, PI, gp_hedge, EIps, PIps] |
| n_initial_points | [5, 10, 20] |  |  |
| initial_point_generator | [random, sobol, halton, hammersly, lhs] |  |  |
| LA-MCTS<br>(Wang et al., ) | n_individuals | [10, 20, 50, 100] |  |
| c_e | [0.01, 0.05, 0.1] |  |  |
| leaf_size | [10, 20, 30, 40, 50] |  |  |
| LS | Simulated Annealing<br>(Kirkpatrick et al., ) | NP | [10, 20, 50, 100, 200] |
| sigma_init | [0.1, 0.3, 0.5] |  |  |
| sigma_decay | 1 |  |  |
| sigma_limit | [0.01, 0.05, 0.1] |  |  |
| temp_init | 1 |  |  |
| temp_limit | 0.1 |  |  |
| temp_decay | [0.9, 0.99, 0.999] |  |  |
| boltzmann_const | [1, 5, 10] |  |  |
| Dual Annealing<br>(Xiang et al., ) | initial_temp | [523, 5230, 50000] |  |
| visit | [1.62, 2.62, 3.62] |  |  |
| restart_temp_ratio | [2e-5, 2e-3, 2e-1] |  |  |
| NSA<br>(Fontes et al., ) | sigma | [0.1, 0.3, 0.5] |  |
| schedule | [linear, quadratic] |  |  |
| n_samples | [10, 20, 50, 100, 200] |  |  |
| rt | [0.9, 0.99, 0.999] |  |  |
| NO | SLSQP<br>(Kraft, ) | eps | [1e-12, 1e-10, 1e-8, 1e-6, 1e-4] |
| Trust-Constr<br>(Conn et al., ) | initial_tr_radius | [0.5, 1, 1.5, 2] |  |
| initial_constr_penalty | [0.5, 1, 1.5, 2] |  |  |
| factorization_method | [equality_constrained_sqp, tr_interior_point] |  |  |
| COBYLA<br>(Powell, ) | rhobeg | [0.5, 1, 1.5, 2] |  |
| L-BFGS-B<br>(Morales & Nocedal, ) | maxcor | [5, 10, 15, 20] |  |
| eps | [1e-12, 1e-10, 1e-8, 1e-6, 1e-4] |  |  |

## Appendix B Details of Data Augmentation

It is a common practice to augment the training data for boosting the generalization performance in recent LLMs works (Sanh et al., ; Wei et al., ; Chung et al., ). In LLaMoCo, we alter different writing styles of a problem’s definition to generate moderate diverse prompts for each problem instance generated in $P$. For the different writing styles, we investigate $500$ university students majoring in computer science, invite them to write Python or LaTeX code that they believe is correct for defining the given problem instances. After systematic statistics, we have empirically summarized several writing patterns, which we believe could approximately represent the major writing patterns of different users. Based on these different patterns, for each problem instance $p\in P$, we can obtain moderate rephrased versions for its objective function and constraints written by either Python or LaTeX code. We showcase the found patterns on a toy Katsuura problem which holds the formulation as:

$\begin{aligned} Minimize:\quad&f(x)=\frac{10}{D^{2}}\prod_{i=1}^{D}\left(1+i
\sum_{j=1}^{32}\frac{\left|2^{j}x_{i}-\operatorname{round}\left(2^{j}x_{i}
\right)\right|}{2^{j}}\right)^{\frac{10}{D^{1.2}}}-\frac{10}{D^{2}},X\in R^{D}
\\
\end{aligned}$

For LaTeX patterns, we found three different writing styles from the $500$ testees, which differ from each other mainly based on the laws of arithmetic, e.g., commutative law, distributive law and associative law. We illustrate some different LaTeX codes for our toy problem in Figure 6.

Figure: Figure 6: Three writing styles in LaTeX of the toy problem.
Refer to caption: x8.png

For Python patterns, the testees show different coding preferences on the writing styles of the objective functions and the constraints, e.g., some may prefer using temporary variables to store interim calculation results, some leverage numpy to facilitate matrix operations while others use a for loop, some may encapsulate the calculation details into a functional module etc. In Figure 7 we list some of these writing styles on the toy problem.

Figure: Figure 7: Three writing styles in Python of the toy problem.
Refer to caption: x9.png

## Appendix C Details in Training Process

Homogeneous batch sampling. We further apply a homogeneous batch sampling strategy at the instruction tuning phase to reinforce the alignment of the different rephrasing version prompts for a problem $p\in P$. Concretely, we force the LLMs to sample data pairs which come from the same problem instances in a mini-batch. We observe consistent boosts in the training of LLaMoCo-S, LLaMoCo-M and LLaMoCo-L. By presenting the LLMs with a batch of homogeneous samples, they can learn patterns specific to these cross-modal prompts data more effectively.

Batch size. We would clarify that due to the resource limitation, all of our experiments are run on an NVIDIA A$800$ GPU. When we train the CodeGen-Mono ($350$M), the batch size is $4$ for both phases in our two-phase learning strategy. However, for one A$800$, Phi-$2$ ($2.7$B) and Code Llama ($7$B) are too large to include a batch of $4$ samples, even if we adapt LoRA for them. For Phi-$2$, the batch size is $3$ and $2$ for each learning phase, while $3$ and $1$ for Code Llama.

## Appendix D Calculation of Experimental Statistics

To provide a thorough evaluation on the LLMs fine-tuned by our LLaMoCo and the other approaches, for a group of $N_{p}$ problem instances, we first leverage the optimization programs generated by each LLM to optimize them, for $5$ independent runs. Then we calculate the average error rate, recovery cost, optimization performance and computational cost of an approach as the performance metrics of overall performance. The calculation details of these four performance metrics in our experimental results are as follows:

Error rate (Err.) The robustness of the generated optimization program is a very important index for quality of service (QoS). We measure the robustness by the proportion of error programs generated by an LLM, named as error rate. For each instance, we use the optimization program generated by an LLM (ours or the others) to optimize that instance for $5$ independent runs. We count the number of the generated programs which encounter compilation error or runtime error when being executed, denoted as $N_{err}$ (every single run on each instance is counted). Then the error rate of an approach on the tested instances is calculated as $\frac{N_{err}}{5\times N_{p}}$.

Recovery cost (Rec.) While an optimization program may encounter compilation error or runtime error, we observe from our experiments that a certain proportion of the error programs could be repaired and recovered. We provide a metric named recovery cost to measure the efforts required to repair the generated programs. Concretely, for an optimization program $a_{j}$, we denote the number of lines in it as $L^{(j)}$, and the number of lines that need to be repaired as $L_{err}^{(j)}$. Then the recovery cost for $a_{j}$ is $r_{j}=\frac{L_{err}^{(j)}}{L^{(}j)}$, and the recovery cost considering all $N_{err}$ error programs is calculated as $\frac{\sum_{j=1}^{N_{err}}r_{j}}{N_{err}}$.

Optimization performance (Perf.) We measure the optimization performance of an approach by a min-max normalized objective value descent. Concretely, we first estimate an optimal objective value $f^{*}_{i}$ for $i$-th problem instance, which can be easily obtained from our benchmarking process (achieved best objective value). For the given approach, we denote the performance on the $i$-th problem instance in $j$-th run as a min-max normalized term $w_{i,j}=\frac{f^{*}_{i,j}-f^{*}_{i}}{f^{0}_{i,j}-f^{*}_{i}}$, where $f^{0}_{i,j}$ is the best objective value of the solutions initialized by the optimizer on solving the $i$-th problem instance in $j$-th run, and $f^{*}_{i,j}$ is the corresponding best objective the optimizer finds. Then the overall average optimization performance of the given approach on the $N_{p}$ instances can be calculated as follows: $\frac{\sum_{i=1}^{N_{p}}\sum_{j=1}^{5}w_{i,j}}{5\times N_{p}}$.

Computational overhead (Comp.) Measuring the computational overhead by the wall-time complexity of an LLM-based approach is impractical since some of the LLMs only provide API for users. The network communication budget through calling the APIs would bias the ground results. We instead count the average number of tokens (input+output) consumed by an approach for solving a problem instance over the test runs.

## Appendix E Example Input-Output of the Fine-tuned Model

### E.1 Synthetic unconstrained example

We showcase the prompt and the generated optimization program (Figure 8) of a synthetic problem instance without constraints, which has the following formulation:

$\begin{aligned} Minimize:\quad&f(x)=\sum_{i=0}^{1}W_{i}f_{i}(z),z=\mathbf{M}^{
\mathrm{T}}x,x\in R^{D},\mathbf{M}\in R^{D\times D}\\
Where:\quad&f_{0}(\mathbf{x})=-20\exp\left(-0.2\sqrt{(1/D)\sum_{i=1}^{D}x_{i}^
{2}}\right)-\exp\left((1/D)\sum_{i=1}^{D}\cos\left(2\pi x_{i}\right)\right)+20
+e\\
&f_{1}(\mathbf{x})=\sum_{i=1}^{D}\left(\sqrt{\left|x_{i}\right|}+2sin(x_{i}^{3
})\right)\\
&W0=0.6002499789314202\\
&W1=0.02117765478091216\\
\end{aligned}$

Figure: Figure 8: A unconstrained problem prompt (on the left, a Python version), and the optimization program (on the right) output by LLaMoCo-S. The corresponding $16$-dimensional problem is constructed by a composition of two basic functions. Our LLaMoCo-S is prompted to output a competent optimizer for solving the problem within $40000$ function evaluations, which in this case, is BIPOP-CMA-ES.
Refer to caption: x10.png

### E.2 Synthetic constrained example

We showcase the prompt and the generated optimization program (Figure 9) of a synthetic problem instance with some constraints, which has the following formulation:

$\begin{aligned} Minimize:\quad&f(x)=z_{1}^{2}+10^{6}\sum_{i=2}^{D}z_{i}^{2},z=
x-o,X\in R^{D},o\in R^{D}\\
s.t.:\quad&\\
&h_{0}(x):\sum_{i=1}^{D}\left(\sum_{j=1}^{i}y_{j}\right)^{2}=0,y=x-o\\
&h_{1}(x):\sum_{i=1}^{D-1}\left(y_{i}^{2}-y_{i+1}\right)^{2}=0,y=x-o\\
\end{aligned}$

Figure: Figure 9: A constrained problem prompt (on the left, a Python version), and the optimization program (on the right) output by LLaMoCo-S. The corresponding $23$-dimensional problem is one of the basic functions, with two additional quality constraints. Our LLaMoCo-S is prompted to output a competent optimizer for solving that problem within $20000$ function evaluations, which in this case, is SLSQP. We note that the GPT-$4$ Turbo attain the same answer on this problem. However, the configurations suggested by LLaMoCo-S achieve higher optimization performance against GPT-$4$ Turbo that adopts the default configurations.
Refer to caption: x11.png

### E.3 Realistic example

We showcase the prompt and the generated optimization program (Figure 10) of a realistic problem instance with a large number of constraints yet with a relatively simpler objective function, which holds a different problem structure against the synthetic problems, which has the following formulation:

$\begin{aligned} Minimize:\quad&f(x)=35x_{1}^{0.6}+35x_{2}^{0.6}\\
s.t.:\quad&\\
&h_{1}(x):200x_{1}x_{4}-x_{3}=0\\
&h_{2}(x):200x_{2}x_{6}-x_{5}=0\\
&h_{3}(x):x_{3}-10000(x_{7}-100)=0\\
&h_{4}(x):x_{5}-10000(300-x_{7})=0\\
&h_{5}(x)=x_{3}-10000(600-x_{8})=0\\
&h_{6}(x)=x_{5}-10000(900-x_{9})=0\\
&h_{7}(x))=x_{4}\ln(x_{8}-100)-x_{4}\ln(600-x_{7})-x_{8}+x_{7}+500=0\\
&h_{8}(x)=x_{6}\ln(x_{9}-x_{7})-x_{6}\ln(600)-x_{9}+x_{7}+600=0\end{aligned}$

Figure: Figure 10: A realistic problem prompt (on the left, a LaTeX version), and the optimization program (on the right) output by LLaMoCo-S. The corresponding $9$-dimensional problem holds an out-of-distribution structure, with far more constraints than the problem instances LLaMoCo-S has ever seen. Our LLaMoCo-S is prompted to output a competent optimizer for solving that problem within $10000$ function evaluations, which in this case, is an advanced GA-TDX algorithm specialized in constraints handling. We note that the GPT-$4$ Turbo suggests a DE algorithm for this problem, which is hardly adopted for solving constrianed problems.
Refer to caption: x12.png

## Peer Reviews

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: 1. Investigate Model Performance Discrepancies: It would be beneficial to analyze why the smaller model occasionally outperforms larger ones. This could involve examining the training dynamics, learning rates, or potential overfitting issues in larger models. Providing insights or adjustments based on this analysis would strengthen the validity of the results.
2. Expand Baseline Comparisons: Could the authors add another baseline of ChatGPT o1-mini/o1-preview? Since o1-mini/o1-preview are reasoning/coding/math enhanced models. I expect it to perform better than ChatGPT 4o. These models are designed for coding tasks and would serve as competitive benchmarks to better evaluate LLaMoCo's performance. Incorporating such comparisons would contextualize LLaMoCo's performance within the broader landscape of code generation research. 
3. Enhance Robustness Evaluation: Assessing the models on out-of-distribution samples or real-world optimization problems beyond the dataset used for training could demonstrate the generalization capabilities and practical applicability of LLaMoCo, which could alleviate/address the concern of “Unexpected Performance Across Model Sizes”.
soundness: 3
strengths: 1. Specialized Dataset Creation: The development of a tailored code-to-code instruction dataset is a significant contribution. It aligns the fine-tuning process closely with the target task and provides a valuable resource for future research in optimization code generation.
2. Innovative Training Enhancements: Implementing contrastive warm-up, data augmentation through rephrasing, and balanced sampling demonstrates a comprehensive strategy to improve model performance. These techniques address common challenges in model training, such as overfitting and data imbalance.
3. Comprehensive Evaluation and Analysis: Evaluating the framework across models of varying sizes offers insights into scalability and the impact of model complexity. The inclusion of an ablation study allows for a deeper understanding of how each training enhancement contributes to the overall performance.
summary: This paper introduces LLaMoCo, a framework for fine-tuning general-purpose Large Language Models (LLMs) to generate optimization code through instruction tuning. The authors construct a specialized code-to-code instruction dataset tailored for optimization tasks. They enhance the training process with techniques such as contrastive warm-up, data augmentation via rephrasing, and balanced sampling. These methods are evaluated across three pre-trained models of different sizes (S, M, L), showing significant performance improvements. An ablation study further validates the effectiveness of the proposed techniques. Overall, the paper presents a promising approach to adapting LLMs for the specialized task of optimization code generation.
weaknesses: 1. Unexpected Performance Across Model Sizes: Table 1, 2 and 3 show that the performance of LLaMoCo-S, LLaMoCo-M and LLaMoCo-L are very similar. The results also show that LLaMoCo-S sometimes outperforms its larger counterparts (LLaMoCo-M and LLaMoCo-L), despite having significantly fewer parameters. This is counterintuitive and raises concerns about potential inefficiencies in leveraging larger model’s increased capacity.

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 2
questions: 1. What is the impact of dataset size on the training performance? Will the performance of the models continue to improve when using more data?

2. How to control the quality of the synthesized tasks? Can we ensure that unsolvable optimization problems or problems with only trivial solutions are not synthesized?

3. Why does the computational overhead of the trained models increase? (in Table 1)
soundness: 3
strengths: 1. This paper introduces the first complete framework for training LLMs to solve optimization problems, including instruction-tuning dataset construction and detailed methods for training. The method is well-described and effective, making a significant contribution to the optimization community. 

2. The experiments demonstrate performance improvements on both synthetic and realistic problem sets. across different scales of LLMs, highlighting the generalization and effectiveness of LLaMoCo.
summary: This paper proposes a data generation and instruction tuning method for optimization-problem-solving LLMs. The authors conduct comprehensive experiments to demonstrate the optimization capabilities of the instruction-tuned LLMs and analyze the contribution of each component of the method.
weaknesses: 1. Lack of sufficient novelty. Several key components of the method follow prior work [1-3], particularly the instruction-tuning approach (Section 3.2), which reduces its originality. Although this paper introduces the first instruction-tuning framework for optimization tasks, it primarily applies standard training techniques. The authors should emphasize their main innovations more clearly in the paper.

2. Writing. Figure 1 does not effectively highlight the main differences between LLaMoCo and previous methods, which is overly simplified. The authors should include more details of the method. There are typos in the caption of Figure 2 (wither -> either). The capitalization of “LaTeX” in the full paper is inconsistent.

[1]Problem definitions and evaluation criteria for the cec 2021 on single objective bound constrained numerical optimization.

[2]Unixcoder: Unified cross-modal pre-training for code representation.

[3]Exploring the limits of transfer learning with a unified text-to-text transformer.

---

confidence: 4
contribution: 3
initial_rating: 6
presentation: 2
questions: 1. Further experiments needed to demonstrate the combined effect of SFT and alignment.
2. Grid search "best" performance criteria not clearly defined, benchmarking process lacks clear evaluation metrics for optimizer selection.
soundness: 3
strengths: 1. 350M parameter model achieves 81.8% optimization performance vs GPT-4's 74.2% (without prompting) while using only 2.4K tokens vs 3.5K tokens.
2. Data pipeline converts 6000 problems to 32570 training pairs through systematic benchmarking of 23 optimizers across different configurations.
summary: This paper presents LLaMoCo, a pioneering framework that maps optimization problem descriptions directly to expert-level optimization code through instruction tuning. By creating a comprehensive dataset of (problem, best-solver) pairs and using a two-phase training strategy, even a small model (350M parameters) can surpass GPT-4 in selecting and generating appropriate optimizers for both synthetic and realistic optimization tasks.
weaknesses: 1. Zero-shot evaluation tested on only 8 realistic problems, requiring more cases to validate the claims.
2. GPT-4 baseline with vector search not evaluated.
3. Grid search necessity on original problems is subtle, some parameters are hard to set without careful data observation, requiring further validation of selection appropriateness.

---

confidence: 3
contribution: 2
initial_rating: 5
presentation: 3
questions: 1. Is the current dataset format truly optimal? For instance, could leveraging CoT enhance performance? Similarly, would implementing multi-turn iterative improvements for optimization code be a promising approach?

2. Could the proposed method be compared with previous non-LLM-based automatic algorithm selection approaches? Automatic algorithm selection for optimization problems is a well-established research area with a rich body of existing work.

3. Could the specific technical challenges unique to this optimization domain be highlighted? (see Weakness 1)

4. Would it be reasonable to separate the contrastive warm-up technique into a standalone paper or clarify that this technique is highly specialized for the domain under consideration? (see Weakness 2)
soundness: 3
strengths: 1. The authors have developed and plan to release a novel dataset designed to teach language models to solve optimization problems. This represents a significant contribution to both researchers and practitioners.

2. The experimental results are compelling. I especially appreciate Table 3, where the proposed method strongly performs on realistic optimization problems (rather than toy problems).
summary: This paper introduces LLaMoCo, a new framework for fine-tuning LLMs to solve optimization problems. The contributions of this paper are two-fold: (1) a novel fine-tuning dataset and (2) a new training warm-up strategy for training leveraging contrastive learning. Experimental evaluations demonstrate that LLaMoCo's models perform well on their held-out test set and realistic problems.
weaknesses: 1. This paper lacks novelty. This paper primarily focuses on fine-tuning OSS LLMs for a specific domain. The main approach is straightforward from this perspective: the authors adjusted prompts (specifically, framing problem descriptions in Python or Latex) and developed a new dataset. Could authors emphasize the unique technical challenges associated with this domain?

2. The contrastive warm-up technique in this paper seems out of place. This technique does not appear to be specifically tailored to optimization problems. Could it be beneficial for fine-tuning in other domains as well? If not, what are the reasons? I would suggest separating this novel technique into a dedicated paper or clarifying how it suits the domain under discussion. The ablation study in Figure 4 is not very convincing, as it was tested with only a single configuration, making the results dependent on that specific setup.

Meta-review: ### Summary of Claims and Findings
The paper introduces LLaMoCo, a novel instruction-tuning framework for adapting large language models (LLMs) to generate optimization code directly from problem descriptions in Python or LaTeX. The framework features a curated dataset of optimization problems paired with expert-level solutions and a two-phase training strategy that includes a contrastive warm-up phase to align problem-solution representations. Experimental results demonstrate that LLaMoCo significantly outperforms GPT-4 Turbo and other baselines in optimization performance across synthetic and realistic tasks.

### Strengths
1. **Framework Innovation**: LLaMoCo offers a structured approach to instruction tuning in the optimization domain, addressing challenges such as problem representation, model alignment, and data imbalance.
2. **Comprehensive Evaluation**: The paper demonstrates strong results on a diverse set of synthetic and real-world problems, coupled with scaling law analysis and ablation studies.
3. **Practical Impact**: The model's ability to generate efficient and effective optimization code has broad applications in engineering and optimization research.

### Weaknesses
1. **Perceived Incrementality**: Reviewers noted that many components (e.g., instruction tuning, dataset construction, contrastive learning) leverage existing techniques. Despite the authors’ rebuttal, the domain-specific nature of the contributions remains under-emphasized.
2. **Limited Demonstration of Contrastive Warm-Up's Necessity**: While the warm-up strategy appears effective, its justification as domain-specific was unconvincing to some reviewers, with suggestions that it could apply broadly across domains.
3. **Modest Scaling Gains**: Performance improvements from smaller to larger models appeared incremental, raising questions about the optimization knowledge effectively learned.

### Decision
While LLaMoCo represents a commendable effort to adapt LLMs for optimization code generation, the core novelty remains a concern. The primary contributions are seen as applications of existing methods rather than groundbreaking domain-specific innovations. Combined with lingering skepticism about the necessity and specialization of the proposed techniques, this submission falls marginally below the acceptance threshold.

Decision: Reject