Views
No views yet
Qwen/Qwen-1_8B-Chat model. This model was fine-tuned on a small, custom dataset to answer questions related to hemiplegia, cerebral thrombosis (stroke), and related conditions. This fine-tuning experiment is associated with work at Tiansuan AI.Qwen/Qwen-1_8B-Chat and then apply these LoRA weights using the PEFT library.1from peft import PeftModel
2from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
3import torch
4
5# Define model IDs
6base_model_id = "Qwen/Qwen-1_8B-Chat"
7lora_adapter_id = "jinv2/qwen-1_8b-hemiplegia-lora" # This is your model
8
9# Setup quantization configuration (as used during fine-tuning)
10quantization_config = BitsAndBytesConfig(
11 load_in_4bit=True,
12 bnb_4bit_compute_dtype=torch.float16 # Matches the successful fine-tuning compute dtype
13)
14
15# Load the base model with quantization
16print(f"Loading base model: {base_model_id}...")
17base_model = AutoModelForCausalLM.from_pretrained(
18 base_model_id,
19 quantization_config=quantization_config,
20 trust_remote_code=True,
21 device_map="auto" # Automatically distribute model on available anjing (GPU if available, else CPU)
22)
23print("Base model loaded.")
24
25# Load the tokenizer
26# It's good practice to load tokenizer from the same source as the fine-tuned adapter if uploaded,
27# or ensure base tokenizer settings (pad_token, etc.) are consistent.
28print(f"Loading tokenizer from: {lora_adapter_id} (or fallback to {base_model_id})...")
29try:
30 tokenizer = AutoTokenizer.from_pretrained(lora_adapter_id, trust_remote_code=True)
31 print(f"Successfully loaded tokenizer from {lora_adapter_id}.")
32except Exception:
33 print(f"Could not load tokenizer from {lora_adapter_id}, falling back to {base_model_id}.")
34 tokenizer = AutoTokenizer.from_pretrained(base_model_id, trust_remote_code=True)
35
36# Set pad_token if not already set (important for Qwen and generation)
37if tokenizer.pad_token_id is None:
38 if tokenizer.eos_token_id is not None:
39 tokenizer.pad_token_id = tokenizer.eos_token_id
40 print(f"Set tokenizer.pad_token_id to eos_token_id: {tokenizer.pad_token_id}")
41 else:
42 # Fallback if eos_token_id is also None (should not happen for Qwen)
43 # For Qwen, eos_token_id is typically around 151643 for <|endoftext|>
44 # tokenizer.pad_token_id = 151643 # Example, verify Qwen's actual eos_token_id
45 print("Warning: pad_token_id and eos_token_id are None. Generation might be problematic.")
46tokenizer.padding_side = "left" # Usually preferred for generation
47
48# Load the LoRA adapter onto the base model
49print(f"Loading LoRA adapter: {lora_adapter_id}...")
50model = PeftModel.from_pretrained(base_model, lora_adapter_id)
51model.eval() # Set the model to evaluation mode
52print("LoRA adapter loaded and model is ready for inference.")
53
54# --- Inference Example ---
55# Since tokenizer.chat_template was 'Not Available' during Colab run,
56# we manually construct the prompt according to Qwen's ChatML format.
57system_prompt_content = "你是一个专注于偏瘫、脑血栓、半身不遂领域的医疗问答助手。"
58user_query_content = "偏瘫患者的早期康复锻炼有哪些?" # A question from your training set
59
60prompt = f"<|im_start|>system\n{system_prompt_content}<|im_end|>\n<|im_start|>user\n{user_query_content}<|im_end|>\n<|im_start|>assistant\n"
61
62print(f"\nFormatted Prompt:\n{prompt}")
63
64inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
65
66# Generate response
67print("Generating response...")
68with torch.no_grad(): # Inference doesn't need gradient calculation
69 outputs = model.generate(
70 **inputs,
71 max_new_tokens=150,
72 pad_token_id=tokenizer.pad_token_id, # Crucial for generation to avoid warnings/errors
73 eos_token_id=[tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|im_end|>")] if tokenizer.eos_token_id is not None else None, # Qwen specific EOS handling
74 temperature=0.7,
75 top_p=0.9,
76 do_sample=True
77 )
78
79# Decode and print the response
80# We need to slice the output to get only the generated part, excluding the input prompt
81response_text = tokenizer.decode(outputs[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
82print(f"\nModel Response:\n{response_text.strip()}")
83
84# Example with a new question
85user_query_new = "中风后如何进行语言恢复训练?"
86prompt_new = f"<|im_start|>system\n{system_prompt_content}<|im_end|>\n<|im_start|>user\n{user_query_new}<|im_end|>\n<|im_start|>assistant\n"
87inputs_new = tokenizer(prompt_new, return_tensors="pt").to(model.device)
88print("\nGenerating response for a new question...")
89with torch.no_grad():
90 outputs_new = model.generate(
91 **inputs_new,
92 max_new_tokens=200,
93 pad_token_id=tokenizer.pad_token_id,
94 eos_token_id=[tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids("<|im_end|>")] if tokenizer.eos_token_id is not None else None,
95 temperature=0.7,
96 top_p=0.9,
97 do_sample=True
98 )
99response_text_new = tokenizer.decode(outputs_new[0][inputs_new.input_ids.shape[1]:], skip_special_tokens=True)
100print(f"\nModel Response (New Question):\n{response_text_new.strip()}")
101LICENSE file if included, or refer to Apache 2.0 License details.
The base model Qwen/Qwen-1_8B-Chat is subject to the Tongyi Qianwen LICENSE AGREEMENT.