lukatang commited on
Commit
14a19cc
·
1 Parent(s): ab6cffb

Publish PertMind model

Browse files
.gitattributes CHANGED
@@ -1,35 +1,3 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  *.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
3
+ *.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
LICENSE ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty percent
20
+ (50%) or more of the outstanding shares, or (iii) beneficial ownership of
21
+ such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source, and
28
+ configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation or
31
+ translation of a Source form, including but not limited to compiled object
32
+ code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that is
36
+ included in or attached to the work (an example is provided in the Appendix
37
+ below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as a
42
+ whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its representatives,
54
+ including but not limited to communication on electronic mailing lists,
55
+ source code control systems, and issue tracking systems that are managed by,
56
+ or on behalf of, the Licensor for the purpose of discussing and improving the
57
+ Work, but excluding communication that is conspicuously marked or otherwise
58
+ designated in writing by the copyright owner as "Not a Contribution."
59
+
60
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
61
+ behalf of whom a Contribution has been received by Licensor and subsequently
62
+ incorporated within the Work.
63
+
64
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
65
+ License, each Contributor hereby grants to You a perpetual, worldwide,
66
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
67
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
68
+ sublicense, and distribute the Work and such Derivative Works in Source or
69
+ Object form.
70
+
71
+ 3. Grant of Patent License. Subject to the terms and conditions of this
72
+ License, each Contributor hereby grants to You a perpetual, worldwide,
73
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
74
+ section) patent license to make, have made, use, offer to sell, sell, import,
75
+ and otherwise transfer the Work, where such license applies only to those
76
+ patent claims licensable by such Contributor that are necessarily infringed by
77
+ their Contribution(s) alone or by combination of their Contribution(s) with
78
+ the Work to which such Contribution(s) was submitted. If You institute patent
79
+ litigation against any entity (including a cross-claim or counterclaim in a
80
+ lawsuit) alleging that the Work or a Contribution incorporated within the Work
81
+ constitutes direct or contributory patent infringement, then any patent
82
+ licenses granted to You under this License for that Work shall terminate as of
83
+ the date such litigation is filed.
84
+
85
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
86
+ Derivative Works thereof in any medium, with or without modifications, and in
87
+ Source or Object form, provided that You meet the following conditions:
88
+
89
+ (a) You must give any other recipients of the Work or Derivative Works a copy
90
+ of this License; and
91
+
92
+ (b) You must cause any modified files to carry prominent notices stating that
93
+ You changed the files; and
94
+
95
+ (c) You must retain, in the Source form of any Derivative Works that You
96
+ distribute, all copyright, patent, trademark, and attribution notices from
97
+ the Source form of the Work, excluding those notices that do not pertain to
98
+ any part of the Derivative Works; and
99
+
100
+ (d) If the Work includes a "NOTICE" text file as part of its distribution,
101
+ then any Derivative Works that You distribute must include a readable copy of
102
+ the attribution notices contained within such NOTICE file, excluding those
103
+ notices that do not pertain to any part of the Derivative Works, in at least
104
+ one of the following places: within a NOTICE text file distributed as part of
105
+ the Derivative Works; within the Source form or documentation, if provided
106
+ along with the Derivative Works; or, within a display generated by the
107
+ Derivative Works, if and wherever such third-party notices normally appear.
108
+ The contents of the NOTICE file are for informational purposes only and do not
109
+ modify the License. You may add Your own attribution notices within
110
+ Derivative Works that You distribute, alongside or as an addendum to the
111
+ NOTICE text from the Work, provided that such additional attribution notices
112
+ cannot be construed as modifying the License.
113
+
114
+ You may add Your own copyright statement to Your modifications and may provide
115
+ additional or different license terms and conditions for use, reproduction, or
116
+ distribution of Your modifications, or for any such Derivative Works as a
117
+ whole, provided Your use, reproduction, and distribution of the Work otherwise
118
+ complies with the conditions stated in this License.
119
+
120
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
121
+ Contribution intentionally submitted for inclusion in the Work by You to the
122
+ Licensor shall be under the terms and conditions of this License, without any
123
+ additional terms or conditions. Notwithstanding the above, nothing herein
124
+ shall supersede or modify the terms of any separate license agreement you may
125
+ have executed with Licensor regarding such Contributions.
126
+
127
+ 6. Trademarks. This License does not grant permission to use the trade names,
128
+ trademarks, service marks, or product names of the Licensor, except as
129
+ required for reasonable and customary use in describing the origin of the Work
130
+ and reproducing the content of the NOTICE file.
131
+
132
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
133
+ writing, Licensor provides the Work (and each Contributor provides its
134
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
135
+ KIND, either express or implied, including, without limitation, any warranties
136
+ or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
137
+ PARTICULAR PURPOSE. You are solely responsible for determining the
138
+ appropriateness of using or redistributing the Work and assume any risks
139
+ associated with Your exercise of permissions under this License.
140
+
141
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
142
+ tort, contract, or otherwise, unless required by applicable law (such as
143
+ deliberate and grossly negligent acts) or agreed to in writing, shall any
144
+ Contributor be liable to You for damages, including any direct, indirect,
145
+ special, incidental, or consequential damages of any character arising as a
146
+ result of this License or out of the use or inability to use the Work
147
+ (including but not limited to damages for loss of goodwill, work stoppage,
148
+ computer failure or malfunction, or any and all other commercial damages or
149
+ losses), even if such Contributor has been advised of the possibility of such
150
+ damages.
151
+
152
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work
153
+ or Derivative Works thereof, You may choose to offer, and charge a fee for,
154
+ acceptance of support, warranty, indemnity, or other liability obligations
155
+ and/or rights consistent with this License. However, in accepting such
156
+ obligations, You may act only on Your own behalf and on Your sole
157
+ responsibility, not on behalf of any other Contributor, and only if You agree
158
+ to indemnify, defend, and hold each Contributor harmless for any liability
159
+ incurred by, or claims asserted against, such Contributor by reason of your
160
+ accepting any such warranty or additional liability.
161
+
162
+ END OF TERMS AND CONDITIONS
163
+
164
+ APPENDIX: How to apply the Apache License to your work.
165
+
166
+ To apply the Apache License to your work, attach the following boilerplate
167
+ notice, with the fields enclosed by brackets "[]" replaced with your own
168
+ identifying information. (Don't include the brackets!) The text should be
169
+ enclosed in the appropriate comment syntax for the file format. We also
170
+ recommend that a file or class name and description of purpose be included on
171
+ the same "printed page" as the copyright notice for easier identification
172
+ within third-party archives.
173
+
174
+ Copyright [yyyy] [name of copyright owner]
175
+
176
+ Licensed under the Apache License, Version 2.0 (the "License");
177
+ you may not use this file except in compliance with the License.
178
+ You may obtain a copy of the License at
179
+
180
+ http://www.apache.org/licenses/LICENSE-2.0
181
+
182
+ Unless required by applicable law or agreed to in writing, software
183
+ distributed under the License is distributed on an "AS IS" BASIS,
184
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
185
+ See the License for the specific language governing permissions and
186
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ library_name: transformers
4
+ pipeline_tag: text-generation
5
+ base_model: Qwen/Qwen3-4B-Base
6
+ tags:
7
+ - biology
8
+ - biomedical
9
+ - perturbation-response
10
+ - reinforcement-learning
11
+ - qwen3
12
+ - transformers
13
+ - vllm
14
+ ---
15
+
16
+ # PertMind
17
+
18
+ PertMind is a biological language model built around a central discovery: public cellular perturbation atlases can be reorganized into reinforcement-learning environments, where measured gene responses act as computable reward signals for biological reasoning. Instead of relying only on manually curated reasoning traces, PertMind combines trusted-trajectory supervised initialization with perturbation-derived reinforcement learning for perturbation-centered inference and biological profile generation.
19
+
20
+ PertMind is initialized from [Qwen/Qwen3-4B-Base](https://huggingface.co/Qwen/Qwen3-4B-Base). The project repository is [shapsider/PertMind](https://github.com/shapsider/PertMind).
21
+
22
+ ![Figure 1](assets/Figure1.png)
23
+
24
+ *Figure 1. Schematic scope of the capabilities enabled by PertMind. Reasoning-based applications use natural-language inference for perturbation-response prediction, perturbation prioritization, mechanism reasoning, and proposal planning. Embedding-based applications encode PertMind-generated biological profiles into reusable molecular, cellular, and donor representations for reference mapping, cellular perturbation-response prediction, and donor-level tumor-state reference mapping. The figure summarizes the intended capability space, not benchmark performance. Within this space, the quantitatively evaluated subset in the manuscript covers forward perturbation-response prediction, reverse perturbation-condition inference, phenotypic-screen hit prioritization, biological-process naming, and molecular-, cellular-, and donor-level reference mapping.*
25
+
26
+ ## Model Summary
27
+
28
+ PertMind starts from the Qwen3-4B base model family and treats perturbation-response prediction as a training interface for biological reasoning. Each query is centered on a `(cell line, perturbation, target gene)` triplet. The model receives retrieved biological context, but the query-specific endpoint remains hidden from the prompt. Training then rewards responses that align with experimentally observed perturbation outcomes.
29
+
30
+ The released package preserves the model configuration, tokenizer assets, and three runnable inference entry points included in this repository:
31
+
32
+ - `inference_vllm.py`
33
+ - `inference_transformers.py`
34
+ - `tui_chat.py`
35
+
36
+ ## Perturbation-Derived RL
37
+
38
+ PertMind operationalizes perturbation-derived reinforcement learning in three stages:
39
+
40
+ 1. Gene-centered queries are assembled from the Tahoe-100M perturbation atlas and paired with experimentally derived `Up`, `Down`, or `No` response labels.
41
+ 2. A small trusted set of model-generated trajectories provides structured supervised initialization, giving the policy an evidence-grounded starting point before reinforcement learning.
42
+ 3. Group Relative Policy Optimization then optimizes a composite reward with three parts: a gene-level endpoint reward, a pathway-direction reward derived from transcriptional response summaries, and a format reward that keeps outputs parseable.
43
+
44
+ This setup is meant to test whether reinforcement on experimental endpoints can concentrate reusable biological strategies that are already accessible to a pretrained language model.
45
+
46
+ ## Operational Emergence
47
+
48
+ In the PertMind manuscript, *emergence* is used in an operational sense: a capability appears on a target task that was absent from post-training. PertMind is post-trained only on forward perturbation-response prediction, while the manuscript evaluates transfer to other biological tasks such as reverse perturbation-condition inference, phenotypic-screen prioritization, biological-process interpretation, and multiscale representation construction.
49
+
50
+ This framing is intentionally bounded. Transfer outside the post-training objective supports the hypothesis that PertMind learns reusable biological strategies, but it does not prove that every free-text reasoning trace is mechanistically faithful.
51
+
52
+ ## Intended Uses
53
+
54
+ Evidence-supported uses described in the manuscript include:
55
+
56
+ - forward perturbation-response reasoning in held-out biological contexts;
57
+ - reverse perturbation-condition inference and related transfer settings absent from post-training;
58
+ - biological-process interpretation and screen-oriented biological briefing;
59
+ - generation of PertMind-derived biological profiles for downstream molecular, cellular, and donor-level representations.
60
+
61
+ Broader intended capability scope illustrated in Figure 1 includes mechanism reasoning and proposal planning. Figure 1 should be read as a capability overview, not as a benchmark summary.
62
+
63
+ ## Out-Of-Scope Uses
64
+
65
+ PertMind is not intended for:
66
+
67
+ - clinical diagnosis, treatment selection, or other medical decision-making;
68
+ - replacing wet-lab validation or expert biological review;
69
+ - claims of faithful causal mechanism recovery from endpoint accuracy alone;
70
+ - unrestricted deployment to perturbation modalities, tissues, doses, or disease states that were not studied in the released work.
71
+
72
+ ## Quick Start
73
+
74
+ Create a clean environment and install dependencies:
75
+
76
+ ```bash
77
+ conda create -n pertmind python=3.11 -y
78
+ conda activate pertmind
79
+ pip install -r requirements.txt
80
+ ```
81
+
82
+ If multiple Python environments are present, verify that the active interpreter is the one from `pertmind`:
83
+
84
+ ```bash
85
+ which python
86
+ python -c "import sys; print(sys.executable)"
87
+ ```
88
+
89
+ Run a single prompt with vLLM:
90
+
91
+ ```bash
92
+ python inference_vllm.py \
93
+ --model . \
94
+ --prompt "In HCT116, predict how LMBR1 changes expression of SLC26A6."
95
+ ```
96
+
97
+ Run a single prompt with Transformers:
98
+
99
+ ```bash
100
+ python inference_transformers.py \
101
+ --model . \
102
+ --prompt "In HCT116, predict how LMBR1 changes expression of SLC26A6."
103
+ ```
104
+
105
+ Start the terminal chat interface:
106
+
107
+ ```bash
108
+ python tui_chat.py --model . --backend vllm
109
+ ```
110
+
111
+ Useful TUI commands:
112
+
113
+ ```text
114
+ /reset clear conversation history
115
+ /exit quit
116
+ ```
117
+
118
+ ## Tested Setup
119
+
120
+ The release content was prepared against the included runtime files and dependency pins:
121
+
122
+ - Python 3.11
123
+ - PyTorch 2.10.0
124
+ - Transformers 5.14.0
125
+ - Accelerate 1.14.0
126
+ - Safetensors 0.8.0
127
+ - vLLM 0.19.1
128
+
129
+ The model package is approximately 7.5 GB in `bfloat16`. A GPU with at least 16 GB VRAM is recommended for basic inference. Larger context lengths and vLLM serving may require more VRAM, and the first vLLM run may spend extra time compiling and caching CUDA graphs.
130
+
131
+ ## Limitations And Responsible Use
132
+
133
+ - Endpoint correctness does not by itself establish a faithful causal mechanism.
134
+ - Free-text trajectories are auditable, but the reward does not verify every intermediate reasoning step.
135
+ - Pathway supervision is a transcriptional proxy and does not directly measure protein activity, metabolic flux, spatial signaling, or causal pathway activation.
136
+ - The evaluated datasets, interventions, and downstream tasks cover only part of biological diversity, so generalization outside the studied settings remains unresolved.
137
+ - Retrieval resources and trusted trajectories may propagate omissions, annotation errors, and historical biases from their sources.
138
+ - PertMind-derived embeddings still depend on task-specific projections, aggregation, and downstream supervision.
139
+
140
+ PertMind is released for research use, hypothesis generation, and method development.
141
+
142
+ ## License
143
+
144
+ This repository is released under the [Apache-2.0 License](LICENSE).
assets/Figure1.png ADDED

Git LFS Details

  • SHA256: 1068b4c8edebcb9bd2e144d944d1fe6da6f4d79d872ef68c60c5dca98a5c11de
  • Pointer size: 131 Bytes
  • Size of remote file: 412 kB
chat_template.jinja ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0].role == 'system' %}
4
+ {{- messages[0].content + '\n\n' }}
5
+ {%- endif %}
6
+ {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
7
+ {%- for tool in tools %}
8
+ {{- "\n" }}
9
+ {{- tool | tojson }}
10
+ {%- endfor %}
11
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
12
+ {%- else %}
13
+ {%- if messages[0].role == 'system' %}
14
+ {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
15
+ {%- endif %}
16
+ {%- endif %}
17
+ {%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
18
+ {%- for message in messages[::-1] %}
19
+ {%- set index = (messages|length - 1) - loop.index0 %}
20
+ {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
21
+ {%- set ns.multi_step_tool = false %}
22
+ {%- set ns.last_query_index = index %}
23
+ {%- endif %}
24
+ {%- endfor %}
25
+ {%- for message in messages %}
26
+ {%- if message.content is string %}
27
+ {%- set content = message.content %}
28
+ {%- else %}
29
+ {%- set content = '' %}
30
+ {%- endif %}
31
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
32
+ {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
33
+ {%- elif message.role == "assistant" %}
34
+ {%- set reasoning_content = '' %}
35
+ {%- if message.reasoning_content is string %}
36
+ {%- set reasoning_content = message.reasoning_content %}
37
+ {%- else %}
38
+ {%- if '</think>' in content %}
39
+ {%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
40
+ {%- set content = content.split('</think>')[-1].lstrip('\n') %}
41
+ {%- endif %}
42
+ {%- endif %}
43
+ {%- if loop.index0 > ns.last_query_index %}
44
+ {%- if loop.last or (not loop.last and reasoning_content) %}
45
+ {{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
46
+ {%- else %}
47
+ {{- '<|im_start|>' + message.role + '\n' + content }}
48
+ {%- endif %}
49
+ {%- else %}
50
+ {{- '<|im_start|>' + message.role + '\n' + content }}
51
+ {%- endif %}
52
+ {%- if message.tool_calls %}
53
+ {%- for tool_call in message.tool_calls %}
54
+ {%- if (loop.first and content) or (not loop.first) %}
55
+ {{- '\n' }}
56
+ {%- endif %}
57
+ {%- if tool_call.function %}
58
+ {%- set tool_call = tool_call.function %}
59
+ {%- endif %}
60
+ {{- '<tool_call>\n{"name": "' }}
61
+ {{- tool_call.name }}
62
+ {{- '", "arguments": ' }}
63
+ {%- if tool_call.arguments is string %}
64
+ {{- tool_call.arguments }}
65
+ {%- else %}
66
+ {{- tool_call.arguments | tojson }}
67
+ {%- endif %}
68
+ {{- '}\n</tool_call>' }}
69
+ {%- endfor %}
70
+ {%- endif %}
71
+ {{- '<|im_end|>\n' }}
72
+ {%- elif message.role == "tool" %}
73
+ {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
74
+ {{- '<|im_start|>user' }}
75
+ {%- endif %}
76
+ {{- '\n<tool_response>\n' }}
77
+ {{- content }}
78
+ {{- '\n</tool_response>' }}
79
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
80
+ {{- '<|im_end|>\n' }}
81
+ {%- endif %}
82
+ {%- endif %}
83
+ {%- endfor %}
84
+ {%- if add_generation_prompt %}
85
+ {{- '<|im_start|>assistant\n' }}
86
+ {%- if enable_thinking is defined and enable_thinking is false %}
87
+ {{- '<think>\n\n</think>\n\n' }}
88
+ {%- endif %}
89
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "Qwen3ForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "dtype": "bfloat16",
9
+ "eos_token_id": 151645,
10
+ "head_dim": 128,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2560,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 9728,
15
+ "layer_types": [
16
+ "full_attention",
17
+ "full_attention",
18
+ "full_attention",
19
+ "full_attention",
20
+ "full_attention",
21
+ "full_attention",
22
+ "full_attention",
23
+ "full_attention",
24
+ "full_attention",
25
+ "full_attention",
26
+ "full_attention",
27
+ "full_attention",
28
+ "full_attention",
29
+ "full_attention",
30
+ "full_attention",
31
+ "full_attention",
32
+ "full_attention",
33
+ "full_attention",
34
+ "full_attention",
35
+ "full_attention",
36
+ "full_attention",
37
+ "full_attention",
38
+ "full_attention",
39
+ "full_attention",
40
+ "full_attention",
41
+ "full_attention",
42
+ "full_attention",
43
+ "full_attention",
44
+ "full_attention",
45
+ "full_attention",
46
+ "full_attention",
47
+ "full_attention",
48
+ "full_attention",
49
+ "full_attention",
50
+ "full_attention",
51
+ "full_attention"
52
+ ],
53
+ "max_position_embeddings": 40960,
54
+ "max_window_layers": 36,
55
+ "model_type": "qwen3",
56
+ "num_attention_heads": 32,
57
+ "num_hidden_layers": 36,
58
+ "num_key_value_heads": 8,
59
+ "pad_token_id": null,
60
+ "rms_norm_eps": 1e-06,
61
+ "rope_parameters": {
62
+ "rope_theta": 1000000,
63
+ "rope_type": "default"
64
+ },
65
+ "sliding_window": null,
66
+ "tie_word_embeddings": true,
67
+ "transformers_version": "5.12.0",
68
+ "use_cache": true,
69
+ "use_sliding_window": false,
70
+ "vocab_size": 151936
71
+ }
generation_config.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "temperature": 0.6,
10
+ "top_k": 20,
11
+ "top_p": 0.95,
12
+ "transformers_version": "5.12.0"
13
+ }
inference_transformers.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run PertMind with Hugging Face Transformers."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+
11
+
12
+ DEFAULT_SYSTEM_PROMPT = (
13
+ "You are PertMind, a biomedical assistant. For biomedical prediction, "
14
+ "screen-ranking, or gene-set interpretation tasks, answer first and then "
15
+ "provide a concise explanation. Use this style when applicable:\n"
16
+ "Final Answer: <answer>\nExplanation: <brief explanation>"
17
+ )
18
+
19
+
20
+ def parse_args() -> argparse.Namespace:
21
+ parser = argparse.ArgumentParser(description=__doc__)
22
+ parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
23
+ parser.add_argument("--prompt", required=True, help="User prompt.")
24
+ parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
25
+ parser.add_argument("--max-new-tokens", type=int, default=768)
26
+ parser.add_argument("--temperature", type=float, default=0.0)
27
+ parser.add_argument("--top-p", type=float, default=0.95)
28
+ return parser.parse_args()
29
+
30
+
31
+ def main() -> int:
32
+ args = parse_args()
33
+ tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
34
+ model = AutoModelForCausalLM.from_pretrained(
35
+ args.model,
36
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
37
+ device_map="auto",
38
+ trust_remote_code=True,
39
+ )
40
+ messages = [
41
+ {"role": "system", "content": args.system_prompt},
42
+ {"role": "user", "content": args.prompt},
43
+ ]
44
+ try:
45
+ text = tokenizer.apply_chat_template(
46
+ messages,
47
+ tokenize=False,
48
+ add_generation_prompt=True,
49
+ enable_thinking=False,
50
+ )
51
+ except TypeError:
52
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
53
+ inputs = tokenizer(text, return_tensors="pt").to(model.device)
54
+ do_sample = args.temperature > 0
55
+ outputs = model.generate(
56
+ **inputs,
57
+ max_new_tokens=args.max_new_tokens,
58
+ do_sample=do_sample,
59
+ temperature=args.temperature if do_sample else None,
60
+ top_p=args.top_p if do_sample else None,
61
+ pad_token_id=tokenizer.eos_token_id,
62
+ )
63
+ generated = outputs[0, inputs["input_ids"].shape[-1] :]
64
+ print(tokenizer.decode(generated, skip_special_tokens=True).strip())
65
+ return 0
66
+
67
+
68
+ if __name__ == "__main__":
69
+ raise SystemExit(main())
inference_vllm.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run PertMind with vLLM."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+
8
+ from vllm import LLM, SamplingParams
9
+
10
+
11
+ DEFAULT_SYSTEM_PROMPT = (
12
+ "You are PertMind, a biomedical assistant. For biomedical prediction, "
13
+ "screen-ranking, or gene-set interpretation tasks, answer first and then "
14
+ "provide a concise explanation. Use this style when applicable:\n"
15
+ "Final Answer: <answer>\nExplanation: <brief explanation>"
16
+ )
17
+
18
+
19
+ def parse_args() -> argparse.Namespace:
20
+ parser = argparse.ArgumentParser(description=__doc__)
21
+ parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
22
+ parser.add_argument("--prompt", required=True, help="User prompt.")
23
+ parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
24
+ parser.add_argument("--max-tokens", type=int, default=768)
25
+ parser.add_argument("--temperature", type=float, default=0.0)
26
+ parser.add_argument("--top-p", type=float, default=0.95)
27
+ parser.add_argument("--max-model-len", type=int, default=12288)
28
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
29
+ return parser.parse_args()
30
+
31
+
32
+ def main() -> int:
33
+ args = parse_args()
34
+ llm = LLM(
35
+ model=args.model,
36
+ trust_remote_code=True,
37
+ dtype="bfloat16",
38
+ max_model_len=args.max_model_len,
39
+ gpu_memory_utilization=args.gpu_memory_utilization,
40
+ )
41
+ tokenizer = llm.get_tokenizer()
42
+ messages = [
43
+ {"role": "system", "content": args.system_prompt},
44
+ {"role": "user", "content": args.prompt},
45
+ ]
46
+ try:
47
+ text = tokenizer.apply_chat_template(
48
+ messages,
49
+ tokenize=False,
50
+ add_generation_prompt=True,
51
+ enable_thinking=False,
52
+ )
53
+ except TypeError:
54
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
55
+ params = SamplingParams(
56
+ temperature=args.temperature,
57
+ top_p=args.top_p,
58
+ max_tokens=args.max_tokens,
59
+ )
60
+ output = llm.generate([text], params)[0].outputs[0].text.strip()
61
+ print(output)
62
+ return 0
63
+
64
+
65
+ if __name__ == "__main__":
66
+ raise SystemExit(main())
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:523a2b0dc10f350407064b804815a5fe22089fd1e54fae99072c620841081ca0
3
+ size 8044982080
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ transformers==5.14.0
3
+ accelerate==1.14.0
4
+ safetensors==0.8.0
5
+ vllm==0.19.1
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
3
+ size 11422650
tokenizer_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "backend": "tokenizers",
4
+ "bos_token": null,
5
+ "clean_up_tokenization_spaces": false,
6
+ "eos_token": "<|im_end|>",
7
+ "errors": "replace",
8
+ "is_local": true,
9
+ "local_files_only": false,
10
+ "model_max_length": 131072,
11
+ "pad_token": "<|endoftext|>",
12
+ "padding_side": "right",
13
+ "split_special_tokens": false,
14
+ "tokenizer_class": "Qwen2Tokenizer",
15
+ "unk_token": null
16
+ }
tui_chat.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """A small terminal chat UI for PertMind."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from dataclasses import dataclass
8
+
9
+
10
+ DEFAULT_SYSTEM_PROMPT = (
11
+ "You are PertMind, a biomedical assistant. For biomedical prediction, "
12
+ "screen-ranking, or gene-set interpretation tasks, answer first and then "
13
+ "provide a concise explanation. Use this style when applicable:\n"
14
+ "Final Answer: <answer>\nExplanation: <brief explanation>"
15
+ )
16
+
17
+
18
+ def parse_args() -> argparse.Namespace:
19
+ parser = argparse.ArgumentParser(description=__doc__)
20
+ parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
21
+ parser.add_argument("--backend", choices=["vllm", "transformers"], default="vllm")
22
+ parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
23
+ parser.add_argument("--max-new-tokens", type=int, default=768)
24
+ parser.add_argument("--temperature", type=float, default=0.0)
25
+ parser.add_argument("--top-p", type=float, default=0.95)
26
+ parser.add_argument("--max-model-len", type=int, default=12288)
27
+ parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
28
+ return parser.parse_args()
29
+
30
+
31
+ def render_chat(tokenizer, messages: list[dict[str, str]]) -> str:
32
+ try:
33
+ return tokenizer.apply_chat_template(
34
+ messages,
35
+ tokenize=False,
36
+ add_generation_prompt=True,
37
+ enable_thinking=False,
38
+ )
39
+ except TypeError:
40
+ return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
41
+
42
+
43
+ @dataclass
44
+ class VllmBackend:
45
+ model: str
46
+ max_model_len: int
47
+ gpu_memory_utilization: float
48
+
49
+ def __post_init__(self) -> None:
50
+ from vllm import LLM
51
+
52
+ self.llm = LLM(
53
+ model=self.model,
54
+ trust_remote_code=True,
55
+ dtype="bfloat16",
56
+ max_model_len=self.max_model_len,
57
+ gpu_memory_utilization=self.gpu_memory_utilization,
58
+ )
59
+ self.tokenizer = self.llm.get_tokenizer()
60
+
61
+ def generate(self, messages: list[dict[str, str]], max_new_tokens: int, temperature: float, top_p: float) -> str:
62
+ from vllm import SamplingParams
63
+
64
+ prompt = render_chat(self.tokenizer, messages)
65
+ params = SamplingParams(temperature=temperature, top_p=top_p, max_tokens=max_new_tokens)
66
+ return self.llm.generate([prompt], params)[0].outputs[0].text.strip()
67
+
68
+
69
+ @dataclass
70
+ class TransformersBackend:
71
+ model: str
72
+
73
+ def __post_init__(self) -> None:
74
+ import torch
75
+ from transformers import AutoModelForCausalLM, AutoTokenizer
76
+
77
+ self.torch = torch
78
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model, trust_remote_code=True)
79
+ self.llm = AutoModelForCausalLM.from_pretrained(
80
+ self.model,
81
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
82
+ device_map="auto",
83
+ trust_remote_code=True,
84
+ )
85
+
86
+ def generate(self, messages: list[dict[str, str]], max_new_tokens: int, temperature: float, top_p: float) -> str:
87
+ prompt = render_chat(self.tokenizer, messages)
88
+ inputs = self.tokenizer(prompt, return_tensors="pt").to(self.llm.device)
89
+ do_sample = temperature > 0
90
+ outputs = self.llm.generate(
91
+ **inputs,
92
+ max_new_tokens=max_new_tokens,
93
+ do_sample=do_sample,
94
+ temperature=temperature if do_sample else None,
95
+ top_p=top_p if do_sample else None,
96
+ pad_token_id=self.tokenizer.eos_token_id,
97
+ )
98
+ generated = outputs[0, inputs["input_ids"].shape[-1] :]
99
+ return self.tokenizer.decode(generated, skip_special_tokens=True).strip()
100
+
101
+
102
+ def print_panel(title: str, text: str) -> None:
103
+ line = "=" * min(88, max(20, len(title) + 8))
104
+ print(f"\n{line}\n{title}\n{line}\n{text}\n")
105
+
106
+
107
+ def main() -> int:
108
+ args = parse_args()
109
+ if args.backend == "vllm":
110
+ backend = VllmBackend(args.model, args.max_model_len, args.gpu_memory_utilization)
111
+ else:
112
+ backend = TransformersBackend(args.model)
113
+
114
+ messages: list[dict[str, str]] = [{"role": "system", "content": args.system_prompt}]
115
+ print_panel("PertMind TUI", "Type your question and press Enter. Commands: /reset, /exit")
116
+ while True:
117
+ try:
118
+ user_text = input("You> ").strip()
119
+ except (EOFError, KeyboardInterrupt):
120
+ print()
121
+ break
122
+ if not user_text:
123
+ continue
124
+ if user_text.lower() in {"/exit", "exit", "quit", "/quit"}:
125
+ break
126
+ if user_text.lower() == "/reset":
127
+ messages = [{"role": "system", "content": args.system_prompt}]
128
+ print_panel("PertMind", "Conversation reset.")
129
+ continue
130
+ messages.append({"role": "user", "content": user_text})
131
+ answer = backend.generate(messages, args.max_new_tokens, args.temperature, args.top_p)
132
+ messages.append({"role": "assistant", "content": answer})
133
+ print_panel("PertMind", answer)
134
+ return 0
135
+
136
+
137
+ if __name__ == "__main__":
138
+ raise SystemExit(main())