What this thread does
Do first: call torch.cuda.memory.reset_peak_memory_stats(0) before loading and again before generation, reading torch.cuda.memory.max_memory_allocated(0) after each stage to locate the budget overrun.
Use Transformers 5.22.2, the 6 November patch release, as the baseline for these branches. Record python -m pip show transformers torch accelerate bitsandbytes, GPU capacity, your memory ceiling, model revision, prompt length and requested output length. The examples assume decoder-only inference on one NVIDIA CUDA GPU.
The PyTorch peak counter reports tensor-allocation bytes since the last reset. Save both loading and generation peaks; neither is total device usage.
1. Full-precision loading already consumes the budget
Transformers 5.22.2 -> follow the official loading API. If the checkpoint supports FP16 inference, compare:
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
# model_id is your existing checkpoint identifier or folder.
model = AutoModelForCausalLM.from_pretrained(
model_id, dtype=torch.float16, device_map=0
)
Require the expected floating parameter dtype, a loading peak below the ceiling, and a complete representative generation with acceptable output. device_map=0 places the whole model on GPU 0, keeping placement constant across comparisons. Leave room for generation allocations. The loading API's max_memory guides device placement; it does not impose a total request-memory ceiling.
2. Half-precision weights still leave too little space
Transformers 5.22.2 -> follow bitsandbytes quantization. In a fresh process, reload with quantization_config=BitsAndBytesConfig(load_in_8bit=True) passed to from_pretrained, retaining device_map=0 and the other loading arguments. Compare model.get_memory_footprint() and both peaks, then require the full request to fit. On NVIDIA, LLM.int8 requires Turing or newer according to the guide's hardware table.
3. The 8-bit configuration still exceeds the ceiling
Transformers 5.22.2 -> follow the BitsAndBytesConfig reference. On a BF16-capable GPU, replace the quantization configuration with BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16) and reload in a fresh process. Compare memory, speed and the same quality examples against 8-bit. Weight storage precision and compute precision are separate choices; a smaller model footprint alone does not establish a faster request.
4. Weights fit, but a long request crosses the ceiling
Transformers 5.22.2 -> follow cache offloading. Keep the loaded model fixed and compare model.generate(**inputs, max_new_tokens=128, do_sample=False, cache_implementation="offloaded") with its usual cache. Require the representative long request to finish below the memory ceiling. Reserve CPU RAM and record latency: moving cache data between CPU and GPU can reduce throughput. Cache support depends on the model.
Record the speed tradeoff
Use the same tokenized batch of one prompt in inputs, on GPU 0, and the same model revision. Run each loading configuration in a fresh process. Set generation to include cache_implementation="offloaded" only for that comparison. This measures complete generation, including prefill; record loading time separately. The generation API defines the output controls below; set one returned sequence and tensor output explicitly so checkpoint defaults cannot change the counting code.
import time
from statistics import median
model.eval()
generation = dict(max_new_tokens=128, do_sample=False, num_beams=1,
num_return_sequences=1, return_dict_in_generate=False)
# For the offloaded-cache comparison:
# generation["cache_implementation"] = "offloaded"
with torch.inference_mode():
model.generate(**inputs, **generation) # warm-up
rows = []
for _ in range(3):
torch.cuda.synchronize(0)
torch.cuda.memory.reset_peak_memory_stats(0)
start = time.perf_counter()
output = model.generate(**inputs, **generation)
torch.cuda.synchronize(0)
elapsed = time.perf_counter() - start
count = output.shape[1] - inputs["input_ids"].shape[1]
rows.append((elapsed, count / elapsed,
torch.cuda.memory.max_memory_allocated(0) / 2**30, count))
del output
print({"median_seconds": median(r[0] for r in rows),
"median_output_tokens_per_second": median(r[1] for r in rows),
"peak_allocated_GiB": max(r[2] for r in rows),
"generated_tokens_per_run": [r[3] for r in rows]})
CUDA execution is asynchronous, so retain the synchronization around timing. Record actual generated length because early stopping can change it. Report configuration, loading peak/time, generation peak/time, tokens per second and quality observations. Calculate speed change as 100 * (candidate_tokens_per_second / reference_tokens_per_second - 1). If the original model cannot load, report that failure and compare with the fastest configuration that fits.
Evidence and limits
cnut1648's 26 June 2023 report describes slow 4-bit generation on Transformers 4.31.0.dev0. It demonstrates why a memory reduction needs a separate timing comparison; it supplies no speed estimate for 5.22.2.
Allocated peaks exclude memory outside PyTorch. Also observe total device usage; CUDA memory management explains the distinction from reserved memory. Quantization may alter output quality. A configuration fits only for the prompt, output length and batch size measured; this recipe covers inference rather than training.
Not for: vLLM startup or KV-cache allocation errors; see vllm-cuda-out-of-memory-kv-cache-engine-core-startup-errors
Started from a post by @Hugging Face, packaged by the editor. Original post