Home / Guide / Tutorial
Tutorial

How to Use AirLLM: A Clear Walkthrough From First Script to Real Projects

Learn how to use AirLLM step by step: loading models, tokenising prompts, generating text, configuring compression and building reusable scripts.

How to Use AirLLM: A Clear Walkthrough From First Script to Real Projects

Plenty of people install AirLLM, run the README example once and then wonder what to do next. This guide on how to use AirLLM goes further. It explains each line of the standard script, shows which settings matter, and ends with patterns you can reuse in real projects such as batch summarisation and private document analysis.

The mental model: a model on a conveyor belt

Before writing code, picture what AirLLM does. A language model is a stack of identical transformer layers. Normally the whole stack sits in GPU memory. AirLLM instead lays the layers out on disk and feeds them through the GPU one after another, like boxes on a conveyor belt. Each layer is loaded, used and released. Your prompt travels through all of them, and the result emerges at the end. Understanding this explains almost every behaviour you will see: low memory use, heavy disk activity and slower generation than a fully loaded model.

Step 1: install and confirm

pip install -U airllm
python -c "import airllm, torch; print(torch.cuda.is_available())"

If you need help with this stage, our AirLLM download guide and AirLLM Windows setup cover it in depth.

Step 2: load a model with AutoModel

from airllm import AutoModel
model = AutoModel.from_pretrained("Qwen/Qwen2.5-7B-Instruct")

AutoModel inspects the model's configuration and chooses the correct internal class, so the same line works for Llama, Qwen, DeepSeek, Mistral and other supported families. The argument can be a Hugging Face repository name or a path to a local folder that already contains the weights.

Useful arguments

  • compression="4bit" or "8bit": shrinks the shards so they load faster from disk.
  • layer_shards_saving_path: where shards are written; point it at your fastest drive.
  • hf_token: your Hugging Face token for gated models such as Llama.
  • prefetching: overlaps loading the next layer with computing the current one; enabled by default.
  • delete_original: removes the original downloaded weights after splitting to save disk space.

Step 3: tokenise the prompt

MAX_LENGTH = 256
prompt = ["Explain the difference between RAM and VRAM in plain English."]
tokens = model.tokenizer(prompt, return_tensors="pt",
                         return_attention_mask=False,
                         truncation=True, max_length=MAX_LENGTH, padding=False)

The tokenizer converts text into the integer IDs the model understands. max_length caps how long the input can be. Shorter limits mean smaller activations, which helps on cards with very little memory.

Step 4: generate

output = model.generate(tokens["input_ids"].cuda(),
                        max_new_tokens=60,
                        use_cache=True,
                        return_dict_in_generate=True)
print(model.tokenizer.decode(output.sequences[0], skip_special_tokens=True))

max_new_tokens is the most important number for your patience: every new token requires a full pass through every layer. Start with 20 to 60 tokens while testing, then increase it once you know how long a pass takes on your machine.

Step 5: use the chat template for instruct models

Instruction-tuned models respond far better when the prompt follows the format they were trained on. Most tokenizers expose that format through apply_chat_template:

messages = [
    {"role": "system", "content": "You are a concise assistant."},
    {"role": "user", "content": "Give me three tips for writing clear emails."},
]
text = model.tokenizer.apply_chat_template(messages, tokenize=False,
                                           add_generation_prompt=True)
tokens = model.tokenizer([text], return_tensors="pt")

This single change often turns rambling output into focused, well-structured answers.

Step 6: wrap it in a reusable function

def ask(question, new_tokens=120):
    msgs = [{"role": "user", "content": question}]
    text = model.tokenizer.apply_chat_template(msgs, tokenize=False,
                                               add_generation_prompt=True)
    ids = model.tokenizer([text], return_tensors="pt")["input_ids"].cuda()
    out = model.generate(ids, max_new_tokens=new_tokens,
                         use_cache=True, return_dict_in_generate=True)
    return model.tokenizer.decode(out.sequences[0][ids.shape[1]:],
                                  skip_special_tokens=True)

print(ask("Summarise the benefits of local AI in two sentences."))

Slicing from ids.shape[1] returns only the newly generated text instead of repeating the prompt.

Practical patterns

Batch jobs that run overnight

Because each token is slow, AirLLM shines in unattended work. Put your prompts in a list, loop through them, and write each answer to a file as soon as it is produced. If the job stops, you keep everything finished so far.

Private document analysis

Everything runs locally once the model is downloaded. You can read a confidential text file, place its contents in the prompt and ask for a summary without the text ever leaving your machine. Set HF_HUB_OFFLINE=1 after the first download to guarantee no network calls are attempted.

Comparing models

Researchers use AirLLM to evaluate large models on modest hardware. Keep the prompt and settings fixed, swap the repository name and record the outputs side by side.

Mistakes to avoid

  • Starting with a 70B or larger model before confirming a 7B model works.
  • Saving shards to a slow hard drive or a network share.
  • Requesting hundreds of new tokens during testing.
  • Forgetting .cuda() on the input IDs when using a GPU.
  • Skipping the chat template with instruct models.

Controlling output style with generation settings

By default, generation is greedy: the model always picks the most likely next token. That produces consistent, focused answers, which is ideal for summaries, extraction and testing. For creative writing, you can enable sampling by passing do_sample=True together with a temperature between roughly 0.6 and 0.9 and a top_p around 0.9. Higher temperatures produce more varied text but also more mistakes. Because each token is expensive with AirLLM, it is worth settling on good settings with a smaller model first, then applying them to the large one.

Organising a small AirLLM project

As your experiments grow, a little structure saves time. A layout that works well looks like this:

airllm-project/
├── config.py        # model name, paths, compression, token limits
├── engine.py        # loads the model once and exposes ask()
├── prompts/         # text files with reusable prompt templates
├── inputs/          # documents to process
├── outputs/         # generated answers, one file per input
└── run_batch.py     # loops over inputs and calls ask()

Keeping configuration in one file lets you switch models or compression modes without editing several scripts. Writing one output file per input means an interrupted job can simply skip inputs that already have results when restarted.

Logging and timing every run

Record the model name, settings, start time, end time and number of tokens generated for every request. A simple CSV file is enough. Over a few days, this log tells you exactly how long different tasks take on your machine, which models offer the best balance of quality and speed, and whether a configuration change actually helped. It also turns guesswork about scheduling into a reliable estimate: if a summary takes twelve minutes, you know a hundred of them will comfortably finish overnight.

Turn the sample into a repeatable task

Once the first AirLLM completion works, choose a simple task with a result you can verify. For example, give the model a short project note and ask it to extract the owner, deadline and unresolved questions. Keep the original note fixed while you test. Write down what a correct response must contain, then inspect the generated answer for missing facts and unsupported guesses. A known task is more diagnostic than an open question with many plausible replies.

Save the model ID, version and generation settings beside the script. Use the chat template from the model's tokenizer when the model expects one. That keeps role markers and separators consistent with training. When switching checkpoints, confirm how each tokenizer handles special tokens and review the exact rendered prompt. A change in answer quality after a model swap may come from different prompt formatting, even if your application sends the same conversation.

Before passing a long input, count its tokens with the same tokenizer the model will use. Budget space for the answer and remember that system instructions and formatting add tokens. If a document is too large, split it into meaningful sections such as headings or paragraphs and process each one with the same extraction prompt. Combine the results by retaining a reference to each source section. That makes the final summary easier to check.

If you call AirLLM repeatedly, load the model once per worker and reuse it for requests that target the same checkpoint. Keep input records and generated outputs separate. When testing a batch, write the result of each item as it finishes so an interruption does not force you to run the entire batch again. Record item identifiers and failure states so only the necessary items are retried. Use small batches until you have observed disk and memory usage under a realistic workload.

Add a simple validation step before a result leaves the script. For a structured output, check whether required fields are present and typed correctly. For a summary, compare dates and names against the source. Keep the original result available when validation fails, since it can reveal whether the model stopped early, misunderstood the format or produced a plausible but incorrect value. Update one instruction at a time and rerun the same test case to see what improved.

Finally, repeat the task from a clean terminal session and check that the script uses the expected environment and model files. Measure a first run and a later run separately. Preparation time matters when moving to another checkpoint, while the repeated timing is more relevant for everyday operation. Keep one short example and its expected result with your script. It gives you a quick check after changing the checkpoint, adjusting the prompt template or updating airllm.

Frequently asked questions

Install the package with pip, import AutoModel, call from_pretrained with a Hugging Face repository name, tokenise a prompt and call generate. The whole workflow fits in about ten lines of Python.

Basic Python is enough. You do not need to understand transformer internals, although knowing what tokens and context length are will help you choose sensible settings.

AirLLM generates text from whatever prompt you supply. To hold a conversation, keep the message history yourself, format it with the model chat template and pass the full history as the next prompt.

On the first run AirLLM downloads the weights and splits them into per-layer shards. That preprocessing happens once per model; later runs skip it and begin generating much sooner.

Conclusion

Learning how to use AirLLM is mostly about understanding its conveyor-belt design and choosing settings that respect it. Load with AutoModel, keep prompts and outputs short while testing, use chat templates for instruct models and give the shards a fast drive. With a small helper function in place, you can build batch pipelines, private assistants and model comparisons on hardware that would otherwise be far too small. Next, see how to add a friendly interface in our AirLLM UI guide.