Yirankong commited on
Commit
797d7cd
·
verified ·
1 Parent(s): 2fb79ee

Upload Qwen35-27B-FS_3.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. Qwen35-27B-FS_3.py +155 -0
Qwen35-27B-FS_3.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import time
3
+ from tqdm import tqdm
4
+ import os
5
+
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ import torch
8
+
9
+
10
+
11
+ model_name = "/data/Albus/Survival/Models/Qwen3.5-27B"
12
+
13
+ #load the tokenizer and the model
14
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
15
+ model = AutoModelForCausalLM.from_pretrained(
16
+ model_name,
17
+ torch_dtype=torch.bfloat16,
18
+ device_map="auto"
19
+ )
20
+
21
+ def Qwen_format(human_texts,ai_texts):
22
+ save_result ={
23
+
24
+ "conversations":[
25
+ {
26
+ "from":"human",
27
+ "value":human_texts
28
+ }
29
+ ,
30
+ {
31
+ "from":"Qwen-3",
32
+ "value": "None"
33
+ }
34
+ ]
35
+ ,
36
+ "images": None
37
+ }
38
+
39
+ save_result['conversations'][0]["value"] = human_texts
40
+ save_result['conversations'][1]["value"] = ai_texts
41
+
42
+ return save_result
43
+
44
+
45
+ def infer_COT(data,max_try = 6):
46
+ COT_ = []
47
+
48
+ for item in tqdm(data, desc="Infer_cot", unit="case"):
49
+ prompt = ""
50
+
51
+ for conversation in item['conversations']:
52
+ if conversation['from'] == 'human':
53
+ modified_text1 = """
54
+ Given the following patient clinical information and paired pre- and post-treatment GTV radiomic features, predict the cumulative Disease-Free Survival (DFS) probability at each specified follow-up interval.
55
+
56
+ The patient information includes:
57
+ • Clinical features
58
+ • Paired radiomic features extracted from the GTV, including:
59
+ - First-order statistical features
60
+ - 3D shape features
61
+
62
+ Predictions must be based on both **clinical features** and **paired pre- and post-treatment GTV radiomic features**.
63
+
64
+ Output requirements:
65
+ 1. Output exactly one line per interval.
66
+ 2. Each line must be wrapped in <answer>...</answer>.
67
+ 3. Probabilities must be decimals between 0 and 1 with exactly 4 decimal places.
68
+ 4. Cumulative DFS probabilities must be non-increasing over time.
69
+ 5. Do not include explanations, reasoning steps, or any additional text.
70
+
71
+ Example output (follow this exact format):
72
+ <answer>"By 15 months, the patient's cumulative Disease-Free Survival probability is **0.XXXX**."</answer>
73
+ <answer>"By 24 months, the patient's cumulative Disease-Free Survival probability is **0.XXXX**."</answer>
74
+ <answer>"By 36 months, the patient's cumulative Disease-Free Survival probability is **0.XXXX**."</answer>
75
+ ...
76
+ """
77
+
78
+
79
+
80
+
81
+ modified_text = modified_text1 + conversation['value']
82
+ prompt = modified_text
83
+ # print(prompt)
84
+ messages = [{
85
+ "role": "user",
86
+ "content": prompt
87
+ }]
88
+
89
+ attempt = 0
90
+ content = ""
91
+
92
+ while attempt < max_try:
93
+ attempt += 1
94
+
95
+ try:
96
+
97
+ text = tokenizer.apply_chat_template(
98
+ messages,
99
+ tokenize=False,
100
+ add_generation_prompt=True
101
+
102
+ )
103
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
104
+
105
+ # conduct text completion
106
+ generated_ids = model.generate(
107
+ **model_inputs,
108
+ max_new_tokens=6384,
109
+
110
+ do_sample=True,
111
+ temperature=0.7,
112
+ top_p=0.8,
113
+ top_k=20,
114
+ repetition_penalty=1.1 ,
115
+ min_p=0.1,
116
+ # **model_inputs,
117
+ # max_new_tokens=32768
118
+ )
119
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
120
+ content = tokenizer.decode(output_ids, skip_special_tokens=True)
121
+ if content.strip():
122
+ break
123
+ else:
124
+ print(f"{attempt}-th has defeat,try again!")
125
+
126
+ except Exception as e:
127
+ print(f"第 {attempt}-th has defeated: {e}")
128
+ time.sleep(20)
129
+
130
+ human_texts = conversation['value']
131
+
132
+ if content.strip():
133
+ ai_texts = content.strip()
134
+ COT_.append(Qwen_format(human_texts, ai_texts))
135
+ else:
136
+ print("⚠️ this case failed after max_try")
137
+
138
+
139
+ return COT_
140
+
141
+
142
+ infer_input = '/data/Albus/Survival/Data/DFS_cf_rf_V10_foshan.json'
143
+
144
+ cot_file = '/data/Albus/Survival/Result/Foshan_qwen35-27B_Base_e3.json'
145
+ os.makedirs(os.path.dirname(cot_file), exist_ok=True)
146
+
147
+ with open(infer_input, 'r', encoding='utf-8') as file:
148
+ input = json.load(file)
149
+
150
+ COT_results = infer_COT(input,max_try = 6)
151
+ with open(cot_file, 'w', encoding='utf-8') as f:
152
+ json.dump(COT_results, f, ensure_ascii=False, indent=4)
153
+
154
+ print(f"successfully save infer_cot to {cot_file}")
155
+