
An older laptop can show you how a large language model (LLM) generates text one token at a time. Start with the smallest original GPT-2 checkpoint, a short English sentence and 12 new tokens. The CPU does the work. The first run needs internet access to download the tokenizer and model.
Choose the small download
The quantized ONNX decoder in this example is about 127 MB. The full precision decoder in the same repository is about 499 MB. Quantization stores weights more compactly. The download size measures the file on disk; Python, the inference engine and its working arrays need additional RAM. On a 4 GB machine, close the browser and run the script from a terminal. Available memory and CPU support determine whether it runs comfortably.
Set up Python
Use 64 bit Python 3.11 in a new folder. On Windows, run these commands in PowerShell. Calling the virtual environment’s Python directly also avoids activation issues.
py -3.11 -m venv .venv
.\.venv\Scripts\python -m pip install numpy onnxruntime tokenizers huggingface_hubOn Linux or macOS, create the environment with python3.11 -m venv .venv and use .venv/bin/python in place of the Windows interpreter path.
Generate your first continuation
Save this as run_gpt2.py. Each pass scores the possible next tokens. The script picks the highest scoring one, appends it, then repeats. Keeping the sequence short makes this simple approach practical on a CPU.
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from tokenizers import Tokenizer
repo = 'Xenova/gpt2'
def fetch(filename):
return hf_hub_download(repo_id=repo, filename=filename)
tokenizer = Tokenizer.from_file(fetch('tokenizer.json'))
options = ort.SessionOptions()
options.intra_op_num_threads = 2
options.inter_op_num_threads = 1
model = ort.InferenceSession(fetch('onnx/decoder_model_quantized.onnx'),
sess_options=options,
providers=['CPUExecutionProvider'])
ids = tokenizer.encode('The old laptop on my desk').ids
eos = tokenizer.token_to_id('<|endoftext|>')
for _ in range(12):
tokens = np.array([ids], dtype=np.int64)
inputs = {'input_ids': tokens,
'attention_mask': np.ones_like(tokens),
'position_ids': np.arange(len(ids), dtype=np.int64)[None, :]}
feed = {item.name: inputs[item.name] for item in model.get_inputs()}
logits = model.run(['logits'], feed)[0]
next_id = int(logits[0, -1].argmax())
if next_id == eos:
break
ids.append(next_id)
print(tokenizer.decode(ids))Run .\.venv\Scripts\python run_gpt2.py on Windows or .venv/bin/python run_gpt2.py on Linux and macOS. Look for a line beginning “The old laptop on my desk” followed by generated text. Try changing the opening to “The train from Kolkata” and compare the continuation. GPT-2 learned to continue text, so a sentence fragment works better here than a chat instruction.
If your laptop struggles
If generation is slow, change range(12) to range(4). If loading fails for lack of memory, shortening the output cannot fix that stage: close other applications and confirm the filename ends in _quantized.onnx. If pip reports no matching distribution, check your Python version and whether your operating system and processor have a compatible ONNX Runtime wheel. After a successful download, pass local_files_only=True to hf_hub_download to reuse the cached files offline.
Original GPT-2 model card · ONNX model files and sizes · Applied AI tutorials
No comments:
Post a Comment