This guide shows you how to run Qwen3 8B or 27B models with a context window longer than the default (often 8K or 32K tokens) on a GPU with limited VRAM (e.g., 8–16 GB). You’ll learn to use quantization, KV-cache optimizations, and offloading to fit a longer context without running out of memory. Before starting, ensure you have Python, PyTorch, and the Hugging Face Transformers library installed.
What You’ll Need
- A GPU with at least 8 GB VRAM (NVIDIA recommended for CUDA support).
- Python 3.9+ and pip installed.
- PyTorch with CUDA support (install from pytorch.org).
- Hugging Face Transformers library (v4.40+).
- Optional: bitsandbytes for 4-bit/8-bit quantization.
- Optional: FlashAttention-2 for efficient attention.
Step-by-Step
- Check your VRAM and set a target context length. For 8B models, 8 GB VRAM can handle ~8K tokens with 4-bit quantization; for 27B, you’ll need at least 16 GB for ~4K tokens. Use
nvidia-smito see available memory. - Install required packages. Run:
pip install transformers accelerate bitsandbytes flash-attn --no-build-isolation
(FlashAttention-2 is optional but speeds up long-context inference.)
- Load the model with quantization. Use 4-bit quantization (NF4) to reduce memory. Example:
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig import torch quant_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True) model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B", quantization_config=quant_config, device_map="auto", torch_dtype=torch.bfloat16) tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B") - Enable long-context support. Qwen3 models support a maximum of 32K tokens (8B) or 64K (27B) via YaRN. Set the rope scaling:
from transformers import AutoConfig config = AutoConfig.from_pretrained("Qwen/Qwen3-8B") config.rope_scaling = {"type": "yarn", "factor": 4.0} # adjust factor based on target length model = AutoModelForCausalLM.from_pretrained(..., config=config)Note: You must load the model with the new config; you can’t change it after loading.
- Use a sliding window or sparse attention. If your task doesn’t need full bidirectional context, set
use_sliding_window=Truein the model config to reduce memory usage. For full long context, keep it False. - Offload to CPU if needed. For 27B on 16 GB VRAM, offload some layers to CPU using
device_map="auto"withmax_memory:max_memory = {0: "10GiB", "cpu": "20GiB"} model = AutoModelForCausalLM.from_pretrained(..., device_map="auto", max_memory=max_memory) - Set the tokenizer’s model_max_length. Ensure the tokenizer knows the max length:
tokenizer.model_max_length = 32768 # or your target
- Generate with a long prompt. When generating, set
max_new_tokensanduse_cache=True. For very long contexts, useflash_attn_2if available:output = model.generate(input_ids, max_new_tokens=512, use_cache=True, attention_mask=attention_mask)
- Monitor VRAM. Use
nvidia-smito see memory usage. If you get OOM, reduce context length or increase offloading.
Common Mistakes
- Forgetting to set rope_scaling before loading. You must pass the config at load time; changing it later won’t work.
- Using fp16 instead of bf16. On newer GPUs, bf16 is more stable and uses the same memory.
- Not using quantization when VRAM is tight. 4-bit can reduce memory by ~4x.
- Setting max_new_tokens too high. That consumes extra memory; keep it modest.
- Ignoring the attention mask. For packed sequences, you need to pass the mask explicitly.
Tips
- Use
torch.compile()to speed up inference (optional). - For 27B, consider using the AWQ or GPTQ quantized versions from the hub if available.
- Use
batch_size=1for the lowest memory consumption. - If you need longer than the model’s max, you can split the prompt into chunks and use a sliding window, but that loses early context.
- Set
low_cpu_mem_usage=Truein from_pretrained to reduce CPU RAM spikes.
Troubleshooting
- Out-of-memory (OOM) error: Reduce context length, lower quantization bits (e.g., 8-bit to 4-bit), increase CPU offloading, or use a smaller model.
- Slow generation: Enable FlashAttention-2 if your GPU supports it; also try
torch.compile. - Incorrect output for long contexts: Ensure you applied YaRN scaling correctly; test with a short prompt first.
- Tokenizer errors: Set
tokenizer.model_max_lengthto your target and ensure the tokenizer’s pad token is set. - CUDA out of memory during loading: Use
device_map="auto"withmax_memoryto offload to CPU.
Frequently Asked Questions
Q: Can I run Qwen3-27B on 8 GB VRAM?
A: Not with a long context. With 4-bit quantization, you might get 2K context, but it will be very slow. Better to use 8B.
Q: What is YaRN?
A: YaRN is a method to extend the context window of rotary position embeddings. Qwen3 uses it to support up to 32K/64K tokens.
Q: How much VRAM does a 32K context use?
A: For 8B in 4-bit, roughly 6-8 GB for the model plus ~2 GB per 8K tokens of KV cache. So 32K might need ~10-12 GB total.
Q: Can I use CPU offloading for the KV cache?
A: Yes, but it will be very slow. Better to use quantization and reduce context length.
Q: Does FlashAttention-2 help with long context?
A: Yes, it reduces memory usage and speeds up attention, making longer contexts feasible.
Q: What is the max context for Qwen3-8B?
A: Officially 32K tokens with YaRN scaling. The base model supports 8K natively.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Philips DST7060/20 7000 Series Iron: Specs & Fit
- Coal Fueled Jet Aircraft: Could It Work?675 L
- Remote Desktop on Raspberry Pi: How to Enable It
- Word Select Last Line in Paragraph?
- Google Assistant IFTTT Recipes: 7 Useful Automations
- OLED TVs in Dark Rooms: Why They Look Better and When They Don’t