Skip to content

Train in one session

A steering vector, a probe or a LoRA is a few small tensors trained against a frozen model. On NDIF the whole loop runs in one session: the parameters, the optimizer and the data are created on the server, and only the trained tensors come back.

The pattern

This session trains a steering vector, added to the output of layer 10, that flips the model's answer on movie-review sentiment. Gradients flow from the loss back through layers 11 to 35 of the remote model to the vector.

import torch
import nnsight
from nnsight import TransformersModel

model = TransformersModel("Qwen/Qwen3-8B")
layer = model.model.layers[10]
pos = model.tokenizer.encode(" positive")[0]
neg = model.tokenizer.encode(" negative")[0]

def prompts_of(batch):
    return [f"Review: {s.strip()}\nSentiment:" for s in batch["sentence"]]

with model.session(remote=True):
    from datasets import load_dataset

    rows = load_dataset("nyu-mll/glue", "sst2", split="train[:400]")
    vector = torch.nn.Parameter(torch.zeros(4096))
    optimizer = torch.optim.Adam([vector], lr=0.1)
    losses = nnsight.save([])

    for start in range(0, len(rows), 10):
        batch = rows[start : start + 10]
        flipped = 1 - torch.tensor(batch["label"])

        with model.trace(prompts_of(batch)):
            hidden = layer.output
            layer.output = hidden + vector.to(hidden.device, hidden.dtype)
            logits = model.lm_head.output[:, -1][:, [neg, pos]]
            loss = torch.nn.functional.cross_entropy(logits.float(), flipped.to(logits.device))
            loss.backward()

        optimizer.step()
        optimizer.zero_grad()
        losses.append(round(loss.item(), 3))

    trained = vector.detach().save()

print(losses[::10], losses[-1])
# [3.965, 0.668, 0.43, 0.252] 0.111
print(trained.shape, trained.dtype)
# torch.Size([4096]) torch.float32

The loss falls over 40 steps, and trained is an ordinary tensor on your machine. On NDIF the whole session ran in 10 seconds.

Use what you trained

A tensor that came back from one job can go into the next. Here the vector is scored on 100 reviews it was not trained on, with and without it.

with model.session(remote=True):
    from datasets import load_dataset

    held_out = load_dataset("nyu-mll/glue", "sst2", split="validation[:100]")
    correct = nnsight.save({"plain": 0, "steered": 0})

    for start in range(0, len(held_out), 25):
        batch = held_out[start : start + 25]
        labels = torch.tensor(batch["label"])

        with model.trace(prompts_of(batch)):
            logits = model.lm_head.output[:, -1]
            plain = (logits[:, pos] > logits[:, neg]).long().cpu()

        with model.trace(prompts_of(batch)):
            hidden = layer.output
            layer.output = hidden + trained.to(hidden.device, hidden.dtype)
            logits = model.lm_head.output[:, -1]
            steered = (logits[:, pos] > logits[:, neg]).long().cpu()

        correct["plain"] += int((plain == labels).sum())
        correct["steered"] += int((steered == labels).sum())

print(correct)
# {'plain': 96, 'steered': 28}

Without the vector the model labels 96 of 100 reviews correctly. With it, 28.

What each part does

Part Why
The loop is inside the session The whole training run is one job.
vector and optimizer are created inside the session They exist on the server, so the optimizer updates the tensor the traces use.
vector.to(hidden.device, hidden.dtype) The parameter is on the CPU in float32. The activation is on a GPU in half precision. The gradient flows back through the conversion.
logits.float() before the loss The loss is computed in float32, not half precision.
layer.output = hidden + ... A new tensor is assigned. Editing hidden in place would break the backward pass.
vector.detach().save() Only the trained tensor is downloaded.

The model's own weights stay fixed

NDIF holds the model's weights frozen, and a block cannot train them (access levels). Train tensors of your own and apply them to activations: a vector added to a layer's output, a probe that reads one, or the two matrices of a LoRA applied to a module's input and added to its output.

A probe does not need gradients through the model. Detach the activation and the loop is otherwise the same:

        with model.trace(prompts_of(batch)):
            hidden = layer.output[:, -1].detach().float().cpu()
        loss = torch.nn.functional.cross_entropy(probe(hidden), torch.tensor(batch["label"]))
        loss.backward()