# Language models

If the inputs are texts, the network can be a pretrained language model. `LoRARegressor` puts LoRA adapters and a small head on one, as in [Kristiadi et al. 2024](https://arxiv.org/abs/2402.05015), and `LaplaceDiscreteSurrogate` finetunes it and fits the Laplace approximation over the adapters and the head. It needs the `llm` extra (and pandas, for the data on this page):

``` bash
pip install "laplacekit-bayesopt[llm]" pandas
```

As an example, we look for the molecule with the lowest redox potential among 300 from the Redox-MER dataset. The molecules are SMILES strings.

``` python
import pandas as pd
import torch

from laplacekit_bayesopt import LaplaceDiscreteSurrogate
from laplacekit_bayesopt.discrete_acqf import expected_improvement
from laplacekit_bayesopt.llm import LoRARegressor

torch.manual_seed(0)

url = (
    "https://raw.githubusercontent.com/wiseodd/lapeft-bayesopt/"
    "master/examples/data/redox_mer.csv"
)
df = pd.read_csv(url).sample(300, random_state=0)
smiles = df["SMILES"].tolist()
y = df["Ered"].to_numpy()

print(smiles[:3])
print(f"lowest Ered of all: {y.min():.3f}")
```

    ['CCOCN(C(C)=O)c1c(C(F)(F)F)c(C#N)c(SC(F)(F)F)c2nsnc12', 'CCOCN(C(C)=O)c1c(SC(F)(F)F)c(N(C)C)c(SC)c2nsnc12', 'CCOCN(C(C)=O)c1c(SC)c(N(C)C)c(C#N)c2nsnc12']
    lowest Ered of all: 1.640

The loop is the same as with any other network: see [Candidate sets](../quickstart/candidates.llms.md). Since we minimize, the acquisition takes `maximize=False`.

``` python
seen = torch.randperm(len(smiles))[:10].tolist()

for i in range(3):
    model = LaplaceDiscreteSurrogate(
        LoRARegressor(),
        [smiles[j] for j in seen],
        y[seen],
    )

    pending = [j for j in range(len(smiles)) if j not in seen]
    pred = model.predict([smiles[j] for j in pending])
    ei = expected_improvement(pred, best=y[seen].min(), maximize=False)
    seen.append(pending[ei.argmax()])

    print(f"round {i + 1}: best = {y[seen].min():.3f}")
```

    round 1: best = 1.708
    round 2: best = 1.708
    round 3: best = 1.708

Each round finetunes the model anew, which takes about a minute on a CPU. We only do 3 rounds here so that the page runs quickly. In practice, BO runs for hundreds or thousands of rounds.

## Other models

The default model is [T5Chem](https://huggingface.co/GT4SD/multitask-text-and-chemistry-t5-base-augm), and `LoRARegressor` takes other models on the Hugging Face Hub by name:

``` python
LoRARegressor("facebook/esm2_t6_8M_UR50D")  # protein sequences
```

It handles encoders (BERT, ChemBERTa, ESM-2), encoder-decoders (T5, BART), of which only the encoder is used, and decoders (GPT-2, Llama). Its options say how a text becomes one vector (`pooling`), wrap each text in a template (`prompt`), and pick the layers that get adapters (`target_modules`)—see the [reference](../reference/llm.LoRARegressor.llms.md).

## Fixed features

Finetuning is the expensive part. Alternatively, we can keep the language model fixed: `TextEncoder` embeds every text once, and a small network on the embeddings is the surrogate.

| Network | Trade-off |
|----|----|
| `LoRARegressor()` | Better, but takes about a minute per round on a CPU. |
| A small MLP on `TextEncoder().embed(texts)` | Much cheaper (the texts are embedded once), but less accurate. |

``` python
from torch import nn

from laplacekit_bayesopt.llm import TextEncoder

encoder = TextEncoder()
features = encoder.embed(smiles)
print(features.shape)


def make_net():
    return nn.Sequential(
        nn.Linear(encoder.dim, 50),
        nn.Tanh(),
        nn.Linear(50, 50),
        nn.Tanh(),
        nn.Linear(50, 1),
    )


seen = seen[:10]

for i in range(10):
    model = LaplaceDiscreteSurrogate(make_net(), features[seen], y[seen])

    pending = [j for j in range(len(smiles)) if j not in seen]
    pred = model.predict(features[pending])
    ei = expected_improvement(pred, best=y[seen].min(), maximize=False)
    seen.append(pending[ei.argmax()])

    print(f"round {i + 1:2d}: best = {y[seen].min():.3f}")
```

    torch.Size([300, 768])
    round  1: best = 1.856
    round  2: best = 1.729
    round  3: best = 1.726
    round  4: best = 1.708
    round  5: best = 1.708
    round  6: best = 1.708
    round  7: best = 1.708
    round  8: best = 1.708
    round  9: best = 1.708
    round 10: best = 1.708

Again, we only do 10 rounds here—in practice, BO runs for hundreds or thousands.
