Qwen2 Technical Report
Paper โข 2407.10671 โข Published โข 173
How to use LuvU4ever/qwen2.5-3b-qlora-merged-v4 with Transformers:
# Use a pipeline as a high-level helper
from transformers import pipeline
pipe = pipeline("text-generation", model="LuvU4ever/qwen2.5-3b-qlora-merged-v4")
messages = [
{"role": "user", "content": "Who are you?"},
]
pipe(messages) # pip install -U transformers accelerate
# Load model directly
from transformers import AutoTokenizer, AutoModelForCausalLM
tokenizer = AutoTokenizer.from_pretrained("LuvU4ever/qwen2.5-3b-qlora-merged-v4")
model = AutoModelForCausalLM.from_pretrained("LuvU4ever/qwen2.5-3b-qlora-merged-v4", device_map="auto")
messages = [
{"role": "user", "content": "Who are you?"},
]
inputs = tokenizer.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
).to(model.device)
outputs = model.generate(**inputs, max_new_tokens=256)
print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:]))How to use LuvU4ever/qwen2.5-3b-qlora-merged-v4 with vLLM:
# Install vLLM from pip:
pip install vllm
# Start the vLLM server:
vllm serve "LuvU4ever/qwen2.5-3b-qlora-merged-v4"
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:8000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "LuvU4ever/qwen2.5-3b-qlora-merged-v4",
"messages": [
{
"role": "user",
"content": "What is the capital of France?"
}
]
}'docker model run hf.co/LuvU4ever/qwen2.5-3b-qlora-merged-v4
How to use LuvU4ever/qwen2.5-3b-qlora-merged-v4 with SGLang:
# Install SGLang from pip:
pip install sglang
# Start the SGLang server:
python3 -m sglang.launch_server \
--model-path "LuvU4ever/qwen2.5-3b-qlora-merged-v4" \
--host 0.0.0.0 \
--port 30000
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:30000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "LuvU4ever/qwen2.5-3b-qlora-merged-v4",
"messages": [
{
"role": "user",
"content": "What is the capital of France?"
}
]
}'docker run --gpus all \
--shm-size 32g \
-p 30000:30000 \
-v ~/.cache/huggingface:/root/.cache/huggingface \
--env "HF_TOKEN=<secret>" \
--ipc=host \
lmsysorg/sglang:latest \
python3 -m sglang.launch_server \
--model-path "LuvU4ever/qwen2.5-3b-qlora-merged-v4" \
--host 0.0.0.0 \
--port 30000
# Call the server using curl (OpenAI-compatible API):
curl -X POST "http://localhost:30000/v1/chat/completions" \
-H "Content-Type: application/json" \
--data '{
"model": "LuvU4ever/qwen2.5-3b-qlora-merged-v4",
"messages": [
{
"role": "user",
"content": "What is the capital of France?"
}
]
}'How to use LuvU4ever/qwen2.5-3b-qlora-merged-v4 with Docker Model Runner:
docker model run hf.co/LuvU4ever/qwen2.5-3b-qlora-merged-v4
๐ฏ Official Qwen-2.5 3B Instruct tแปซ Alibaba Cloud!
ฤรขy lร bแบฃn copy cแปงa model gแปc Qwen/Qwen2.5-3B-Instruct tแปซ Qwen team. Model nร y ฤฦฐแปฃc phรกt triแปn bแปi Alibaba Cloud vร ฤแบกi diแปn cho state-of-the-art trong LLM 3B parameters.
Deploy trรชn Hugging Face Inference Endpoints:
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
# Load model vร tokenizer
model = AutoModelForCausalLM.from_pretrained(
"LuvU4ever/qwen2.5-3b-qlora-merged-v4",
torch_dtype=torch.bfloat16,
device_map="auto",
trust_remote_code=True
)
tokenizer = AutoTokenizer.from_pretrained("LuvU4ever/qwen2.5-3b-qlora-merged-v4")
# Hร m chat
def chat_with_qwen(message, history=None):
if history is None:
history = []
# Thรชm tin nhแบฏn mแปi vร o history
history.append({"role": "user", "content": message})
# Tแบกo chat template
text = tokenizer.apply_chat_template(
history,
tokenize=False,
add_generation_prompt=True
)
# Tokenize
inputs = tokenizer([text], return_tensors="pt").to(model.device)
# Generate
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=512,
temperature=0.7,
do_sample=True,
top_p=0.9,
repetition_penalty=1.1,
pad_token_id=tokenizer.eos_token_id
)
# Decode response
response = tokenizer.decode(
outputs[0][len(inputs["input_ids"][0]):],
skip_special_tokens=True
)
# Thรชm response vร o history
history.append({"role": "assistant", "content": response})
return response, history
# Sแปญ dแปฅng
response, history = chat_with_qwen("Xin chร o! Bแบกn cรณ thแป giรบp tรดi gรฌ?")
print("๐ค:", response)
# Tiแบฟp tแปฅc cuแปc trรฒ chuyแปn
response2, history = chat_with_qwen("Viแปt Nam cรณ nhแปฏng mรณn ฤn gรฌ ngon?", history)
print("๐ค:", response2)
import requests
import json
class QwenAPI:
def __init__(self, endpoint_url, hf_token):
self.endpoint_url = endpoint_url
self.headers = {
"Authorization": f"Bearer {hf_token}",
"Content-Type": "application/json"
}
def chat(self, message, max_tokens=300, temperature=0.7):
payload = {
"inputs": f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n",
"parameters": {
"max_new_tokens": max_tokens,
"temperature": temperature,
"do_sample": True,
"top_p": 0.9,
"repetition_penalty": 1.1,
"stop": ["<|im_end|>"],
"return_full_text": False
}
}
try:
response = requests.post(self.endpoint_url, headers=self.headers, json=payload)
response.raise_for_status()
result = response.json()
return result[0]["generated_text"].strip()
except Exception as e:
return f"Lแปi: {str(e)}"
# Sแปญ dแปฅng
api = QwenAPI("YOUR_ENDPOINT_URL", "YOUR_HF_TOKEN")
# Single chat
response = api.chat("Hร Nแปi cรณ gรฌ ฤแบทc biแปt?")
print("๐ค:", response)
# Batch processing
questions = [
"Phแป bรฒ ฤฦฐแปฃc nแบฅu nhฦฐ thแบฟ nร o?",
"Lแปch sแปญ Viแปt Nam cรณ ฤiแปu gรฌ thรบ vแป?",
"Vฤn hรณa truyแปn thแปng Viแปt Nam nhฦฐ thแบฟ nร o?"
]
for q in questions:
answer = api.chat(q)
print(f"โ {q}")
print(f"๐ค {answer}\n")
import requests
import json
def stream_chat(message, endpoint_url, hf_token):
headers = {
"Authorization": f"Bearer {hf_token}",
"Content-Type": "application/json"
}
payload = {
"inputs": f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n",
"parameters": {
"max_new_tokens": 300,
"temperature": 0.7,
"do_sample": True,
"top_p": 0.9,
"stop": ["<|im_end|>"],
"return_full_text": False
},
"stream": True
}
response = requests.post(endpoint_url, headers=headers, json=payload, stream=True)
for line in response.iter_lines():
if line:
try:
data = json.loads(line.decode('utf-8'))
if 'token' in data:
print(data['token']['text'], end='', flush=True)
except:
continue
print() # New line at end
# Sแปญ dแปฅng
stream_chat("Kแป cho tรดi mแปt cรขu chuyแปn ngแบฏn vแป Viแปt Nam",
"YOUR_ENDPOINT_URL", "YOUR_HF_TOKEN")
| Specification | Value |
|---|---|
| Model Size | 3.09B parameters |
| Architecture | Qwen2.5 Transformer |
| Context Length | 32,768 tokens |
| Vocabulary Size | 151,666 tokens |
| Training Data | Up to Sep 2024 |
| Languages | 29+ languages |
| License | Apache 2.0 |
| Precision | BF16/FP16 |
def chat_with_system_prompt(message, system_prompt, model, tokenizer):
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": message}
]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer([text], return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.7)
response = tokenizer.decode(outputs[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
return response
# Example: Vietnamese tutor
system_prompt = "Bแบกn lร mแปt giรกo viรชn tiแบฟng Viแปt giร u kinh nghiแปm. Hรฃy giแบฃi thรญch cรกc khรกi niแปm mแปt cรกch rรต rร ng vร dแป
hiแปu."
response = chat_with_system_prompt(
"Giแบฃi thรญch vแป thฦก lแปฅc bรกt trong vฤn hแปc Viแปt Nam",
system_prompt, model, tokenizer
)
Model nร y cรณ thแป ฤฦฐแปฃc fine-tune thรชm cho specific domains:
# Example cho domain-specific fine-tuning
from transformers import TrainingArguments, Trainer
# Cแบฅu hรฌnh training
training_args = TrainingArguments(
output_dir="./qwen-finetuned",
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
learning_rate=5e-5,
num_train_epochs=3,
warmup_steps=100,
logging_steps=10,
save_strategy="epoch",
evaluation_strategy="epoch",
bf16=True, # Sแปญ dแปฅng bfloat16 cho efficiency
)
["<|im_end|>"]# Sแปญ dแปฅng gradient checkpointing
model.gradient_checkpointing_enable()
# Load vแปi 8-bit quantization nแบฟu cแบงn
from transformers import BitsAndBytesConfig
quantization_config = BitsAndBytesConfig(
load_in_8bit=True,
llm_int8_threshold=6.0,
)
model = AutoModelForCausalLM.from_pretrained(
"LuvU4ever/qwen2.5-3b-qlora-merged-v4",
quantization_config=quantization_config,
device_map="auto"
)
๐ Powered by Alibaba Cloud Qwen Team!