Remote Inference with @lium.machine
Run a small model on a GPU pod with one decorated function. The pod is removed after the call. For options and costs see Serverless functions with @lium.machine.
Authenticate before running the script:
lium init
In CI, set LIUM_API_KEY instead.
#!/usr/bin/env python3
"""Run a small instruct model on a remote Lium GPU."""
import lium
@lium.machine(machine="RTX4090", requirements=["transformers", "accelerate"]) # cheapest node with one RTX 4090; torch comes with the image
def infer(prompt: str) -> str:
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
dtype="auto",
device_map="cuda",
)
messages = [{"role": "user", "content": prompt}]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
outputs = model.generate(
**inputs,
max_new_tokens=64,
do_sample=False,
pad_token_id=tokenizer.eos_token_id,
)
response_tokens = outputs[0][inputs["input_ids"].shape[-1]:]
return tokenizer.decode(response_tokens, skip_special_tokens=True).strip()
print(infer("In one sentence, who discovered penicillin?"))
The answer should name Alexander Fleming.