L3Ms — Lagrange Large Language Models

## Abstract

Abstract Supervised fine-tuning (SFT) and alignment of large language models (LLMs) are key steps in providing a good user experience. However, the concept of an appropriate alignment is inherently application-dependent, and current methods often rely on heuristic choices to drive the optimization. In this work, we formulate SFT and alignment as a constrained optimization problem, where the LLM is trained on a task while being required to meet application-specific requirements, without resorting to heuristics. To solve this, we propose Lagrange Large Language Models (L3Ms), which employ logarithmic barriers to enforce the constraints. This approach allows for the customization of L3Ms across diverse applications while avoiding heuristic-driven processes. We demonstrate experimentally the versatility and efficacy of L3Ms in achieving tailored alignments for various applications.

## 1 Introduction

Large language models (LLMs) are used for a wide range of tasks: as chatbots (Brown et al., ; OpenAI, ), for code generation (Ahmad et al., ; Wang et al., ; Rozière et al., ), for medical assistance (Yang et al., ; Moor et al., ), and more.
The key ingredients for their impressive downstream performance are supervised fine-tuning (SFT) and alignment; the former fine-tunes the LLM to a task of interest, while the latter instills it with preferential properties.
Arguably, the *right* combination of preferential properties is highly application/task-dependent.
For instance, a scholar might want a chatbot to be honest and factual to assist with their work, whereas a fiction writer might prefer the opposite behavior to help create fantastical imaginary worlds.
There is also plenty of (anecdotal) evidence in support: some LLMs refuse to provide information on how to “kill” a process in Unix, recommending the use of less violent strategies for dealing with wayward computer programs instead.(^1^11[https://www.reddit.com/r/LocalLLaMA/comments/180p17f/new_claude_21_refuses_to_kill_a_python_process/](https://www.reddit.com/r/LocalLLaMA/comments/180p17f/new_claude_21_refuses_to_kill_a_python_process/))
Therefore, we need frameworks for the customization of LLMs.

Consequently, Li et al. (); Bai et al. (); Rame et al. (); Wu et al. (); Ji et al. () train LLMs on varying combinations of such preferential properties.
In practice, one tends to resort to trial and error to find the right preference combination for their particular task.
In doing so, one verifies if certain *minimum baselines* are satisfied, such as ensuring the factual correctness of statements or confirming that the response lengths are capped at 100 words.
Since there isn’t a way to enforce such requirements directly, current methods resort to heuristics.
Additionally, existing pipelines carry out SFT and alignment in sequential steps.
Hence they need to ensure that the LLM does not forget relevant task information learned during the SFT stage.
This is achieved by penalizing the LLM for drastic deviations: the strength of the penalty is determined heuristically.

In this work, we formulate SFT and alignment in LLMs as a constrained optimization problem.
In particular, we fine-tune an LLM to minimize the task perplexity (the objective function) while simultaneously satisfying application-specific minimum requirements (the constraints).
This merges the SFT and alignment stages and mitigates the reliance on heuristics altogether.
Furthermore, we propose Lagrange Large Language Models, a.k.a. L3Ms, to solve such constrained optimization problems.
Specifically, they do so by employing logarithmic barriers and enforcing the constraints gradually over the training procedure.
Lastly, we empirically demonstrate how one can pick and choose different constraints and tailor L3Ms to a range of applications without resorting to heuristics.
For example, Table 1 provides the generated responses from two such L3Ms; both are trained on the task of instruction-following, but one is constrained to be concise while the other is to be verbose.

In summary, our contributions are as follows:

- 1.
We formulate SFT and alignment in LLMs as a constrained optimization problem: an LLM is fine-tuned on a task while simultaneously satisfying custom requirements (cf. Section 4).
- 2.
We propose L3Ms, a family of LLMs fine-tuned using the above framework (cf. Section 5).
- 3.
We demonstrate experimentally how L3Ms can be customized to different applications and their specific requirements while avoiding heuristic-driven processes (cf. Section 6).

**Table 1: Example responses from length constrained L3Ms. We provide example responses from L3Ms with varying length constraints. We include the prompt along with the generated responses from two L3Ms: one constrained to have short responses, and the other constrained to long ones.**
| Prompt | What are the four main types of macromolecules found in living organisms? |
| --- | --- |
| Response<br>(short response L3M) | 1. Nucleic acids (DNA and RNA)<br>2. Proteins<br>3. Carbohydrates<br>4. Lipids |
| Response<br>(long response L3M) | 1. Nucleic acids, including DNA and RNA, which carry genetic information<br>2. Proteins, which are responsible for the structure, function, and regulation<br>of living organisms<br>3. Lipids, which provide energy and form the membranes that surround cells<br>4. Carbohydrates, which are used as an energy source and as structural<br>components of cells. |
| Prompt | Who discovered the law of universal gravitation? |
| Response<br>(short response L3M) | Sir Isaac Newton is credited with discovering the law of universal<br>gravitation in the late 17th century. |
| Response<br>(long response L3M) | Sir Isaac Newton is widely credited with the discovery of the law of<br>universal gravitation, which states that every particle in the universe attracts<br>every other particle with a force proportional to their masses and inversely<br>proportional to the square of the distance between them. |

## 2 Optimization for LLMs

Training an LLM proceeds in multiple stages (Ouyang et al., ), which we discuss below.

### 2.1 Pre-training

The pre-training stage instills the LLM with a generic knowledge of language.
It entails regenerating text/token sequences by minimizing their perplexity, i.e., the negative log-likelihood of the sequence normalized by its length.
More formally, the perplexity on a sequence $x$ is defined as:

$$ $l_{\theta}\left(x\right)\ =\ -\frac{\log\pi_{\theta}\left(x\right)}{|x|}\ =\ - \frac{1}{|x|}\sum_{i=1}^{|x|}\log\pi_{\theta}\left(x_{i}|x_{<i}\right),$ $$

where $x_{i}$ and $x_{<i}$ denote the $i$-th token in the sequence and its prefix, respectively.
Additionally, the function $\pi_{\theta}(\cdot)$ denotes the LLM’s predicted probability distribution over token sequences, where the LLM is parameterized with weights $\theta$.
Then, the pre-training objective is given as follows:

$$ $\min_{\theta}\ \mathds{E}_{x\sim q\left(\cdot\right)}\left[l_{\theta}\left(x \right)\right],$ $$

and the expectation is replaced by an empirical average over a large corpus with trillions of tokens.

### 2.2 Supervised fine-tuning (SFT)

Next, one fine-tunes the LLM to a task of interest, such as instruction-following, summarization, or translation.
The data are (prompt, response) pairs $(x,y)$, and the LLM is trained to regenerate these responses.
Thus, one minimizes the perplexity on the response conditioned on the prompt:

$$ $\min_{\theta}\ \mathds{E}_{\left(x,y\right)\sim p\left(\cdot\right)}\left[l_{ \theta}\left(y|x\right)\right],$ (1) $$

for the distribution $p(\cdot)$ over (prompt, response) pairs which reflects the task-related data.

### 2.3 Alignment

This stage aligns the LLM to generate responses with preferential properties.
A common setup is to learn preference reward functions that represent properties like helpfulness and harmlessness (Bai et al., ), followed by reinforcement learning to adapt the LLM to maximize said rewards.
This is referred to as reinforcement learning from human feedback (RLHF; Knox & Stone, ; Griffith et al., ; Christiano et al., ).
Note that the preference reward functions need not always be learned; they could also be engineered or rule-based, such as the length of the response.

Given a single preference reward function $r(\cdot)$, the alignment objective is given as follows:

$$ $\max_{\theta}\ \mathds{E}_{\begin{subarray}{c}\left(x,\cdot\right)\sim p\left( \cdot\right)\\ y\sim\pi_{\theta}\left(\cdot|x\right)\end{subarray}}\left[r\left(y|x\right) \right].$ (2) $$

This maximizes the rewards for the LLM’s responses to prompts sampled from the task distribution.
To prevent over-optimization of the reward and avoid drastic deviation away from the SFT model, it is common practice to add a regularization penalty such as the KL divergence (Gao et al., ).

We are interested in $k\geq 1$ different preferential properties.
In such a scenario, one could learn individual preference reward functions $r_{i}$’s and optimize the LLM to maximize their combination.
In particular, Li et al. (); Rame et al. (); Wu et al. (); Ji et al. () use a linear combination of the rewards, substituting the single reward in Eq. 2 with $\sum_{i=1}^{k}\alpha_{i}r_{i}(y|x)$, for some choice of $\alpha_{i}\geq 0$.
Alternatively, one could learn a single reward function by choosing the data proportions of the different properties used to train it.
For instance, Bai et al. () use a 3:1 proportion of helpfulness to harmlessness data to train a single preference reward function.
Note that the proportions can also be represented via weights $\alpha_{i}\geq 0$ with $\sum_{i=1}^{k}\alpha_{i}=1$.
Therefore, the choice of $\alpha_{i}$’s, combined with the strength of the regularization penalty, together steer the alignment.
They are chosen based on the good judgment of the practitioner in a somewhat heuristic manner.

### 2.4 Shortcomings

While the above pipeline is commonly used to train LLMs for deployment, it has shortcomings.

Firstly, how does one choose the weights $\alpha_{i}$’s?
Or equivalently, *what is the right combination of preference properties?*
Choosing between properties such as truthfulness, verbosity, and humor depends on the application at hand.
However, even when the application is known, the weights are chosen through trial and error: trying different combinations and inspecting the achieved rewards.
For instance, if one wants the responses to be under 100 words for a summarization task, one might repeatedly examine the length of the responses and adjust the weights $\alpha_{i}$’s to achieve that.
This inherently involves verification against a set of minimum baselines being satisfied.
*Can we avoid heuristics and enforce such minimum requirements for the preference rewards in a principled way?*

Secondly, recall that the original task objective is in Eq. 1.
However, optimizing a special purpose objective like Eq. 2 can lead to a decrease in performance on the original task.
While penalizing the deviation away from the SFT model helps mitigate this to some extent, the strength of the penalty is again determined heuristically.
*Can we ensure the performance on the original task is maintained?*

## 3 Related work

### 3.1 One size does not fit all

Early work on LLM alignment assumed homogeneity of preferences (Bakker et al., ).
However, the reality is quite different: human preferences vary widely and are highly application-specific (Rame et al., ; Casper et al., ).
Consequently, Rame et al. (); Wu et al. (); Ji et al. (); Zhou et al. () linearly combine several fine-grained preference rewards, where each combination reflects a different customized preference.
However, the *right* combination of preferential properties for a particular application is determined heuristically through trial and error.
Conversely, we formulate alignment as a constrained optimization problem, where the custom requirements are naturally imposed as constraints.
This alleviates the need for heuristic choices.

### 3.2 Constrained alignment for LLMs

Independent of our work, Moskovitz et al. (); Dai et al. () also introduced constrained optimization for LLM alignment but for varying reasons.
Motivated to avoid over-optimization of preference rewards, Moskovitz et al. () find “proxy points”, values of the reward functions beyond which the performance of the LLM is negatively impacted.
They constrain the average rewards to be in the vicinity of these proxy points.
Dai et al. () trade-off between helpfulness and harmlessness from a safety standpoint.
They maximize the LLM’s helpfulness while constraining its average harmlessness reward.
Our motivation on the other hand is to tailor to custom preferences through sets of different constraints, while simultaneously learning to perform the task at hand.

Our work is different in two important ways.
Firstly, both Moskovitz et al. (); Dai et al. () consider the alignment process in isolation, because of which their objective is either to maximize one of the preference rewards or to minimize the deviation away from the SFT model.
On the other hand, we merge the SFT and alignment stages and choose task perplexity minimization as our objective.
This directly ensures that the LLM’s task-solving capabilities are preserved, and it avoids loading an additional reference (SFT) model during the training process to compute the deviations.

Secondly, both Moskovitz et al. (); Dai et al. () obtain solutions to the constrained problem by computing the saddle-point of the Lagrangian.
This is done by formulating a min-max game where the LLM minimizes the Lagrangian and the Lagrange multipliers adapt to maximize it.
However, the non-convexity of the objective makes this nontrivial.
Instead, we choose the logarithmic barrier approach as the associated Lagrange multipliers satisfy the KKT complementary slackness condition by design (cf. Section 5.2) rather than letting the learning procedure do so (which in our experience is extremely sensitive to the choice of the learning rate).
We empirically observe that while both methods satisfy the constraints, our approach using log-barriers minimizes the task perplexity better (cf. Section 6.3).
As a side effect, we avoid introducing new learning parameters.

Additionally, we provide experimental validation of our approach on more preferences than Moskovitz et al. (); Dai et al. (), and a 4.5$\times$ larger LLM than Moskovitz et al. ().

## 4 Constrained optimization

Our goal is to reduce the task objective in Eq. 1 for the LLM to solve the intended task, while also enabling custom alignment by having the LLM meet the application-specific minimum requirements on different preference rewards.
To do so, we propose the constrained optimization problem:

$$ $\displaystyle\min_{\theta}\ \mathds{E}_{\left(x,y\right)\sim p\left(\cdot \right)}\left[l_{\theta}\left(y|x\right)\right]$ (3) $\displaystyle\text{subject to}\ \mathds{E}_{\begin{subarray}{c}\left(x,\cdot \right)\sim p\left(\cdot\right)\\ y\sim\pi_{\theta}\left(\cdot|x\right)\end{subarray}}\left[r_{i}\left(y|x\right )\right]\ \geq\ b_{i}\ \text{for all}\ i\in\left\{1,2,\ldots,k\right\}.$ (4) $$

Here, the objective is the same as the task objective in SFT, and the constraints are enforced to satisfy the custom requirements; this merges the SFT and alignment stages.
The $b_{i}$’s signify the minimum baselines for each preference reward function $r_{i}(\cdot)$ and the constraints are enforced on average.

Compared to the previous approach, we no longer rely on heuristics to find a set of weights $\alpha_{i}$’s to satisfy the minimum requirements; we can do so directly through the constraints.
Furthermore, with the same objective as SFT, we can directly maintain task performance without any deviation penalty.
Additionally, note that whenever a constraint is satisfied, its influence vanishes.
For instance, if the LLM is naturally harmless and $r_{\text{harmless}}(y|x)\geq b_{\text{harmless}}$, then the constraint is not active and the LLM will not be penalized.
Conversely, the previous approach would further penalize the LLM.

#### Notation

For ease of notation, we rewrite the constrained problem in Eqs. 3 and 4 as follows:

$$ $\min_{\theta}\ L\left(\theta\right)\ \text{subject to}\ C_{i}\left(\theta \right)\ \leq\ 0\ \text{for all}\ i\in\left\{1,2,\ldots,k\right\},$ (5) $$

with the objective $L(\theta)=\mathds{E}_{(x,y)\sim p(\cdot)}[l_{\theta}(y|x)]$ and constraints
$C_{i}(\theta)=\mathds{E}_{\begin{subarray}{c}(x,\cdot)\sim p(\cdot)\\
y\sim\pi_{\theta}(\cdot|x)\end{subarray}}[b_{i}-r_{i}(y|x)]$.

### 4.1 Types of constraints

While we write the constraints in Eq. 4 as expectation/average constraints, other forms exist.
For instance, uniform constraints impose a minimum reward on every generated (prompt, response) pair:

$$ $r_{i}\left(y|x\right)\ \geq\ b_{i}\ \text{for all}\ \left(x,\cdot\right)\sim p \left(\cdot\right),\ y\sim\pi_{\theta}\left(\cdot|x\right)\ \text{and all}\ i \in\left\{1,2,\ldots,k\right\}.$ (6) $$

Additionally, chance constraints bound the probability of the inequality holding away from zero:

$$ $\mathds{P}_{\begin{subarray}{c}\left(x,\cdot\right)\sim p\left(\cdot\right)\\ y\sim\pi_{\theta}\left(\cdot|x\right)\end{subarray}}\left[r_{i}\left(y|x\right )\ \geq\ b_{i}\right]\ \geq\ 1-\epsilon_{i}\ \text{for all}\ i\in\left\{1,2, \ldots,k\right\}.$ (7) $$

While these constraints are not equivalent, they are related.
We can rewrite Eq. 7 in the form of expectation constraints by using $1-\epsilon_{i}$ as the threshold and taking the expectation of the indicator $\mathds{1}\{r_{i}(y|x)\geq b_{i}\}$.
Moreover, Eq. 6 implies Eq. 4, but the converse is not true.
Unfortunately, Eq. 6 is difficult to achieve in practice, especially when the data distribution is unknown.

We continue using the expectation constraints, but similar discussions can extend to the other types.

### 4.2 Lagrange multipliers

We can introduce Lagrange multipliers $\lambda_{i}\geq 0$ for the constraints and obtain the Lagrangian:

$$ $\mathcal{L}\left(\theta\right)\ =\ L\left(\theta\right)+\sum_{i=1}^{k}\lambda_ {i}C_{i}\left(\theta\right).$ (8) $$

There is a rich literature connecting the Lagrangian with constrained optimization.
Notably, the KKT conditions (Karush, ; Kuhn & Tucker, ) provide sufficiency conditions for global optimality under convexity, where the solution can be obtained by finding the saddle point of the Lagrangian.
However, these conditions are not enough for highly non-convex scenarios like ours.

Nonetheless, the Lagrangian is instructive in understanding the relative importance of the constraints.
For an active constraint, i.e., one satisfied with equality, the corresponding Lagrange multiplier can be non-zero; the larger its value, the more important the constraint.
Conversely, for an inactive constraint, i.e., one satisfied with strict inequality, the corresponding Lagrange multiplier must vanish to 0.
This is known as complementary slackness and is one of the KKT conditions.

### 4.3 Logarithmic barrier

A practical way to enforce constraints is with barrier functions.
Consider the (relaxed) log-barrier:

$$ $\mathcal{B}_{\mu,s}\left(z\right)\ =\ \begin{cases}-\mu\log\left(-z\right),&z \ \leq\ -s\\ \frac{\mu}{s}z+\mu-\mu\log s,&z\ >\ -s\end{cases},\ \text{and hence}\ \partial _{z}\mathcal{B}_{\mu,s}\left(z\right)\ =\ \frac{\mu}{\max\left(-z,s\right)},$ (9) $$

with parameters $\mu,s>0$.
This is a convex, continuous, and differentiable function, which is valid for all $z\in\mathds{R}$.
Importantly, for $s=\mu^{2}$, this barrier function converges to the characteristic function $\chi\{z\leq 0\}$ as $\mu\rightarrow 0$, i.e., it takes the value 0 when $z\leq 0$ and $\infty$ otherwise (Tal et al., ; Nash et al., ; Hauser & Saccon, ; Feller & Ebenbauer, ); the condition $s=\mu^{2}$ is sufficient, but not necessary (Kervadec et al., ).
This convergence to the characteristic function is visually depicted in Fig. 1, showing the change in the log-barrier function as we gradually decrease $\mu$.

We can now use the log-barrier to enforce the constraints in Eq. 5 and simply add them to the objective.
We obtain an *unconstrained* objective, with $\mu$ controlling the strength of the constraints:

$$ $\mathcal{G}_{\mu}\left(\theta\right)\ =\ L\left(\theta\right)+\frac{1}{k}\sum_ {i=1}^{k}\mathcal{B}_{\mu,\mu^{2}}\left(C_{i}\left(\theta\right)\right).$ (10) $$

Figure: Figure 1: The relaxed logarithmic barrier. We depict the convergence of the relaxed logarithmic barrier $\mathcal{B}_{\mu,\mu^{2}}(z)$ to the characteristic function $\chi\{z\leq 0\}$ as $\mu\rightarrow 0$. We gradually decrease $\mu$ from 1 (blue) to 0.01 (red). Consequently, $\mathcal{B}_{\mu,\mu^{2}}(z)$ gets closer to 0 for $z\leq 0$ and increases to $\infty$ otherwise.
Refer to caption: x1.png

## 5 Lagrange Large Language Models (L3Ms)

We have thus far formulated the SFT and alignment stages as a constrained optimization problem in Eq. 5.
We proceed to find solutions for the same by solving the unconstrained objective in Eq. 10.
We call the family of models obtained in this way L3Ms, i.e., Lagrange Large Language Models.

### 5.1 Optimization procedure

Since the log-barrier converges to the characteristic function as $\mu\rightarrow 0$, we want to find the minimizer of $\mathcal{G}_{\mu}(\theta)$ for a very small $\mu$.
However, doing so directly leads to instabilities as the objective function is ill-conditioned.
Instead, it is common practice to follow an iterative procedure where one finds the minimizer for a fixed $\mu$, reduces $\mu$, and repeats (Curtis et al., ).
Specifically, the procedure is instantiated with initial values $\theta_{0}$, $\mu_{1}$, and $0<\gamma<1$.
On the $t$-th iteration, $\mu_{t}\leftarrow\gamma\mu_{t-1}$ is reduced and $\theta_{t}\leftarrow\arg_{\theta}\min\mathcal{G}_{\mu_{t}}(\theta)$ (with the initialization at $\theta_{t-1}$).
In doing so, the constraints are enforced gradually, nudging the LLM to satisfy them over the training procedure while avoiding instabilities.
Furthermore, as $\{\mu_{t}\}\searrow 0$, the weights $\theta_{t}$ converges to the minimizer of the constrained problem.

It is impossible to minimize $\mathcal{G}_{\mu_{t}}(\theta)$ exactly in many practical applications.
Instead, at each iteration, we take a single optimization step toward the solution.
Doing so is amenable to stochastic gradient methods and mitigates computational overhead — the training proceeds as normal while the value of $\mu$ is reduced over the course of the training.
One can guarantee convergence of such a procedure to the optimal solution in some settings; for instance, Curtis et al. () prove convergence when dealing with box constraints.
However, convergence in a scenario like ours is not guaranteed.
Nonetheless, we will experimentally demonstrate its use for our constrained problems.

We employ stochastic gradient methods and derive the gradient of our objective function directly:

$$ $\partial_{\theta}\mathcal{G}_{\mu}\left(\theta\right)\ =\ \partial_{\theta}L \left(\theta\right)+\frac{\mu}{k}\sum_{i=1}^{k}\frac{\partial_{\theta}C_{i} \left(\theta\right)}{\max\left(-C_{i}\left(\theta\right),\mu^{2}\right)}.$ (11) $$

This follows immediately from Eqs. 9 and 10.
Note that the $\partial_{\theta}C_{i}(\theta)$’s are also known as the policy gradients in reinforcement learning literature.
We discuss our strategy for estimating these gradients in Appendix B and refer readers to Schulman et al. () for a more detailed review.

### 5.2 Connection to Lagrange multipliers

The log-barrier and the Lagrangian are intrinsically connected; this becomes evident when comparing Eq. 11 with the (gradient of the) Lagrangian in Eq. 8.
In particular, we define the multipliers:

$$ $\hat{\lambda}_{i}\ =\ \frac{\mu}{k\max\left(-C_{i}\left(\theta\right),\mu^{2} \right)},$ $$

corresponding to the gradients $\partial_{\theta}C_{i}(\theta)$’s in Eq. 11.
They can be interpreted as Lagrange multipliers: for active constraints, $\hat{\lambda}_{i}=1/k\mu$ is non-zero; for inactive constraints, $\hat{\lambda}_{i}=-\mu/kC_{i}(\theta)$ vanishes to 0 0 as $\mu\rightarrow 0$.
Hence, the KKT complementary slackness condition is satisfied by design.

### 5.3 Implementation details

#### Alternating objective and gradient clipping.

A simple, yet effective way to ensure stable training of large models is gradient clipping (Goodfellow et al., ; Zhang et al., ).
We employ this technique, albeit with the modification of clipping the gradients of both the task objective and the constraints separately, as they can have varying magnitudes.
We achieve this by alternating between reducing the task objective and enforcing the constraints by flipping a fair coin to select one or the other.
While this doubles the number of steps to achieve the same effect, it does not increase the amount of work done as now only one part of the objective or the other is evaluated at each step.

#### Length normalization.

The gradient of our objective function in Eq. 11 involves the log-likelihoods of the generated responses through the gradients $\partial_{\theta}C_{i}(\theta)$’s (cf. Eq. 12).
To avoid a response length bias, we length-normalize the log-likelihoods, akin to the definition of perplexity.

#### Estimating the mean preference rewards.

We need to estimate the expectations involved in the gradient of our objective function in Eq. 11.
The expectations in the numerators can be estimated with the per-mini-batch Monte Carlo averages (Mohamed et al., ).
However, $C_{i}(\theta)$ in the denominator needs careful consideration.
Note that: (i) $C_{i}(\theta)$ does not involve the gradient, so its estimates can include information from previous mini-batches to reduce variance, and (ii) since the weights are updated during training, $C_{i}(\theta)$ is non-stationary.
Consequently, we use an exponential moving average estimate for the mean (offset) preference rewards $C_{i}(\theta)$ in the denominator.

## 6 Experimental results

To illustrate the versatility of L3Ms, we empirically evaluate them on two criteria: (i) the satisfaction of the imposed custom constraints, and (ii) the task perplexity objective.
Note that L3Ms have essentially the same time complexity as traditional approaches: the SFT and alignment stages have been combined into one and the log-barrier parameter is adjusted during the training procedure itself.

### 6.1 Setup

We use LLaMA-7B (Touvron et al., ) for all our experiments, as it is a lightweight LLM pre-trained on a large corpus.
We are interested in the instruction-following task, for which we use UltraChat (Ding et al., ), a large-scale dataset of instructional conversations.
We refer to the model trained via the SFT objective (without alignment) as the *SFT* model.
We train LLMs using the min-max approach to find the saddle-point of the Lagrangian, as proposed by Moskovitz et al. (); Dai et al. (), referring to them as *MMs*.
Lastly, we refer to models trained using our approach as *L3Ms*.
We use the Transformers package (Wolf et al., ) for our implementation and run experiments on NVIDIA H100s.
Further details on our setup are included in Appendix A.

In what follows, we use different preference reward functions and vary the custom constraint requirements.
All results are obtained on a held-out test dataset (not seen during training or validation).

### 6.2 Length constrained L3Ms

Consider tasks where the lengths of the responses need to be contained in the range $[l_{\text{low}},l_{\text{high}}]$ to control its verbosity, in summarization tasks for example (Makino et al., ).
The natural choice of reward functions in this case are the ones that compute the response length and its negation via $r_{1}(y|x)=|y|$ and $r_{2}(y|x)=-|y|$; correspondingly, these rewards are to be controlled with the requirements of $l_{\text{low}}$ and $l_{\text{high}}$ respectively. Note that these rewards are perfectly anti-correlated.

If we naively average the rewards, any unconstrained formulation of alignment (including RLHF) will be ineffective as the loss will always vanish due to the anti-correlation.
We could use a weighted average and tune the weights heuristically, but this is tedious.
Instead, we use the constrained formulation and directly constrain the rewards $r_{1}(y|x)=|y|\geq l_{\text{low}}$ and $r_{2}(y|x)=-|y|\geq-l_{\text{high}}$.

We train several L3Ms with varying length constraints.
We illustrate the distributions of the generated response lengths (in tokens) and report the perplexities achieved on the task-related data in Fig. 2.
We observe that the mean response lengths are in the required range in each case, satisfying the imposed expectation constraints.
Additionally, the task perplexities increase slightly as the constraints on the response lengths are made more stringent.
However, there is little to no degradation relative to the SFT model, with all mean task perplexities being within 0.02 standard deviations.

The examples included in Table 1 are generated from such L3Ms.
While all the responses correctly answer the prompts, their lengths vary corresponding to the length constraints imposed on them.

Figure: Figure 2: Length constrained L3Ms. We report the response lengths (in tokens) and task perplexities of the SFT model and the L3Ms with varying length constraints. *Left:* The mean response length with the mean and standard deviation of the task perplexities. *Right:* The distribution of the response lengths. The notches indicate the medians and their 95% confidence intervals, the boxes show the $\pm$25% quantiles, and the whiskers denote the 1.5$\times$ interquartile ranges. The white circles mark the means and the black dashed lines depict the constraints imposed on the different L3Ms.
Refer to caption: x2.png

### 6.3 Helpful and harmless L3Ms

Next, we consider the Helpful and Harmless preferences that have been extensively used in the LLM alignment literature (Ji et al., ; Wang et al., ; Zhou et al., ; Guo et al., ).
Specifically, we utilize the datasets by Bai et al. () to train two preference reward functions respectively.
These learned reward functions are negatively correlated (Bai et al., ; Dai et al., ).
Furthermore, note that the numerical outputs of both these reward functions are interpreted as ratings such that a higher numerical value indicates higher helpfulness/harmlessness and vice versa.

We train several L3Ms with varying HH constraints.
We compare our L3M approach of using log-barriers with the min-max optimization by Moskovitz et al. (); Dai et al. () to find the saddle-point of the Lagrangian (MMs).
In our experience, learning the Lagrange multipliers in this way is extremely sensitive to the choice of the learning rate.
Moreover, to avoid loading an additional reference LLM during the training process, as is done by Moskovitz et al. (); Dai et al. (), our implementation of MM minimizes the task perplexity directly (as is done by L3Ms as well).

Fig. 3 shows the achieved task perplexities and helpful-harmless rewards for the different LLMs.
At initialization, the helpful and harmless rewards are both low, with a high task perplexity of 1.316$\pm$0.4.
This is improved upon by the SFT model, reducing the perplexity to 0.805$\pm$0.3 and attaining a high helpfulness reward (attributed to the task data instilling instruction-following capabilities).
Further, MMs sacrifice task performance to over-satisfy the constraints, with mean task perplexities higher than 0.822.
On the other hand, L3Ms satisfy the imposed helpful-harmless reward constraints with lower task perplexities (the mean perplexities are in the range of 0.804-0.820).
We attribute this to the L3Ms having better Lagrange multipliers by design rather than learning them as is done in MMs.

Figure: Figure 3: Helpful and harmless L3Ms. We report the helpful-harmless rewards and task perplexities achieved by the different LLMs. *Left:* The helpful-harmless rewards attained by the LLM at initialization (at the bottom-left in blue), the SFT model (at the top-left in orange), the MMs (in green), and the L3Ms (in red). We depict the imposed constraints in black, with the dotted gray lines connecting LLMs to their corresponding constraints. Note that constraints are satisfied if the obtained reward point is at the top-right of its corresponding constraint point. *Right:* The mean and standard deviation of the task perplexities for MMs and L3Ms, along with their corresponding constraints; the task perplexity at initialization is 1.316$\pm$0.4 and that of the SFT model is 0.805$\pm$0.3.
Refer to caption: x3.png

## 7 Conclusions

In this work, we formulate the SFT and alignment processes for LLMs as one of constrained optimization: we minimize the task perplexity while simultaneously imposing custom constraints on preferences.
This enables customization of the LLM to different preferential properties while maintaining performance on the original task.
Consequently, we propose Lagrange Large Language Models (L3Ms) to solve this constrained problem by incorporating the constraints in the objective function using the logarithmic barrier.
We include experimental results to illustrate the customization qualities of L3Ms, which can fit to different preferences, providing a personalized user experience.

## Appendix A Experimental setup

In addition to Section 6.1, here we provide further details of the experimental setup.

#### Task data

We use UltraChat (Ding et al., ), a large-scale dataset of instructional conversations, as our task data to induce instruction-following capabilities.
Since each sample contains a sequence of multi-turn question-answer pairs, we randomly sample one of the answers as the response and treat the preceding dialogue as the prompt.
We then filter such (prompt, response) pairs to a maximum token length of 512.
Consequently, we obtain 340k training samples, 1.7k validation samples, and 1.7 test samples, split randomly as the dataset does not contain train-val-test splits.

#### Hyper-parameters

We train LLMs for 1 epoch on the task data, with a mini-batch size of 64.
We use Adam with a learning rate of 10^-6, and a cosine learning rate scheduler (with 5% of the epoch used for warmup).
We set weight decay to 0.1 and the gradient clipping maximum norm to 1.
We also utilize 16-bit (mixed) precision training and gradient checkpointing.
We exponentially decay the log-barrier parameter $\mu$ during training from 1 to 10^-6, and use a smoothing factor of 0.1 for the exponential moving average.
Lastly, we use top-$p$ sampling ($p$ set to 0.9) for response generation.
Apart from this, we use the default hyper-parameters in the Transformers library (Wolf et al., ).

### A.1 Learning preference reward models

While some preference reward functions are engineered or rule-based, others are learned.
Such preferences can often be difficult to quantify.
Alternatively, it is easier to compare responses with respect to the preference, e.g., ranking them from most to least helpful.
Consequently, the data for learning preference reward models consist of tuples of the form $(x,y_{+},y_{-})$, where the prompt $x$ is accompanied by two responses $y_{+}$ and $y_{-}$, with the former response being preferred over the latter.

The preference reward model is denoted by $r_{\phi}(\cdot)$ (parameterized by $\phi$).
Assuming the Bradley-Terry model (Bradley & Terry, ), the model’s predicted probability for preferring $y_{+}$ over $y_{-}$ is:

$$ $p_{r_{\phi}}\left(y_{+}\succ y_{-}|x\right)\ =\ \sigma\left(r_{\phi}\left(y_{+ }|x\right)-r_{\phi}\left(y_{-}|x\right)\right),$ $$

with the standard logistic function $\sigma(\cdot)$.
Then, the model minimizes the negative log-likelihood:

$$ $\min_{\phi}\ \mathds{E}_{\left(x,y_{+},y_{-}\right)\sim t\left(\cdot\right)} \left[-\log p_{r_{\phi}}\left(y_{+}\succ y_{-}|x\right)\right].$ $$

Taking inspiration from Rafailov et al. (), we initialize the preference reward model $r_{\phi}(\cdot)$ as a pre-trained LLM, and set the reward to be its length-normalized log-likelihood.
In this way, we utilize the pre-trained model fully, not just its backbone.
As the preference reward model is fine-tuned, its log-likelihoods are updated to differentiate the preferred responses from the rejected ones.

#### Helpful and harmless data

We use the Helpful and Harmless (Bai et al., ) preference data to learn two reward models respectively.
We obtain 161k training samples and 9k test samples after filtering the (prompt, response) pairs to a maximum token length of 2024; 3/4-th are for helpfulness while the remaining 1/4-th are for harmlessness.
We further set 5% of the training data for validation.

#### Hyper-parameters

We initialize all preference reward functions with LLaMA-7B.
We train for 2 epochs with a mini-batch size of 64.
We use Adam with a learning rate of 10^-6, and a cosine learning rate scheduler (with 10% of the epoch used for warmup).
We set weight decay to 0.1 and the gradient clipping maximum norm to 1.
We also utilize 16-bit (mixed) precision training and gradient checkpointing.
Apart from this, we use the default hyper-parameters in the Transformers library (Wolf et al., ).
We validate after every 10% of the epoch and save the best model.

## Appendix B Policy gradient

We are interested in the policy gradient $\partial_{\theta}C_{i}(\theta)$.
Note that when taking derivatives with respect to the parameters of a distribution in an expectation, we can use the log-derivative trick:

$$ $\begin{gathered}\partial_{\theta}\mathds{E}_{x\sim p_{\theta}\left(\cdot\right )}\left[f\left(x\right)\right]\ =\ \int dxf\left(x\right)\partial_{\theta}p_{ \theta}\left(x\right)\ =\ \int dxf\left(x\right)\frac{p_{\theta}\left(x\right) }{p_{\theta}\left(x\right)}\partial_{\theta}p_{\theta}\left(x\right)\\ =\ \int dxf\left(x\right)p_{\theta}\left(x\right)\partial_{\theta}\log p_{ \theta}\left(x\right)\ =\ \mathds{E}_{x\sim p_{\theta}\left(\cdot\right)}\left [f\left(x\right)\partial_{\theta}\log p_{\theta}\left(x\right)\right].\end{gathered}$ $$

Applying this to the policy gradient $\partial_{\theta}C_{i}(\theta)$ yields,

$$ $\partial_{\theta}C_{i}\left(\theta\right)\ =\ \partial_{\theta}\mathds{E}_{ \begin{subarray}{c}\left(x,\cdot\right)\sim p\left(\cdot\right)\\ y\sim\pi_{\theta}\left(\cdot|x\right)\end{subarray}}\left[c_{i}\left(y|x\right )\right]\ =\ \mathds{E}_{\begin{subarray}{c}\left(x,\cdot\right)\sim p\left( \cdot\right)\\ y\sim\pi_{\theta}\left(\cdot|x\right)\end{subarray}}\left[c_{i}\left(y|x\right )\partial_{\theta}\log\pi_{\theta}\left(y|x\right)\right],$ (12) $$

where $c_{i}(y|x)=b_{i}-r_{i}(y|x)$.
This is the simplest form of the policy gradient and can be estimated as Monte Carlo averages.
We refer readers to Schulman et al. () for a review of other estimates.

## Peer Reviews

confidence: 3
contribution: 3
initial_rating: 6
presentation: 3
questions: -Are there any plans to incorporate other evaluation metrics in addition to perplexity to better evaluate the performance of L3Ms?

-Will the authors explore the application of L3Ms to a wider range of tasks, such as computational and reasoning tasks? How would the method be adapted to optimize for task-related metrics specific to these tasks?
soundness: 3
strengths: The formulation of SFT and alignment as a constrained optimization problem and the use of logarithmic barriers in L3Ms is a novel approach that has the potential to improve the customization of LLMs for different applications.

The paper provides a solid theoretical foundation for the proposed method, including discussions on constraint types, Lagrange multipliers, and the connection to the KKT conditions.

The experimental results on length-constrained L3Ms and helpful and harmless (HH) L3Ms show that the proposed method can effectively customize LLMs according to different constraints while maintaining performance on the original task.
summary: This paper presents Lagrange large language models (L3Ms), which formulate supervised fine-tuning and alignment of large language models as a constrained optimization problem. L3Ms use logarithmic barriers to enforce constraints, allowing for customization across diverse applications without relying on heuristics. The paper demonstrates the versatility and efficacy of L3Ms in achieving tailored alignments.
weaknesses: The experiments mainly consider length constraints and helpful and harmless preferences. It would be interesting to see how the proposed method performs on a more diverse set of tasks, such as computational and reasoning tasks, and whether it can optimize for task-related metrics specific to those tasks.

The paper primarily focuses on perplexity as an evaluation metric. It would be beneficial to include other metrics to provide a more comprehensive assessment of the performance of L3Ms.Are there any plans to incorporate other evaluation metrics in addition to perplexity to better evaluate the performance of L3Ms? If so, which metrics are being considered and why?
Will the authors explore the application of L3Ms to a wider range of tasks, such as computational and reasoning tasks? How would the method be adapted to optimize for task-related metrics specific to these tasks?

---

confidence: 3
contribution: 3
initial_rating: 5
presentation: 2
questions: See the above weaknesses.
soundness: 3
strengths: 1. The paper innovatively formulates SFT and alignment as a constrained optimization problem, offering a fresh perspective that avoids traditional heuristic methods.
2. L3Ms, with their logarithmic barriers, demonstrate technical excellence and adaptability across diverse applications, ensuring robust performance.
3. By providing a systematic approach to fine-tuning LLMs, this research addresses a critical need and offers practical benefits for both academic and industrial use.
summary: This paper presents a novel approach to the supervised fine-tuning (SFT) and alignment of large language models (LLMs), formulating it as a constrained optimization problem. The authors propose Lagrange large language models (L3Ms), which use logarithmic barriers to enforce application-specific requirements, eliminating the need for heuristic-driven processes. This approach allows for the customization of L3Ms across diverse applications. The paper demonstrates the versatility and efficacy of L3Ms through experimental results, showing their ability to achieve tailored alignments for various applications. This work contributes a new perspective and methodology to the fine-tuning and alignment of LLMs, enhancing their adaptability and effectiveness across different applications.
weaknesses: 1. The paper's experimental section may lack comprehensive evaluations, which could limit the full demonstration of L3Ms' capabilities and robustness across a wide range of scenarios.
2. The choice of datasets used in the experiments appears to be restricted, potentially affecting the generalizability of the findings and the ability to assess the method's effectiveness on varied data types.
3. Utilizing LLMs with only 7 billion parameters might restrict the scalability and performance of L3Ms, as larger models are often necessary for handling complex tasks and achieving state-of-the-art results.
4. Writing Issues: The paper has some writing issues, including incorrect formula numbering, which can cause confusion and disrupt the flow of the paper. Improving the clarity and accuracy of the writing would enhance the overall quality and readability of the paper.

---

confidence: 3
contribution: 3
initial_rating: 6
presentation: 4
questions: - Can authors provided more discussions on computation overheads introduced in this work in comparison to the general SFT and other related works (https://openreview.net/forum?id=TyFrPOKYXw, https://openreview.net/forum?id=gkfUvn0fLU).
soundness: 4
strengths: - Clear problem statement. This work discusses the shortcomings of previous works on constrained RLHF and proposes corresponding improvements to solve it, which seems convincing to me.
- Good optimization problem conversion. I find it quite interesting and instructive how this work converts a general target of balancing task performance and multiple specific requirements into a solvable object function of Lagrangian and introduces the necessary components of the logarithmic barrier to make it practically work.
summary: This work introduces a new method for fine-tuning and aligning large language models (LLMs) by treating these processes as a constrained optimization problem. Instead of relying on heuristic methods, the authors propose using Lagrange Large Language Models (L3Ms) that incorporate constraints directly into the optimization through logarithmic barriers. This approach allows models to maintain performance on primary tasks while being customized to meet specific user or application-related preferences. The paper provides experimental evidence showing that L3Ms are effective.
weaknesses: - My main concern is with the experimental results in Figure 3, where MM appears to achieve a better performance frontier than L3M. Although L3M results in lower perplexity (PPL), it's unclear how significantly this affects real task performance, as the improvement seems marginal. Could the authors provide further discussion on this?
- The constraints used in the experiments are somewhat limited in terms of variety. It's unclear how the proposed algorithms would perform in scenarios with more complex or demanding constraints.
- The experimental setups seem relatively simple, which may not fully capture the real-world performance of the fine-tuned LLMs.

---

confidence: 3
contribution: 2
initial_rating: 3
presentation: 2
questions: - Why the log barrier parameter $\mu$ should be decayed during training? (Lines 715-716) 

- As the log barrier parameter $\mu$ is a hyper-parameter of L3M, what the relationship between its value and L3M performance?
soundness: 3
strengths: - The paper suggests to formulate SFT and alignment into one constrained optimization problem and optimize its approximate Lagrangian.
summary: The paper suggests to model SFT and alignment into one constrained optimization problem and proposes a method called L3M, which is to optimize such constrained optimization problems via approximate Lagrangian.
weaknesses: - The core objective Eq.(10) $\mathcal{G} _ \mu(\theta)=L(\theta)+\frac{1}{k}\sum _ {i=1}^k\mathcal{B} _ {\mu,\mu^2}(C _ i(\theta))$ is equivalent to the lowerbound of multi-objective RLHF objective with induced reward models and a SFT term. Given a reward model $r _ i(x,y)$, a monotonically increasing function $f _ 1(x)=\mathcal{B} _ {\mu,\mu^2}(x)$, and a monotonically decreasing function $f _ 2(x)=b _ i-x$, we can induce a new reward model $r _ i'(x,y)=-f _ 1(f _ 2(r(x,y)))=-\mathcal{B} _ {\mu,\mu^2}(b _ i-r _ i(x,y))$. As $\mathcal{B} _ {\mu,\mu^2}(x)$ is convex,
$$
\begin{split}
\min &\mathbb{E} _ {x,y}[-r _ i'(x,y)]\\\\
=&\mathbb{E} _ {x,y}[\mathcal{B} _ {\mu,\mu^2}(b _ i-r(x,y))] \\\\
\geq&\mathcal{B} _ {\mu,\mu^2}(\mathbb{E} _ {x,y}[b _ i-r(x,y)])\\\\
=&\mathcal{B} _ {\mu,\mu^2}(C _ i(\theta)),
\end{split}
$$
where the inequality holds by jensen’s inequality. It can be extend into multi-objective scenario with a SFT term $L(\theta)$:
$$
\begin{split}
\min &L(\theta)+\mathbb{E} _ {x,y}\left[\frac{1}{k}\sum _ {i=1}^k-r _ i'(x,y)\right]\\\\
=&L(\theta)+\frac{1}{k}\sum _ {i=1}^k\mathbb{E} _ {x,y}[-r _ i'(x,y)]\\\\
\geq&L(\theta)+\frac{1}{k}\sum _ {i=1}^k\mathcal{B} _ {\mu,\mu^2}(C _ i(\theta))=\mathcal{G} _ \mu(\theta),
\end{split}
$$
which is Eq.(10) of the paper.

- For baselines, as Line 355-358 writed: “L3Ms have the same time complexity as traditional approaches as we combine the SFT and alignment stages into one”. Traditional SFT+alignment, having the same training budget with L3M, should be considered as a baseline.

- For benchmarks, more instruction following tasks should be evaluated to demonstrate the generalization of L3M across diverse distribution.

- For evaluations, 1) ppl (perplexity) can not directly reflect the instruction following ability of an aligned LM. 2) As reward hacking is a considerable problem in RLHF, the score of reward models which are involved into L3M training is not a valid metric. Other metrics should be considered to evaluate the alignment.

Meta-review: Summary of the paper: This paper introduces Lagrange Large Language Models (L3Ms), an approach to the SFT and alignment of LLMs by framing these tasks as a constrained optimization problem. Logarithmic barriers are used to enforce application-specific constraints, eliminating the need for heuristic methods and allowing for greater customization across diverse applications. Experimental results demonstrate the versatility and efficacy of L3Ms, showcasing their ability to achieve tailored alignments while maintaining strong performance on primary tasks. 

Strengths of the paper: 
- Well-Motivated: The paper identifies shortcomings in existing constrained RLHF methods and proposes convincing improvements, making the optimization problem more practical and solvable.
- Innovative Approach and Theoretical Foundation: The formulation of SFT and alignment as a constrained optimization problem, utilizing logarithmic barriers in L3Ms, offers a fresh perspective and a solid theoretical basis, including discussions on constraint types, Lagrange multipliers, and KKT conditions.
- Experimental Validation: The experimental results effectively demonstrate the method's capability to customize LLMs under various constraints while maintaining performance on original tasks and avoiding heuristic-driven processes.

Weaknesses of the paper: All reviewers share similar concerns regarding the evaluation:
- Limited Datasets and Tasks Evaluated (Reviewers uf9P, PMWz, oGFz, tPT4): The choice of datasets/tasks in the experiments appears limited, which may affect the generalizability of the findings and hinder the assessment of the method's effectiveness across different scenarios. L3Ms are recommended to be evaluated on a broader variety of tasks, such as computational and reasoning challenges. 
- Need for More Evaluation Metrics (Reviewers uf9P, oGFz, tPT4): Incorporating additional evaluation metrics beyond perplexity could be beneficial, providing a more comprehensive understanding of L3Ms' performance.
- Insufficient Results on Larger Models (Reviewer PMWz): Using models with only 7 billion parameters in the experiment may limit the scalability and performance of L3Ms.

Reasons for the Decision
During the rebuttal, the authors primarily addressed the conceptual issues raised by the reviewers. I believe that most of these conceptual concerns have been adequately resolved after reviewing all the comments. However, the authors did not include additional experimental results as suggested by the reviewers. After considering the authors' responses, I am partially convinced of their reasoning for not using evaluation metrics beyond perplexity (as discussed with Reviewer tPT4) and for not performing experiments on larger models (Reviewer PMWz). Nonetheless, I still believe that the authors should evaluate the proposed method across a wider range of tasks to empirically justify their claim that "the proposed L3M algorithm can easily extend to new tasks (along with corresponding task-related rewards) without modifications since assumptions on the task types are not placed." Upon careful consideration, I am slightly leaning towards accepting this paper. It is well-motivated, and the proposed method is innovative with a solid theoretical foundation. More importantly, this work contributes a new perspective to the alignment of LLMs, which could provide valuable insights for the research community. Nevertheless, I strongly recommend that the authors include more empirical evidence to support their method in the camera-ready version.

Decision: Accept (Poster)