Complete Qwen Models Tutorial: A Practical Guide to Using Alibaba's Open-Source AI Models

# Tutorial Lengkap Qwen Models: Panduan Praktis Menggunakan Model AI Open-Source dari Alibaba Qwen (通义千问) adalah keluarga model bahasa besar (LLM) open-source yang dikembangkan oleh Alibaba Cloud. Se...

By Ruby Abdullah · · tutorial
QwenLLMOllamavLLMFine-tuning

Complete Qwen Models Tutorial: A Practical Guide to Using Alibaba's Open-Source AI Models

Qwen (通义千问) is a family of large language models (LLMs) developed by Alibaba Cloud. Since its initial release, Qwen has evolved into one of the most competitive open-source model families in the world, rivaling Llama, Mistral, and even proprietary models like GPT-4. In this tutorial, we will learn how to use various Qwen variants for your AI needs, from local inference to fine-tuning.

Why Qwen?

Qwen offers several compelling advantages that make it worth considering:

  • High performance: Qwen consistently ranks at the top of various LLM benchmarks, including MMLU, HumanEval, and GSM8K
  • Open license: Most Qwen variants use the Apache 2.0 license, allowing unrestricted commercial use
  • Multilingual support: Excellent performance across Asian languages including Indonesian, Chinese, Japanese, and Korean
  • Complete ecosystem: Available in various sizes (0.5B to 72B+) and specializations (chat, code, math, vision)
  • Official quantization: The Qwen team provides optimized GGUF, GPTQ, and AWQ versions

Qwen Model Variants

Before we begin, let's understand the Qwen ecosystem:

| Model | Description | Sizes |

|-------|-------------|-------|

| Qwen2.5 | Latest general-purpose language model | 0.5B, 1.5B, 3B, 7B, 14B, 32B, 72B |

| Qwen2.5-Coder | Specialized for coding and programming | 0.5B, 1.5B, 3B, 7B, 14B, 32B |

| Qwen2.5-Math | Specialized for mathematics and reasoning | 1.5B, 7B, 72B |

| Qwen-VL | Multimodal (vision + language) | 2B, 7B, 72B |

| Qwen-Audio | Audio understanding and speech | 7B |

| QwQ | Reasoning model (chain-of-thought) | 32B |

Installation and Setup

Prerequisites

Ensure you have Python 3.9+ and pip installed. We'll install several required libraries:

pip install transformers torch accelerate

pip install autoawq auto-gptq optimum

pip install vllm

pip install ollama

For GPU usage, make sure the CUDA toolkit is installed:

nvidia-smi

Using Qwen via Hugging Face Transformers

The most straightforward way to use Qwen is through Hugging Face's transformers library:

from transformers import AutoModelForCausalLM, AutoTokenizer

modelname = "Qwen/Qwen2.5-7B-Instruct"

tokenizer = AutoTokenizer.frompretrained(modelname)

model = AutoModelForCausalLM.frompretrained(

modelname,

torchdtype="auto",

devicemap="auto"

)

messages = [

{"role": "system", "content": "You are a helpful AI assistant."},

{"role": "user", "content": "Explain what machine learning is in 3 sentences."}

]

text = tokenizer.applychattemplate(

messages,

tokenize=False,

addgenerationprompt=True

)

modelinputs = tokenizer([text], returntensors="pt").to(model.device)

generatedids = model.generate(

modelinputs,

maxnewtokens=512,

temperature=0.7,

topp=0.9

)

generatedids = [

outputids[len(inputids):]

for inputids, outputids in zip(modelinputs.inputids, generatedids)

]

response = tokenizer.batchdecode(generatedids, skipspecialtokens=True)[0]

print(response)

Using Qwen via Ollama (Easiest Method)

Ollama is the easiest way to run Qwen locally:

# Install Ollama

curl -fsSL https://ollama.com/install.sh | sh

Download and run Qwen

ollama pull qwen2.5:7b

ollama run qwen2.5:7b

You can also use Ollama through Python:

import ollama

response = ollama.chat(

model="qwen2.5:7b",

messages=[

{"role": "system", "content": "You are a helpful AI assistant."},

{"role": "user", "content": "Write a Python function to calculate fibonacci numbers."}

]

)

print(response["message"]["content"])

Ollama also provides an OpenAI-compatible API:

from openai import OpenAI

client = OpenAI(

baseurl="http://localhost:11434/v1",

apikey="ollama"

)

response = client.chat.completions.create(

model="qwen2.5:7b",

messages=[

{"role": "user", "content": "What is the capital of Indonesia?"}

],

temperature=0.7

)

print(response.choices[0].message.content)

Advanced Usage

Running Qwen with vLLM for Production

vLLM is a highly efficient inference engine, ideal for production deployments:

pip install vllm

Run as an API server:

vllm serve Qwen/Qwen2.5-7B-Instruct \

--dtype auto \

--max-model-len 8192 \

--gpu-memory-utilization 0.9 \

--port 8000

Then access via API:

from openai import OpenAI

client = OpenAI(

baseurl="http://localhost:8000/v1",

apikey="token-abc123"

)

response = client.chat.completions.create(

model="Qwen/Qwen2.5-7B-Instruct",

messages=[

{"role": "system", "content": "You are an expert data scientist."},

{"role": "user", "content": "How do you address overfitting in deep learning models?"}

],

temperature=0.7,

maxtokens=1024

)

print(response.choices[0].message.content)

Using Quantized Models for Limited Hardware

If your GPU is limited, use pre-quantized models:

from transformers import AutoModelForCausalLM, AutoTokenizer

modelname = "Qwen/Qwen2.5-7B-Instruct-GPTQ-Int4"

tokenizer = AutoTokenizer.frompretrained(modelname)

model = AutoModelForCausalLM.frompretrained(

modelname,

devicemap="auto"

)

messages = [

{"role": "user", "content": "Write Python code for simple web scraping."}

]

text = tokenizer.applychattemplate(messages, tokenize=False, addgenerationprompt=True)

inputs = tokenizer([text], returntensors="pt").to(model.device)

output = model.generate(inputs, maxnewtokens=512)

result = tokenizer.decode(output[0][len(inputs.inputids[0]):], skipspecialtokens=True)

print(result)

Or use the faster AWQ version:

modelname = "Qwen/Qwen2.5-7B-Instruct-AWQ"

model = AutoModelForCausalLM.frompretrained(

modelname,

devicemap="auto"

)

Quantization method comparison:

| Method | Speed | Quality | VRAM |

|--------|-------|---------|------|

| FP16 (original) | Baseline | Best | ~14GB (7B) |

| GPTQ-Int4 | 1.5-2x | Very good | ~4GB (7B) |

| AWQ-Int4 | 2-3x | Very good | ~4GB (7B) |

| GGUF Q4KM | 1.5x | Good | ~4.5GB (7B) |

Qwen2.5-Coder for Programming

Qwen2.5-Coder is optimized specifically for coding tasks:

from transformers import AutoModelForCausalLM, AutoTokenizer

modelname = "Qwen/Qwen2.5-Coder-7B-Instruct"

tokenizer = AutoTokenizer.frompretrained(modelname)

model = AutoModelForCausalLM.frompretrained(

modelname,

torchdtype="auto",

devicemap="auto"

)

messages = [

{"role": "system", "content": "You are an expert Python developer. Write clean, well-documented code."},

{"role": "user", "content": """Create a Python class for PostgreSQL database connection

with connection pooling using psycopg2. Include methods for

executing queries, fetching results, and transaction management."""}

]

text = tokenizer.applychattemplate(messages, tokenize=False, addgenerationprompt=True)

inputs = tokenizer([text], returntensors="pt").to(model.device)

output = model.generate(

inputs,

maxnewtokens=2048,

temperature=0.3,

topp=0.95

)

result = tokenizer.decode(output[0][len(inputs.inputids[0]):], skipspecialtokens=True)

print(result)

Qwen-VL for Image Analysis

Qwen-VL (Vision-Language) enables you to analyze images:

from transformers import Qwen2VLForConditionalGeneration, AutoProcessor

from PIL import Image

import requests

modelname = "Qwen/Qwen2-VL-7B-Instruct"

model = Qwen2VLForConditionalGeneration.frompretrained(

modelname,

torchdtype="auto",

devicemap="auto"

)

processor = AutoProcessor.frompretrained(modelname)

imageurl = "https://example.com/chart.png"

image = Image.open(requests.get(imageurl, stream=True).raw)

messages = [

{

"role": "user",

"content": [

{"type": "image", "image": image},

{"type": "text", "text": "Describe what you see in this image. Provide a detailed analysis."}

]

}

]

text = processor.applychattemplate(messages, tokenize=False, addgenerationprompt=True)

inputs = processor(text=[text], images=[image], returntensors="pt").to(model.device)

output = model.generate(inputs, maxnewtokens=512)

result = processor.decode(output[0], skipspecialtokens=True)

print(result)

QwQ for Complex Reasoning

QwQ is Qwen's reasoning model that uses chain-of-thought:

from transformers import AutoModelForCausalLM, AutoTokenizer

modelname = "Qwen/QwQ-32B"

tokenizer = AutoTokenizer.frompretrained(modelname)

model = AutoModelForCausalLM.frompretrained(

modelname,

torchdtype="auto",

devicemap="auto"

)

messages = [

{"role": "user", "content": """A company has 3 servers.

Server A processes 40% of traffic, Server B 35%, and Server C 25%.

The error probability for each is 2%, 3%, and 5% respectively.

If an error occurs, what is the probability it came from Server C?"""}

]

text = tokenizer.applychattemplate(messages, tokenize=False, addgenerationprompt=True)

inputs = tokenizer([text], returntensors="pt").to(model.device)

output = model.generate(

*inputs,

maxnewtokens=4096,

temperature=0.6

)

result = tokenizer.decode(output[0][len(inputs.inputids[0]):], skipspecialtokens=True)

print(result)

Fine-tuning Qwen

Fine-tuning with LoRA using PEFT

import torch

from datasets import loaddataset

from transformers import (

AutoModelForCausalLM,

AutoTokenizer,

TrainingArguments,

Trainer,

BitsAndBytesConfig

)

from peft import LoraConfig, getpeftmodel, preparemodelforkbittraining

modelname = "Qwen/Qwen2.5-7B-Instruct"

bnbconfig = BitsAndBytesConfig(

loadin4bit=True,

bnb4bitquanttype="nf4",

bnb4bitcomputedtype=torch.bfloat16,

bnb4bitusedoublequant=True

)

model = AutoModelForCausalLM.frompretrained(

modelname,

quantizationconfig=bnbconfig,

devicemap="auto"

)

tokenizer = AutoTokenizer.frompretrained(modelname)

tokenizer.padtoken = tokenizer.eostoken

model = preparemodelforkbittraining(model)

loraconfig = LoraConfig(

r=16,

loraalpha=32,

targetmodules=["qproj", "kproj", "vproj", "oproj", "gateproj", "upproj", "downproj"],

loradropout=0.05,

bias="none",

tasktype="CAUSALLM"

)

model = getpeftmodel(model, loraconfig)

model.printtrainableparameters()

dataset = loaddataset("json", datafiles="trainingdata.jsonl")

def formatinstruction(sample):

messages = [

{"role": "system", "content": sample.get("system", "You are a helpful assistant.")},

{"role": "user", "content": sample["instruction"]},

{"role": "assistant", "content": sample["output"]}

]

text = tokenizer.applychattemplate(messages, tokenize=False)

return {"text": text}

dataset = dataset.map(formatinstruction)

def tokenizefunction(examples):

return tokenizer(

examples["text"],

truncation=True,

maxlength=2048,

padding="maxlength"

)

tokenizeddataset = dataset.map(tokenizefunction, batched=True)

trainingargs = TrainingArguments(

outputdir="./qwen-finetuned",

numtrainepochs=3,

perdevicetrainbatchsize=4,

gradientaccumulationsteps=4,

learningrate=2e-4,

weightdecay=0.01,

warmupsteps=100,

loggingsteps=10,

savestrategy="epoch",

bf16=True,

optim="pagedadamw8bit",

lrschedulertype="cosine"

)

trainer = Trainer(

model=model,

args=trainingargs,

traindataset=tokenizeddataset["train"],

tokenizer=tokenizer

)

trainer.train()

model.savepretrained("./qwen-finetuned-lora")

tokenizer.savepretrained("./qwen-finetuned-lora")

Training Data Format

Prepare your training data in JSONL format:

{"system": "You are a customer service expert.", "instruction": "How do I return an item?", "output": "To return an item, please follow these steps: 1. Log in to your account, 2. Select the order you want to return, 3. Click the 'Request Return' button, 4. Fill in the return reason, 5. Wait for confirmation from our team within 24 hours."}

{"system": "You are a customer service expert.", "instruction": "How long does shipping take to Surabaya?", "output": "Estimated delivery to Surabaya is 2-3 business days for regular service and 1 day for express service. Delivery time is calculated from the order confirmation date."}

Deploying Qwen to Production

Docker Deployment with vLLM

Create a Dockerfile:

FROM vllm/vllm-openai:latest

ENV MODELNAME=Qwen/Qwen2.5-7B-Instruct

ENV MAXMODELLEN=8192

ENV GPUMEMORYUTILIZATION=0.9

CMD ["python", "-m", "vllm.entrypoints.openai.apiserver", \

"--model", "${MODELNAME}", \

"--max-model-len", "${MAXMODELLEN}", \

"--gpu-memory-utilization", "${GPUMEMORYUTILIZATION}", \

"--host", "0.0.0.0", \

"--port", "8000"]

Docker compose:

version: "3.8"

services:

qwen-api:

build: .

ports:

  • "8000:8000"
deploy:

resources:

reservations:

devices:

  • driver: nvidia
count: 1

capabilities: [gpu]

volumes:

  • model-cache:/root/.cache/huggingface
restart: unless-stopped

volumes:

model-cache:

Monitoring and Logging

Add simple monitoring for your deployment:

import time

import logging

from functools import wraps

logging.basicConfig(level=logging.INFO)

logger = logging.getLogger("qwen-api")

def monitorinference(func):

@wraps(func)

def wrapper(args, *kwargs):

starttime = time.time()

result = func(args, kwargs)

duration = time.time() - starttime

tokens = len(result.split())

logger.info(f"Inference completed in {duration:.2f}s, ~{tokens} tokens, {tokens/duration:.1f} tok/s")

return result

return wrapper

Best Practices

1. Choosing the Right Model

  • General chatbot: Qwen2.5-7B-Instruct or 14B-Instruct
  • Coding assistant: Qwen2.5-Coder-7B-Instruct
  • Document/image analysis: Qwen2-VL-7B-Instruct
  • Complex reasoning: QwQ-32B
  • Edge/mobile deployment: Qwen2.5-1.5B or 3B
  • Large-scale production: Qwen2.5-72B with vLLM

2. Performance Optimization

# Use Flash Attention 2 for faster inference

model = AutoModelForCausalLM.frompretrained(

modelname,

torchdtype=torch.bfloat16,

attnimplementation="flashattention2",

devicemap="auto"

)

3. Effective System Prompts

systemprompts = {

"general": "You are an intelligent and helpful AI assistant. Answer clearly and concisely.",

"coding": "You are an expert programmer. Write clean, efficient, well-tested code. Always explain your approach briefly before writing code.",

"analysis": "You are a senior data analyst. Provide structured analysis with actionable insights.",

"creative": "You are a creative writing assistant. Help users craft engaging, well-structured content."

}

4. Handling Context Window

def smarttruncate(messages, tokenizer, maxcontext=6144, reserveoutput=2048):

maxinput = maxcontext - reserveoutput

systemmsg = messages[0] if messages[0]["role"] == "system" else None

conversation = messages[1:] if systemmsg else messages

result = [systemmsg] if systemmsg else []

for msg in reversed(conversation):

testmessages = result + [msg]

text = tokenizer.applychattemplate(testmessages, tokenize=False)

tokencount = len(tokenizer.encode(text))

if tokencount <= maxinput:

result.append(msg)

else:

break

return result

5. Model Evaluation

import json

def evaluateqwen(model, tokenizer, testcases):

results = []

for case in testcases:

messages = [

{"role": "system", "content": case.get("system", "")},

{"role": "user", "content": case["input"]}

]

text = tokenizer.applychattemplate(messages, tokenize=False, addgenerationprompt=True)

inputs = tokenizer([text], returntensors="pt").to(model.device)

output = model.generate(inputs, maxnewtokens=512, temperature=0.1)

response = tokenizer.decode(output[0][len(inputs.inputids[0]):], skipspecialtokens=True)

results.append({

"input": case["input"],

"expected": case.get("expected", ""),

"actual": response,

"match": case.get("expected", "").lower() in response.lower()

})

accuracy = sum(1 for r in results if r["match"]) / len(results)

print(f"Accuracy: {accuracy:.2%}")

return results

Comparing Qwen with Other Models

| Aspect | Qwen2.5-7B | Llama 3.1-8B | Mistral 7B |

|--------|------------|--------------|------------|

| Asian Languages | Excellent | Good | Fair |

| Coding | Excellent | Good | Good |

| Math/Reasoning | Excellent | Good | Fair |

| Context Window | 128K | 128K | 32K |

| License | Apache 2.0 | Llama License | Apache 2.0 |

| Ecosystem | Complete | Very complete | Complete |

Conclusion

Qwen is one of the best open-source AI model families available today. With a comprehensive ecosystem covering language, coding, vision, and reasoning models, Qwen is an excellent choice for a wide range of AI use cases.

Key takeaways to remember:

  • Start with Ollama for quick experimentation, then migrate to vLLM for production
  • Choose the right model size based on your needs and available hardware
  • Use quantization (GPTQ/AWQ) when VRAM is limited
  • Fine-tune with LoRA to customize the model for your specific domain
  • Leverage specialist models (Coder, Math, VL) for appropriate tasks
  • By following this tutorial, you now have a solid foundation for building AI applications using Qwen models. Happy experimenting!

    Related Articles

    Complete Google Gemma Tutorial: Open-Source Models from Google DeepMind

    Tutorial Lengkap Google Gemma: Model Open-Source dari Google DeepMind Google Gemma adalah keluarga model bahasa open-sou...

    Complete Guide to Hugging Face AutoTrain: Fine-Tune AI Models Without the Hassle

    Tutorial Lengkap Hugging Face AutoTrain: Fine-Tuning Model AI Tanpa Ribet Hugging Face AutoTrain adalah platform dan lib...

    LitGPT Tutorial: A Framework for Training and Fine-Tuning Large Language Models

    Tutorial LitGPT: Framework untuk Melatih dan Fine-Tuning Large Language Models LitGPT adalah framework open-source dari ...

    Distilabel Tutorial: Synthetic Data Generation Framework for LLM Fine-Tuning

    Tutorial Distilabel: Framework Generasi Data Sintetis untuk Fine-Tuning LLM Dalam dunia pengembangan Large Language Mode...