Views
No views yet
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.1from transformers import AutoModelForCausalLM, AutoTokenizer
2import torch
3
4# Load model và tokenizer
5model = AutoModelForCausalLM.from_pretrained(
6 "LuvU4ever/qwen2.5-3b-qlora-merged-v4",
7 torch_dtype=torch.bfloat16,
8 device_map="auto",
9 trust_remote_code=True
10)
11
12tokenizer = AutoTokenizer.from_pretrained("LuvU4ever/qwen2.5-3b-qlora-merged-v4")
13
14# Hàm chat
15def chat_with_qwen(message, history=None):
16 if history is None:
17 history = []
18
19 # Thêm tin nhắn mới vào history
20 history.append({"role": "user", "content": message})
21
22 # Tạo chat template
23 text = tokenizer.apply_chat_template(
24 history,
25 tokenize=False,
26 add_generation_prompt=True
27 )
28
29 # Tokenize
30 inputs = tokenizer([text], return_tensors="pt").to(model.device)
31
32 # Generate
33 with torch.no_grad():
34 outputs = model.generate(
35 **inputs,
36 max_new_tokens=512,
37 temperature=0.7,
38 do_sample=True,
39 top_p=0.9,
40 repetition_penalty=1.1,
41 pad_token_id=tokenizer.eos_token_id
42 )
43
44 # Decode response
45 response = tokenizer.decode(
46 outputs[0][len(inputs["input_ids"][0]):],
47 skip_special_tokens=True
48 )
49
50 # Thêm response vào history
51 history.append({"role": "assistant", "content": response})
52
53 return response, history
54
55# Sử dụng
56response, history = chat_with_qwen("Xin chào! Bạn có thể giúp tôi gì?")
57print("🤖:", response)
58
59# Tiếp tục cuộc trò chuyện
60response2, history = chat_with_qwen("Việt Nam có những món ăn gì ngon?", history)
61print("🤖:", response2)1import requests
2import json
3
4class QwenAPI:
5 def __init__(self, endpoint_url, hf_token):
6 self.endpoint_url = endpoint_url
7 self.headers = {
8 "Authorization": f"Bearer {hf_token}",
9 "Content-Type": "application/json"
10 }
11
12 def chat(self, message, max_tokens=300, temperature=0.7):
13 payload = {
14 "inputs": f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n",
15 "parameters": {
16 "max_new_tokens": max_tokens,
17 "temperature": temperature,
18 "do_sample": True,
19 "top_p": 0.9,
20 "repetition_penalty": 1.1,
21 "stop": ["<|im_end|>"],
22 "return_full_text": False
23 }
24 }
25
26 try:
27 response = requests.post(self.endpoint_url, headers=self.headers, json=payload)
28 response.raise_for_status()
29
30 result = response.json()
31 return result[0]["generated_text"].strip()
32
33 except Exception as e:
34 return f"Lỗi: {str(e)}"
35
36# Sử dụng
37api = QwenAPI("YOUR_ENDPOINT_URL", "YOUR_HF_TOKEN")
38
39# Single chat
40response = api.chat("Hà Nội có gì đặc biệt?")
41print("🤖:", response)
42
43# Batch processing
44questions = [
45 "Phở bò được nấu như thế nào?",
46 "Lịch sử Việt Nam có điều gì thú vị?",
47 "Văn hóa truyền thống Việt Nam như thế nào?"
48]
49
50for q in questions:
51 answer = api.chat(q)
52 print(f"❓ {q}")
53 print(f"🤖 {answer}\n")1import requests
2import json
3
4def stream_chat(message, endpoint_url, hf_token):
5 headers = {
6 "Authorization": f"Bearer {hf_token}",
7 "Content-Type": "application/json"
8 }
9
10 payload = {
11 "inputs": f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n",
12 "parameters": {
13 "max_new_tokens": 300,
14 "temperature": 0.7,
15 "do_sample": True,
16 "top_p": 0.9,
17 "stop": ["<|im_end|>"],
18 "return_full_text": False
19 },
20 "stream": True
21 }
22
23 response = requests.post(endpoint_url, headers=headers, json=payload, stream=True)
24
25 for line in response.iter_lines():
26 if line:
27 try:
28 data = json.loads(line.decode('utf-8'))
29 if 'token' in data:
30 print(data['token']['text'], end='', flush=True)
31 except:
32 continue
33 print() # New line at end
34
35# Sử dụng
36stream_chat("Kể cho tôi một câu chuyện ngắn về Việt Nam",
37 "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 |
1def chat_with_system_prompt(message, system_prompt, model, tokenizer):
2 messages = [
3 {"role": "system", "content": system_prompt},
4 {"role": "user", "content": message}
5 ]
6
7 text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
8 inputs = tokenizer([text], return_tensors="pt").to(model.device)
9
10 outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.7)
11 response = tokenizer.decode(outputs[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
12
13 return response
14
15# Example: Vietnamese tutor
16system_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."
17response = chat_with_system_prompt(
18 "Giải thích về thơ lục bát trong văn học Việt Nam",
19 system_prompt, model, tokenizer
20)1# Example cho domain-specific fine-tuning
2from transformers import TrainingArguments, Trainer
3
4# Cấu hình training
5training_args = TrainingArguments(
6 output_dir="./qwen-finetuned",
7 per_device_train_batch_size=4,
8 gradient_accumulation_steps=4,
9 learning_rate=5e-5,
10 num_train_epochs=3,
11 warmup_steps=100,
12 logging_steps=10,
13 save_strategy="epoch",
14 evaluation_strategy="epoch",
15 bf16=True, # Sử dụng bfloat16 cho efficiency
16)["<|im_end|>"]1# Sử dụng gradient checkpointing
2model.gradient_checkpointing_enable()
3
4# Load với 8-bit quantization nếu cần
5from transformers import BitsAndBytesConfig
6
7quantization_config = BitsAndBytesConfig(
8 load_in_8bit=True,
9 llm_int8_threshold=6.0,
10)
11
12model = AutoModelForCausalLM.from_pretrained(
13 "LuvU4ever/qwen2.5-3b-qlora-merged-v4",
14 quantization_config=quantization_config,
15 device_map="auto"
16)