Skip to content

Many jobs at once

Some work is better as separate jobs than as one session: runs on different models, runs where one failure should not stop the rest, or runs longer in total than one job may be. Send them without waiting for each, then collect the results.

Jobs for one model run one at a time on each loaded copy. Sending ten together does not make them finish ten times sooner. It saves you from waiting for one before sending the next.

Send, then collect

blocking=False returns as soon as a job is sent. Keep each job, and ask for results in a loop with a pause.

import time
from nnsight import TransformersModel

model = TransformersModel("Qwen/Qwen3-8B")
prompts = ["The capital of France is", "The capital of Japan is", "The capital of Italy is"]

jobs = {}
for prompt in prompts:
    with model.trace(prompt, remote=True, blocking=False) as tracer:
        token = model.lm_head.output[0, -1].argmax(-1).save()
    jobs[prompt] = tracer.backend

answers = {}
while len(answers) < len(jobs):
    for prompt, job in jobs.items():
        if prompt not in answers and (result := job()) is not None:
            answers[prompt] = model.tokenizer.decode(result["token"])
    time.sleep(2)

print(answers)
# {'The capital of France is': ' Paris', 'The capital of Japan is': ' Tokyo', 'The capital of Italy is': ' Rome'}

A job that failed raises RemoteError from job(). Catch it per job to keep the others:

from nnsight.intervention.backends.remote import RemoteError

try:
    result = job()
except RemoteError as error:
    print("failed:", str(error).splitlines()[-1])

Collect from another process

Write the job ids down, and build each job again from its id later.

import json
from nnsight.intervention.backends.remote import RemoteBackend

json.dump({prompt: job.job_id for prompt, job in jobs.items()}, open("jobs.json", "w"))

# later, in another process
ids = json.load(open("jobs.json"))
jobs = {prompt: RemoteBackend(model.to_model_key(), blocking=False, job_id=i) for prompt, i in ids.items()}

With asyncio

In async code, each job is a coroutine and asyncio.gather waits for all of them.

import asyncio
from nnsight.intervention.backends.remote import AsyncRemoteBackend

async def ask(prompt):
    backend = AsyncRemoteBackend(model.to_model_key())
    with model.trace(prompt, backend=backend):
        token = model.lm_head.output[0, -1].argmax(-1).save()
    result = await backend
    return model.tokenizer.decode(result["token"])

async def main():
    return await asyncio.gather(*(ask(p) for p in prompts))

print(asyncio.run(main()))
# [' Paris', ' Tokyo', ' Rome']

When one session is better

Three prompts on one model, as above, are faster as one session: one wait in the queue instead of three. Use separate jobs when the pieces are independent and large, and a session when they are steps of one experiment.