初始化项目,由ModelHub XC社区提供模型

Model: tzcfly/PertMind
Source: Original Platform
This commit is contained in:
ModelHub XC
2026-10-05 23:01:24 +08:00
commit 4f6a42b090
14 changed files with 809 additions and 0 deletions

3
.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
*.safetensors filter=lfs diff=lfs merge=lfs -text
tokenizer.json filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text

186
LICENSE Normal file
View File

@@ -0,0 +1,186 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and
distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the
copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other
entities that control, are controlled by, or are under common control with
that entity. For the purposes of this definition, "control" means (i) the
power, direct or indirect, to cause the direction or management of such
entity, whether by contract or otherwise, or (ii) ownership of fifty percent
(50%) or more of the outstanding shares, or (iii) beneficial ownership of
such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising
permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation source, and
configuration files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object
code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form,
made available under the License, as indicated by a copyright notice that is
included in or attached to the work (an example is provided in the Appendix
below).
"Derivative Works" shall mean any work, whether in Source or Object form,
that is based on (or derived from) the Work and for which the editorial
revisions, annotations, elaborations, or other modifications represent, as a
whole, an original work of authorship. For the purposes of this License,
Derivative Works shall not include works that remain separable from, or
merely link (or bind by name) to the interfaces of, the Work and Derivative
Works thereof.
"Contribution" shall mean any work of authorship, including the original
version of the Work and any modifications or additions to that Work or
Derivative Works thereof, that is intentionally submitted to Licensor for
inclusion in the Work by the copyright owner or by an individual or Legal
Entity authorized to submit on behalf of the copyright owner. For the
purposes of this definition, "submitted" means any form of electronic,
verbal, or written communication sent to the Licensor or its representatives,
including but not limited to communication on electronic mailing lists,
source code control systems, and issue tracking systems that are managed by,
or on behalf of, the Licensor for the purpose of discussing and improving the
Work, but excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on
behalf of whom a Contribution has been received by Licensor and subsequently
incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
reproduce, prepare Derivative Works of, publicly display, publicly perform,
sublicense, and distribute the Work and such Derivative Works in Source or
Object form.
3. Grant of Patent License. Subject to the terms and conditions of this
License, each Contributor hereby grants to You a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this
section) patent license to make, have made, use, offer to sell, sell, import,
and otherwise transfer the Work, where such license applies only to those
patent claims licensable by such Contributor that are necessarily infringed by
their Contribution(s) alone or by combination of their Contribution(s) with
the Work to which such Contribution(s) was submitted. If You institute patent
litigation against any entity (including a cross-claim or counterclaim in a
lawsuit) alleging that the Work or a Contribution incorporated within the Work
constitutes direct or contributory patent infringement, then any patent
licenses granted to You under this License for that Work shall terminate as of
the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or
Derivative Works thereof in any medium, with or without modifications, and in
Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy
of this License; and
(b) You must cause any modified files to carry prominent notices stating that
You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You
distribute, all copyright, patent, trademark, and attribution notices from
the Source form of the Work, excluding those notices that do not pertain to
any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution,
then any Derivative Works that You distribute must include a readable copy of
the attribution notices contained within such NOTICE file, excluding those
notices that do not pertain to any part of the Derivative Works, in at least
one of the following places: within a NOTICE text file distributed as part of
the Derivative Works; within the Source form or documentation, if provided
along with the Derivative Works; or, within a display generated by the
Derivative Works, if and wherever such third-party notices normally appear.
The contents of the NOTICE file are for informational purposes only and do not
modify the License. You may add Your own attribution notices within
Derivative Works that You distribute, alongside or as an addendum to the
NOTICE text from the Work, provided that such additional attribution notices
cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a
whole, provided Your use, reproduction, and distribution of the Work otherwise
complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any
Contribution intentionally submitted for inclusion in the Work by You to the
Licensor shall be under the terms and conditions of this License, without any
additional terms or conditions. Notwithstanding the above, nothing herein
shall supersede or modify the terms of any separate license agreement you may
have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as
required for reasonable and customary use in describing the origin of the Work
and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
writing, Licensor provides the Work (and each Contributor provides its
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied, including, without limitation, any warranties
or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any risks
associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in
tort, contract, or otherwise, unless required by applicable law (such as
deliberate and grossly negligent acts) or agreed to in writing, shall any
Contributor be liable to You for damages, including any direct, indirect,
special, incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the Work
(including but not limited to damages for loss of goodwill, work stoppage,
computer failure or malfunction, or any and all other commercial damages or
losses), even if such Contributor has been advised of the possibility of such
damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work
or Derivative Works thereof, You may choose to offer, and charge a fee for,
acceptance of support, warranty, indemnity, or other liability obligations
and/or rights consistent with this License. However, in accepting such
obligations, You may act only on Your own behalf and on Your sole
responsibility, not on behalf of any other Contributor, and only if You agree
to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your
accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included on
the same "printed page" as the copyright notice for easier identification
within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

144
README.md Normal file
View File

@@ -0,0 +1,144 @@
---
license: apache-2.0
library_name: transformers
pipeline_tag: text-generation
base_model: Qwen/Qwen3-4B-Base
tags:
- biology
- biomedical
- perturbation-response
- reinforcement-learning
- qwen3
- transformers
- vllm
---
# PertMind
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.
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).
![Figure 1](assets/Figure1.png)
*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.*
## Model Summary
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.
The released package preserves the model configuration, tokenizer assets, and three runnable inference entry points included in this repository:
- `inference_vllm.py`
- `inference_transformers.py`
- `tui_chat.py`
## Perturbation-Derived RL
PertMind operationalizes perturbation-derived reinforcement learning in three stages:
1. Gene-centered queries are assembled from the Tahoe-100M perturbation atlas and paired with experimentally derived `Up`, `Down`, or `No` response labels.
2. A small trusted set of model-generated trajectories provides structured supervised initialization, giving the policy an evidence-grounded starting point before reinforcement learning.
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.
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.
## Operational Emergence
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.
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.
## Intended Uses
Evidence-supported uses described in the manuscript include:
- forward perturbation-response reasoning in held-out biological contexts;
- reverse perturbation-condition inference and related transfer settings absent from post-training;
- biological-process interpretation and screen-oriented biological briefing;
- generation of PertMind-derived biological profiles for downstream molecular, cellular, and donor-level representations.
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.
## Out-Of-Scope Uses
PertMind is not intended for:
- clinical diagnosis, treatment selection, or other medical decision-making;
- replacing wet-lab validation or expert biological review;
- claims of faithful causal mechanism recovery from endpoint accuracy alone;
- unrestricted deployment to perturbation modalities, tissues, doses, or disease states that were not studied in the released work.
## Quick Start
Create a clean environment and install dependencies:
```bash
conda create -n pertmind python=3.11 -y
conda activate pertmind
pip install -r requirements.txt
```
If multiple Python environments are present, verify that the active interpreter is the one from `pertmind`:
```bash
which python
python -c "import sys; print(sys.executable)"
```
Run a single prompt with vLLM:
```bash
python inference_vllm.py \
--model . \
--prompt "In HCT116, predict how LMBR1 changes expression of SLC26A6."
```
Run a single prompt with Transformers:
```bash
python inference_transformers.py \
--model . \
--prompt "In HCT116, predict how LMBR1 changes expression of SLC26A6."
```
Start the terminal chat interface:
```bash
python tui_chat.py --model . --backend vllm
```
Useful TUI commands:
```text
/reset clear conversation history
/exit quit
```
## Tested Setup
The release content was prepared against the included runtime files and dependency pins:
- Python 3.11
- PyTorch 2.10.0
- Transformers 5.14.0
- Accelerate 1.14.0
- Safetensors 0.8.0
- vLLM 0.19.1
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.
## Limitations And Responsible Use
- Endpoint correctness does not by itself establish a faithful causal mechanism.
- Free-text trajectories are auditable, but the reward does not verify every intermediate reasoning step.
- Pathway supervision is a transcriptional proxy and does not directly measure protein activity, metabolic flux, spatial signaling, or causal pathway activation.
- The evaluated datasets, interventions, and downstream tasks cover only part of biological diversity, so generalization outside the studied settings remains unresolved.
- Retrieval resources and trusted trajectories may propagate omissions, annotation errors, and historical biases from their sources.
- PertMind-derived embeddings still depend on task-specific projections, aggregation, and downstream supervision.
PertMind is released for research use, hypothesis generation, and method development.
## License
This repository is released under the [Apache-2.0 License](LICENSE).

3
assets/Figure1.png Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1068b4c8edebcb9bd2e144d944d1fe6da6f4d79d872ef68c60c5dca98a5c11de
size 412350

89
chat_template.jinja Normal file
View File

@@ -0,0 +1,89 @@
{%- if tools %}
{{- '<|im_start|>system\n' }}
{%- if messages[0].role == 'system' %}
{{- messages[0].content + '\n\n' }}
{%- endif %}
{{- "# 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>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\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" }}
{%- else %}
{%- if messages[0].role == 'system' %}
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
{%- set index = (messages|length - 1) - loop.index0 %}
{%- 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>')) %}
{%- set ns.multi_step_tool = false %}
{%- set ns.last_query_index = index %}
{%- endif %}
{%- endfor %}
{%- for message in messages %}
{%- if message.content is string %}
{%- set content = message.content %}
{%- else %}
{%- set content = '' %}
{%- endif %}
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
{%- elif message.role == "assistant" %}
{%- set reasoning_content = '' %}
{%- if message.reasoning_content is string %}
{%- set reasoning_content = message.reasoning_content %}
{%- else %}
{%- if '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- if loop.index0 > ns.last_query_index %}
{%- if loop.last or (not loop.last and reasoning_content) %}
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- else %}
{{- '<|im_start|>' + message.role + '\n' + content }}
{%- endif %}
{%- if message.tool_calls %}
{%- for tool_call in message.tool_calls %}
{%- if (loop.first and content) or (not loop.first) %}
{{- '\n' }}
{%- endif %}
{%- if tool_call.function %}
{%- set tool_call = tool_call.function %}
{%- endif %}
{{- '<tool_call>\n{"name": "' }}
{{- tool_call.name }}
{{- '", "arguments": ' }}
{%- if tool_call.arguments is string %}
{{- tool_call.arguments }}
{%- else %}
{{- tool_call.arguments | tojson }}
{%- endif %}
{{- '}\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
{{- '<|im_start|>user' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking is false %}
{{- '<think>\n\n</think>\n\n' }}
{%- endif %}
{%- endif %}

71
config.json Normal file
View File

@@ -0,0 +1,71 @@
{
"architectures": [
"Qwen3ForCausalLM"
],
"attention_bias": false,
"attention_dropout": 0.0,
"bos_token_id": 151643,
"dtype": "bfloat16",
"eos_token_id": 151645,
"head_dim": 128,
"hidden_act": "silu",
"hidden_size": 2560,
"initializer_range": 0.02,
"intermediate_size": 9728,
"layer_types": [
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention",
"full_attention"
],
"max_position_embeddings": 40960,
"max_window_layers": 36,
"model_type": "qwen3",
"num_attention_heads": 32,
"num_hidden_layers": 36,
"num_key_value_heads": 8,
"pad_token_id": null,
"rms_norm_eps": 1e-06,
"rope_parameters": {
"rope_theta": 1000000,
"rope_type": "default"
},
"sliding_window": null,
"tie_word_embeddings": true,
"transformers_version": "5.12.0",
"use_cache": true,
"use_sliding_window": false,
"vocab_size": 151936
}

13
generation_config.json Normal file
View File

@@ -0,0 +1,13 @@
{
"bos_token_id": 151643,
"do_sample": true,
"eos_token_id": [
151645,
151643
],
"pad_token_id": 151643,
"temperature": 0.6,
"top_k": 20,
"top_p": 0.95,
"transformers_version": "5.12.0"
}

69
inference_transformers.py Executable file
View File

@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Run PertMind with Hugging Face Transformers."""
from __future__ import annotations
import argparse
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
DEFAULT_SYSTEM_PROMPT = (
"You are PertMind, a biomedical assistant. For biomedical prediction, "
"screen-ranking, or gene-set interpretation tasks, answer first and then "
"provide a concise explanation. Use this style when applicable:\n"
"Final Answer: <answer>\nExplanation: <brief explanation>"
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
parser.add_argument("--prompt", required=True, help="User prompt.")
parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
parser.add_argument("--max-new-tokens", type=int, default=768)
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--top-p", type=float, default=0.95)
return parser.parse_args()
def main() -> int:
args = parse_args()
tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
args.model,
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
device_map="auto",
trust_remote_code=True,
)
messages = [
{"role": "system", "content": args.system_prompt},
{"role": "user", "content": args.prompt},
]
try:
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
except TypeError:
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
do_sample = args.temperature > 0
outputs = model.generate(
**inputs,
max_new_tokens=args.max_new_tokens,
do_sample=do_sample,
temperature=args.temperature if do_sample else None,
top_p=args.top_p if do_sample else None,
pad_token_id=tokenizer.eos_token_id,
)
generated = outputs[0, inputs["input_ids"].shape[-1] :]
print(tokenizer.decode(generated, skip_special_tokens=True).strip())
return 0
if __name__ == "__main__":
raise SystemExit(main())

66
inference_vllm.py Executable file
View File

@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Run PertMind with vLLM."""
from __future__ import annotations
import argparse
from vllm import LLM, SamplingParams
DEFAULT_SYSTEM_PROMPT = (
"You are PertMind, a biomedical assistant. For biomedical prediction, "
"screen-ranking, or gene-set interpretation tasks, answer first and then "
"provide a concise explanation. Use this style when applicable:\n"
"Final Answer: <answer>\nExplanation: <brief explanation>"
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
parser.add_argument("--prompt", required=True, help="User prompt.")
parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
parser.add_argument("--max-tokens", type=int, default=768)
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--top-p", type=float, default=0.95)
parser.add_argument("--max-model-len", type=int, default=12288)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
return parser.parse_args()
def main() -> int:
args = parse_args()
llm = LLM(
model=args.model,
trust_remote_code=True,
dtype="bfloat16",
max_model_len=args.max_model_len,
gpu_memory_utilization=args.gpu_memory_utilization,
)
tokenizer = llm.get_tokenizer()
messages = [
{"role": "system", "content": args.system_prompt},
{"role": "user", "content": args.prompt},
]
try:
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
except TypeError:
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
params = SamplingParams(
temperature=args.temperature,
top_p=args.top_p,
max_tokens=args.max_tokens,
)
output = llm.generate([text], params)[0].outputs[0].text.strip()
print(output)
return 0
if __name__ == "__main__":
raise SystemExit(main())

3
model.safetensors Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:523a2b0dc10f350407064b804815a5fe22089fd1e54fae99072c620841081ca0
size 8044982080

5
requirements.txt Normal file
View File

@@ -0,0 +1,5 @@
torch==2.10.0
transformers==5.14.0
accelerate==1.14.0
safetensors==0.8.0
vllm==0.19.1

3
tokenizer.json Normal file
View File

@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506
size 11422650

16
tokenizer_config.json Normal file
View File

@@ -0,0 +1,16 @@
{
"add_prefix_space": false,
"backend": "tokenizers",
"bos_token": null,
"clean_up_tokenization_spaces": false,
"eos_token": "<|im_end|>",
"errors": "replace",
"is_local": true,
"local_files_only": false,
"model_max_length": 131072,
"pad_token": "<|endoftext|>",
"padding_side": "right",
"split_special_tokens": false,
"tokenizer_class": "Qwen2Tokenizer",
"unk_token": null
}

138
tui_chat.py Executable file
View File

@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""A small terminal chat UI for PertMind."""
from __future__ import annotations
import argparse
from dataclasses import dataclass
DEFAULT_SYSTEM_PROMPT = (
"You are PertMind, a biomedical assistant. For biomedical prediction, "
"screen-ranking, or gene-set interpretation tasks, answer first and then "
"provide a concise explanation. Use this style when applicable:\n"
"Final Answer: <answer>\nExplanation: <brief explanation>"
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", default=".", help="Path or Hugging Face model id.")
parser.add_argument("--backend", choices=["vllm", "transformers"], default="vllm")
parser.add_argument("--system-prompt", default=DEFAULT_SYSTEM_PROMPT)
parser.add_argument("--max-new-tokens", type=int, default=768)
parser.add_argument("--temperature", type=float, default=0.0)
parser.add_argument("--top-p", type=float, default=0.95)
parser.add_argument("--max-model-len", type=int, default=12288)
parser.add_argument("--gpu-memory-utilization", type=float, default=0.85)
return parser.parse_args()
def render_chat(tokenizer, messages: list[dict[str, str]]) -> str:
try:
return tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
enable_thinking=False,
)
except TypeError:
return tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
@dataclass
class VllmBackend:
model: str
max_model_len: int
gpu_memory_utilization: float
def __post_init__(self) -> None:
from vllm import LLM
self.llm = LLM(
model=self.model,
trust_remote_code=True,
dtype="bfloat16",
max_model_len=self.max_model_len,
gpu_memory_utilization=self.gpu_memory_utilization,
)
self.tokenizer = self.llm.get_tokenizer()
def generate(self, messages: list[dict[str, str]], max_new_tokens: int, temperature: float, top_p: float) -> str:
from vllm import SamplingParams
prompt = render_chat(self.tokenizer, messages)
params = SamplingParams(temperature=temperature, top_p=top_p, max_tokens=max_new_tokens)
return self.llm.generate([prompt], params)[0].outputs[0].text.strip()
@dataclass
class TransformersBackend:
model: str
def __post_init__(self) -> None:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
self.torch = torch
self.tokenizer = AutoTokenizer.from_pretrained(self.model, trust_remote_code=True)
self.llm = AutoModelForCausalLM.from_pretrained(
self.model,
torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,
device_map="auto",
trust_remote_code=True,
)
def generate(self, messages: list[dict[str, str]], max_new_tokens: int, temperature: float, top_p: float) -> str:
prompt = render_chat(self.tokenizer, messages)
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.llm.device)
do_sample = temperature > 0
outputs = self.llm.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=do_sample,
temperature=temperature if do_sample else None,
top_p=top_p if do_sample else None,
pad_token_id=self.tokenizer.eos_token_id,
)
generated = outputs[0, inputs["input_ids"].shape[-1] :]
return self.tokenizer.decode(generated, skip_special_tokens=True).strip()
def print_panel(title: str, text: str) -> None:
line = "=" * min(88, max(20, len(title) + 8))
print(f"\n{line}\n{title}\n{line}\n{text}\n")
def main() -> int:
args = parse_args()
if args.backend == "vllm":
backend = VllmBackend(args.model, args.max_model_len, args.gpu_memory_utilization)
else:
backend = TransformersBackend(args.model)
messages: list[dict[str, str]] = [{"role": "system", "content": args.system_prompt}]
print_panel("PertMind TUI", "Type your question and press Enter. Commands: /reset, /exit")
while True:
try:
user_text = input("You> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not user_text:
continue
if user_text.lower() in {"/exit", "exit", "quit", "/quit"}:
break
if user_text.lower() == "/reset":
messages = [{"role": "system", "content": args.system_prompt}]
print_panel("PertMind", "Conversation reset.")
continue
messages.append({"role": "user", "content": user_text})
answer = backend.generate(messages, args.max_new_tokens, args.temperature, args.top_p)
messages.append({"role": "assistant", "content": answer})
print_panel("PertMind", answer)
return 0
if __name__ == "__main__":
raise SystemExit(main())