commit 2f408ed7e10732ac60271dce02f6f963ebf171e4 Author: ModelHub XC Date: Mon Aug 24 17:31:16 2026 +0800 初始化项目,由ModelHub XC社区提供模型 Model: nopenet/nope-edge-mini Source: Original Platform diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..52373fe --- /dev/null +++ b/.gitattributes @@ -0,0 +1,36 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +tokenizer.json filter=lfs diff=lfs merge=lfs -text diff --git a/DISCLAIMER.md b/DISCLAIMER.md new file mode 100644 index 0000000..75ac1f8 --- /dev/null +++ b/DISCLAIMER.md @@ -0,0 +1,115 @@ +# Disclaimers, Intended Use & Non-Claims + +NOPE Edge is a fine-tuned text **classifier** that surfaces linguistic signals +associated with safety-critical content (suicidal ideation, self-harm, abuse, +violence, and related risk categories). It is **not a conversational AI, not a +service NOPE operates, and not a crisis service.** These weights are MIT-licensed +and run entirely on your own infrastructure: NOPE receives no user data, runs +nothing for your users, and has no ability to contact, warn, or intervene with +anyone. + +The MIT License (see `LICENSE.md`) is the complete licence and already provides +the model "AS IS" with no warranty and no liability. The statements below are the +NOPE-specific intended-use and non-claims layer; they add to, and do not limit, +the MIT disclaimer. + +## What Edge is NOT + +Edge is **not predictive, not diagnostic, not therapeutic, and not a replacement +for clinical judgment.** Its outputs reflect what is present in the text, not what +will happen next. Edge is **not** a medical device, **not** a validated clinical +instrument, **not** FDA-cleared/approved/registered, **not** CE-marked or +certified under EU MDR, and **not** an approved or certified safety tool in any +jurisdiction. Outputs are **probabilistic signals intended for triage and +flagging by a human**, not clinical assessments or definitive determinations. + +Edge's risk vocabulary is **informed by** clinical frameworks (C-SSRS, HCR-20, +DASH). These citations describe the lineage of the risk-axis structure — they are +**not** an assertion of clinical equivalence or validation, and Edge's outputs are +not certified against any of those instruments. + +## Intended use + +Edge is designed to **supplement, not replace, human review.** It provides +classification signals; **you make the decisions.** Edge sees only the text you +pass it — it cannot assess context, history, relationships, or any factor known +only to you, the people in the conversation, or a qualified professional. + +A detection is a flag for human attention, **not a trigger for automated action.** +Subject attribution (self / other / unknown) is **informational only** and is not +always reliable — do not use it to dismiss or deprioritize a detection. Treat all +detected crises as serious enough to warrant escalation or flagging, regardless of +subject. + +## Out of scope — do NOT deploy Edge for + +- Autonomous intervention, escalation, or any significant action (account + suspension, mandatory intervention, emergency-contact notification, safety- + affecting content removal) taken **solely** on an Edge output without human review. +- Clinical diagnosis, treatment recommendations, or medical advice to any person. +- Real-time, time-critical, or emergency assessment. +- Predictive screening of individuals — Edge classifies conversations, not people. +- Any decision affecting a person's health, safety, or welfare made without + appropriate human oversight and, where relevant, qualified clinical judgment. +- Settings without a path for people to dispute or appeal a classification, or + without informed consent about Edge's role in your pipeline. + +## False positives and false negatives WILL occur + +No automated classification system can achieve 100% accuracy; errors are +**inevitable and expected.** Edge **will** produce: + +- **False negatives** — content that should be flagged but is not. **Some people in + genuine crisis will not be identified.** +- **False positives** — benign content incorrectly flagged. +- **Severity / imminence misclassifications**, over- and under-estimating risk. +- **Inconsistent results** on similar or identical inputs. +- **Missed context** — failures on sarcasm, fiction frames, cultural idiom, coded + or metaphorical language. + +A high score is not a clinical assessment; a low score is **not a clearance +signal.** Edge can be wrong in either direction — treating its output as the +decision, rather than one input to a human decision, is a misuse. Documented +weaknesses include deep multi-turn needles (~33% detection at 18–25 turns), +"resolution syndrome," and implicit/religious/metaphorical ideation. Edge is not +validated for all populations, languages, or cultural contexts. Treat outputs as +signal, not ground truth, and tune thresholds against your own data. + +## Not a crisis or emergency service + +Edge cannot provide crisis intervention, emergency response, or real-time human +support, and cannot dispatch emergency services. It is not a substitute for +emergency services, clinical assessment, or professional crisis intervention. +**If you or someone else is in immediate danger, contact your local emergency +services now.** Crisis resources are available at https://talk.help. If you deploy +Edge, you are responsible for ensuring the people you serve have clear, prominent +access to emergency resources **independent of** any Edge output. + +## Assumption of risk and responsibility + +By downloading and deploying these weights you **assume all risk** associated with +their use. The potential consequences of classification errors include serious +harm or death. You are best positioned to implement appropriate safeguards, human +oversight, and crisis-response protocols for your use case and the people you +serve, and you accept sole responsibility for all decisions — and any action taken +or not taken — based on Edge outputs. NopeNet expressly disclaims any +responsibility for decisions made based on Edge outputs, and has no direct +relationship with, duty to, or liability toward the people whose interactions you +analyze; any duty of care or obligation to intervene rests solely with you. + +## Self-hosted — your data, your responsibility + +These weights run on **your** infrastructure. NOPE does not see, receive, store, +or process anything you run through them. You are the data controller and are +responsible for compliance with all applicable data-protection and other laws +(e.g. GDPR, HIPAA) for any data you process. Use of Edge does not by itself +satisfy, or create a defense under, any legal or regulatory requirement +(including California SB 243 or the UK Online Safety Act); consult qualified +counsel about your obligations. + +Edge is the open-weights build, provided as-is with no support or indemnity. For +production deployments where outputs influence outcomes for real people, a +commercial engagement (calibration, safety review, support, indemnification) and a +supported on-prem container are available — contact support@nope.net. + +_Built on Qwen3 (Apache-2.0, © Alibaba Cloud); see NOTICE.md._ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..ade004e --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,29 @@ +# MIT License + +Copyright (c) 2026 NopeNet, LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation and model files (the "Software"), +to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- + +The MIT grant above is the complete licence for NOPE Edge — free for any use, +including commercial, with no separate agreement required ("Software" = the model +weights and accompanying files). Before deploying a life-safety classifier, +please read **DISCLAIMER.md** (intended use, non-claims, and important +limitations) and **NOTICE.md** (attribution for the Qwen3 base model, which is +licensed under Apache-2.0). diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..b5d2676 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,19 @@ +# NOTICE + +This model is built on Qwen3-1.7B by Alibaba Cloud. + +## Qwen3-1.7B + +Copyright 2024-2025 Alibaba Cloud. All Rights Reserved. + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf60477 --- /dev/null +++ b/README.md @@ -0,0 +1,401 @@ +--- +license: mit +language: + - en +tags: + - safety + - crisis-detection + - text-classification + - mental-health + - content-safety + - suicide-prevention +base_model: Qwen/Qwen3-1.7B +pipeline_tag: text-generation +library_name: transformers +--- + +# NOPE Edge Mini - Crisis Classification Model + +A fine-tuned model for detecting crisis signals in text - suicidal ideation, self-harm, abuse, violence, and other safety-critical content. Features chain-of-thought reasoning that explains its classifications. + +> **License:** [MIT](LICENSE.md) - free for any use, including commercial. Built on Qwen3 (Apache-2.0); see NOTICE.md. + +--- + +## Model Variants + +| Model | Parameters | Use Case | +|-------|------------|----------| +| **[nope-edge](https://huggingface.co/nopenet/nope-edge)** | 4B | Maximum accuracy | +| **[nope-edge-mini](https://huggingface.co/nopenet/nope-edge-mini)** | 1.7B | High-volume, cost-sensitive | + +This is **nope-edge-mini (1.7B)**. + +--- + +## Quick Start + +### Requirements + +- Python 3.10+ +- GPU with 4GB+ VRAM (e.g., RTX 3060, T4, L4) - or CPU (slower) +- ~4GB disk space + +```bash +pip install torch transformers accelerate +``` + +### Usage + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer +import torch +import re + +model_id = "nopenet/nope-edge-mini" + +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained( + model_id, + torch_dtype=torch.bfloat16, + device_map="auto" +) + +def classify(message: str) -> str: + """Returns XML with reflection and risk classification. + + `message` is a single user turn. For multi-turn input, serialize the whole + exchange into this one string, e.g. "User: ...\\n\\nAI: ...\\n\\nUser: ..." — + Edge is trained on one serialized user message, not native chat roles. + """ + inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": message}], + add_generation_prompt=True, + return_dict=True, + return_tensors="pt", + ).to(model.device) + + with torch.no_grad(): + output = model.generate(**inputs, max_new_tokens=300, do_sample=False) + + return tokenizer.decode( + output[0][inputs["input_ids"].shape[1]:], + skip_special_tokens=True + ).strip() + +# Example +result = classify("I want to end it all tonight") +print(result) +``` + +**Output:** +```xml +The user directly expresses intent to end their life with a specific timeline ("tonight"), indicating acute suicidal ideation with imminent risk. + + + +``` + +--- + +## Output Format + +The model outputs XML with two components: + +### 1. Reflection (Chain-of-Thought) + +```xml +Reasoning about the input... +``` + +The model explains its classification, including: +- What signals it detected +- Why it chose the risk type and severity +- Any contextual factors considered + +### 2. Risk Classification + +**Crisis detected:** +```xml + + + +``` + +**No crisis:** +```xml + +``` + +> **"No risk" can also appear as an element.** Benign inputs usually return empty +> ``, but the model may occasionally emit an explicit non-risk element such as +> ``, or a real type with +> `severity="none"`. Treat **any element whose `type` is not one of the 9 below, or +> whose `severity="none"`, as no-risk** (drop it) — that's what NOPE's own parser does +> (see the parsing example). + +### Risk Attributes + +| Attribute | Values | Description | +|-----------|--------|-------------| +| `subject` | `self`, `other`, `unknown` | Who is at risk (defaults to `unknown` if unclear) | +| `type` | `suicide`, `self_harm`, `self_neglect`, `violence`, `abuse`, `sexual_violence`, `exploitation`, `stalking`, `neglect` | Risk category — these **9 only**; there is no `none` type | +| `severity` | `none`, `mild`, `moderate`, `high`, `critical` | Urgency level (`none` means treat as no-risk) | +| `imminence` | `not_applicable`, `chronic`, `subacute`, `urgent`, `emergency` | Time sensitivity | +| `features` | comma-separated list | **Low-confidence, free-form** indicators — see Important Limitations | + +### Subject Attribution + +| Subject | Meaning | Example | +|---------|---------|---------| +| `self` | The speaker is at risk | "I want to kill myself" | +| `other` | Reporting concern about someone else | "My friend said she wants to die" | + +### Parsing Example + +```python +import re +from dataclasses import dataclass +from typing import Optional + +@dataclass +class Risk: + subject: str + type: str + severity: str + imminence: Optional[str] = None + features: Optional[list] = None + +def parse_output(output: str) -> dict: + """Parse model output into structured data.""" + result = { + "reflection": None, + "risks": [], + "is_crisis": False + } + + # Extract reflection + reflection_match = re.search(r'(.*?)', output, re.DOTALL) + if reflection_match: + result["reflection"] = reflection_match.group(1).strip() + + # Check for empty risks (no crisis) + if '' in output or '' in output: + return result + + # Valid risk types — anything else (including a stray type="none") is dropped + VALID_TYPES = { + "suicide", "self_harm", "self_neglect", "violence", "abuse", + "sexual_violence", "neglect", "exploitation", "stalking", + } + + # Extract risk elements + risk_pattern = r']+)/?\s*>' + for match in re.finditer(risk_pattern, output): + attrs = {} + for attr_match in re.finditer(r'(\w+)="([^"]*)"', match.group(1)): + attrs[attr_match.group(1)] = attr_match.group(2) + + # Mirror NOPE's own parser: skip non-risk elements + if attrs.get("type") not in VALID_TYPES: + continue + if attrs.get("severity", "none") == "none": + continue + + result["risks"].append(Risk( + subject=attrs.get("subject", "unknown"), + type=attrs["type"], + severity=attrs["severity"], + imminence=attrs.get("imminence", "not_applicable"), + features=attrs.get("features", "").split(",") if attrs.get("features") else None, + )) + result["is_crisis"] = True + + return result + +# Usage +output = classify("I want to end it all tonight") +parsed = parse_output(output) +print(f"Crisis: {parsed['is_crisis']}") +print(f"Reasoning: {parsed['reflection']}") +for risk in parsed['risks']: + print(f"Risk: {risk.type}/{risk.severity} ({risk.subject})") +``` + +--- + +## Examples + +### Crisis Detection + +**Input:** "I want to end it all tonight" +```xml +The user directly expresses intent to end their life with a specific timeline ("tonight"), indicating acute suicidal ideation with imminent risk. + + + +``` + +**Input:** "My friend told me she's been cutting herself" +```xml +The user is reporting concern about a friend engaging in self-harm behavior. This is third-party disclosure requiring attention. + + + +``` + +### No Crisis (Correctly Ignored) + +**Input:** "kms lmao this exam is killing me" +```xml +The user is using hyperbolic internet slang ("kms" = "kill myself") to express frustration about an exam. The "lmao" and casual context indicate this is not genuine suicidal ideation. + +``` + +**Input:** "I used to be suicidal but therapy helped me recover" +```xml +The user is sharing a recovery narrative about past suicidal ideation. They explicitly state therapy helped and they have recovered. No current crisis indicators. + +``` + +--- + +## Input Best Practices + +### Text Preprocessing + +**Preserve natural prose.** The model was trained on real conversations with authentic expression: + +| Keep | Why | +|------|-----| +| Emojis | Emotional signals matter | +| Punctuation intensity | "I can't do this!!!" vs "I can't do this" | +| Slang/algospeak | "kms", "unalive", "catch the bus", "graped" | +| Casual spelling | "im so done" - don't normalize | + +**Only remove:** Zero-width Unicode, decorative fonts, excessive whitespace. + +### Multi-Turn Conversations + +Serialize into a single user message: + +```python +conversation = """User: How are you? +Assistant: I'm here to help. How are you feeling? +User: Not great. I've been thinking about ending it all.""" + +messages = [{"role": "user", "content": conversation}] +``` + +--- + +## Production Deployment + +For high-throughput use, deploy with vLLM or SGLang: + +```bash +# SGLang (recommended) +pip install sglang +python -m sglang.launch_server \ + --model nopenet/nope-edge-mini \ + --dtype bfloat16 --port 8000 + +# vLLM +pip install vllm +python -m vllm.entrypoints.openai.api_server \ + --model nopenet/nope-edge-mini \ + --dtype bfloat16 --max-model-len 2048 --port 8000 +``` + +Then call as OpenAI-compatible API: + +```bash +curl http://localhost:8000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "nopenet/nope-edge-mini", + "messages": [{"role": "user", "content": "I want to end it all"}], + "max_tokens": 300, "temperature": 0 + }' +``` + +**Health check** (server readiness): + +```bash +curl -fsS http://localhost:8000/health && echo " ready" +``` + +**Docker** (vLLM, one self-contained container): + +```bash +docker run --gpus all --restart unless-stopped -p 8000:8000 \ + vllm/vllm-openai:latest \ + --model nopenet/nope-edge-mini --dtype bfloat16 --max-model-len 2048 +``` + +The server loads the model **once** at startup, so requests don't reload weights — use this (or a small systemd unit wrapping the same command) for any real workload. Running the `classify()` snippet as a fresh process per message re-loads ~4GB of weights every time: fine for testing, not for production. + +--- + +## Model Details + +| | | +|---|---| +| **Parameters** | 1.7B | +| **Precision** | bfloat16 | +| **Base Model** | Qwen/Qwen3-1.7B | +| **Method** | LoRA fine-tune, merged to full weights | +| **License** | [MIT](LICENSE.md) | + +--- + +## Risk Types Detected + +| Type | Description | Clinical Framework | +|------|-------------|-------------------| +| `suicide` | Suicidal ideation, intent, planning | C-SSRS | +| `self_harm` | Non-suicidal self-injury (NSSI) | - | +| `self_neglect` | Eating disorders, medical neglect | - | +| `violence` | Threats/intent to harm others | HCR-20 | +| `abuse` | Domestic/intimate partner violence | DASH | +| `sexual_violence` | Rape, sexual assault, coercion | - | +| `neglect` | Failing to care for dependent | - | +| `exploitation` | Trafficking, grooming, sextortion | - | +| `stalking` | Persistent unwanted contact | SAM | + +--- + +## Important Limitations + +- Outputs are **probabilistic signals**, not clinical assessments +- **False negatives and false positives will occur** +- The `features` list is **heuristic and lower-confidence** than `type`/`severity` — it can include labels not supported by the input text. Treat it as a hint only; don't gate decisions on it. +- Never use as the **sole basis** for intervention decisions +- Always implement **human review** for flagged content +- This model is **not** a medical device or substitute for professional judgment +- Not validated for all populations, languages, or cultural contexts + +--- + +## Disclaimers, Intended Use & Non-Claims + +**Edge is a detection aid — not a predictive, diagnostic, or therapeutic tool, and not a replacement for clinical judgment.** It surfaces signals in text for a human to review; it is not a medical device, not clinically validated, and not a crisis or emergency service. False positives and false negatives will occur — some people in genuine crisis will not be identified — so never use Edge as the sole basis for an intervention decision, and always keep a human in the loop. If anyone is in immediate danger, contact your local emergency services or find resources at talk.help. + +Full disclaimer: see DISCLAIMER.md. + +--- + +## License + +NOPE Edge is **MIT-licensed** — free for any use, including commercial, with no separate agreement required. See [LICENSE.md](LICENSE.md). Built on Qwen3 (Apache-2.0); see NOTICE.md. + +--- + +## About NOPE + +NOPE provides safety infrastructure for AI applications. Our API helps developers detect mental health crises and harmful AI behavior in real-time. + +- **Website:** https://nope.net +- **Documentation:** https://docs.nope.net +- **Support:** support@nope.net + diff --git a/chat_template.jinja b/chat_template.jinja new file mode 100644 index 0000000..01be9b3 --- /dev/null +++ b/chat_template.jinja @@ -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 XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|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('') and message.content.endswith('')) %} + {%- 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 '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-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\n' + reasoning_content.strip('\n') + '\n\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 %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- 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 %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/config.json b/config.json new file mode 100644 index 0000000..a439984 --- /dev/null +++ b/config.json @@ -0,0 +1,63 @@ +{ + "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": 2048, + "initializer_range": 0.02, + "intermediate_size": 6144, + "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" + ], + "max_position_embeddings": 40960, + "max_window_layers": 28, + "model_type": "qwen3", + "num_attention_heads": 16, + "num_hidden_layers": 28, + "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.1.0", + "use_cache": true, + "use_sliding_window": false, + "vocab_size": 151936 +} diff --git a/generation_config.json b/generation_config.json new file mode 100644 index 0000000..d9d057d --- /dev/null +++ b/generation_config.json @@ -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.1.0" +} diff --git a/model.safetensors b/model.safetensors new file mode 100644 index 0000000..941a761 --- /dev/null +++ b/model.safetensors @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:156c98aa54063d7f5fcef0c61bb1940ce8fef28e7a5ccfc8f5ed94e6bafac2e6 +size 4063515640 diff --git a/tokenizer.json b/tokenizer.json new file mode 100644 index 0000000..c7afbed --- /dev/null +++ b/tokenizer.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506 +size 11422650 diff --git a/tokenizer_config.json b/tokenizer_config.json new file mode 100644 index 0000000..70bdfdf --- /dev/null +++ b/tokenizer_config.json @@ -0,0 +1,15 @@ +{ + "add_prefix_space": false, + "backend": "tokenizers", + "bos_token": null, + "clean_up_tokenization_spaces": false, + "eos_token": "<|im_end|>", + "errors": "replace", + "extra_special_tokens": {}, + "is_local": false, + "model_max_length": 131072, + "pad_token": "<|endoftext|>", + "split_special_tokens": false, + "tokenizer_class": "Qwen2Tokenizer", + "unk_token": null +} \ No newline at end of file