Text Generation
Transformers
Safetensors
PyTorch
English
Portuguese
kern_qwen3_moe
kern
sparse-moe
experimental
custom_code
conversational
Instructions to use Project-KERN/KERN-Lab-0.5-624M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Project-KERN/KERN-Lab-0.5-624M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Project-KERN/KERN-Lab-0.5-624M", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Project-KERN/KERN-Lab-0.5-624M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use Project-KERN/KERN-Lab-0.5-624M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Project-KERN/KERN-Lab-0.5-624M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Project-KERN/KERN-Lab-0.5-624M", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Project-KERN/KERN-Lab-0.5-624M
- SGLang
How to use Project-KERN/KERN-Lab-0.5-624M with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "Project-KERN/KERN-Lab-0.5-624M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Project-KERN/KERN-Lab-0.5-624M", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "Project-KERN/KERN-Lab-0.5-624M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Project-KERN/KERN-Lab-0.5-624M", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Project-KERN/KERN-Lab-0.5-624M with Docker Model Runner:
docker model run hf.co/Project-KERN/KERN-Lab-0.5-624M
Project KERN commited on
Release KERN-Lab-0.5-624M
Browse files- KERN_Colab.ipynb +119 -0
- LICENSE +202 -0
- NOTICE +17 -0
- README.md +95 -0
- TRADEMARK.md +5 -0
- app.py +64 -0
- config.json +56 -0
- generate.py +113 -0
- generation_config.json +7 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_kern_qwen06b_v1.py +355 -0
- requirements-ui.txt +2 -0
- requirements.txt +4 -0
- tokenizer.json +0 -0
- tokenizer_config.json +239 -0
- vocab.json +0 -0
KERN_Colab.ipynb
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "intro001",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# KERN-Lab-0.5-624M in Google Colab\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"Run the cells in order. A GPU runtime is optional (Runtime → Change runtime type → GPU). The model completes text prefixes. It is an experimental adaptation of Qwen3-0.6B-Base.\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"The notebook downloads approximately 1.3 GB. Review the custom model Python file in the downloaded snapshot before running the loading cell. It reconstructs the sparse layer through Transformers AutoClass."
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"id": "install01",
|
| 18 |
+
"metadata": {},
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": [],
|
| 21 |
+
"source": [
|
| 22 |
+
"%pip -q install \"torch>=2.7.0\" \"transformers==5.23.0\" \"huggingface_hub>=1.0\" \"safetensors>=0.4.0\" \"tokenizers>=0.20.0\""
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"id": "download1",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": [],
|
| 31 |
+
"source": [
|
| 32 |
+
"from pathlib import Path\n",
|
| 33 |
+
"from hashlib import file_digest\n",
|
| 34 |
+
"from huggingface_hub import snapshot_download\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"MODEL_REPO = \"VAL2409/KERN-Lab-0.5-624M\" # @param {type: \"string\"}\n",
|
| 37 |
+
"REVISION = \"\" # @param {type: \"string\"}\n",
|
| 38 |
+
"LOCAL_MODEL_DIR = \"\" # @param {type: \"string\"}\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"required = [\n",
|
| 41 |
+
" \"config.json\", \"generation_config.json\", \"model.safetensors\",\n",
|
| 42 |
+
" \"modeling_kern_qwen06b_v1.py\", \"tokenizer.json\", \"tokenizer_config.json\",\n",
|
| 43 |
+
" \"merges.txt\", \"vocab.json\",\n",
|
| 44 |
+
"]\n",
|
| 45 |
+
"if LOCAL_MODEL_DIR.strip():\n",
|
| 46 |
+
" model_dir = Path(LOCAL_MODEL_DIR).expanduser().resolve()\n",
|
| 47 |
+
"else:\n",
|
| 48 |
+
" repo_id = MODEL_REPO.strip()\n",
|
| 49 |
+
" if not repo_id or repo_id.startswith(\"__\"):\n",
|
| 50 |
+
" repo_id = input(\"Enter the official Hugging Face repository (owner/KERN-Lab-0.5-624M): \").strip()\n",
|
| 51 |
+
" model_dir = Path(snapshot_download(\n",
|
| 52 |
+
" repo_id=repo_id, revision=REVISION.strip() or None, allow_patterns=required,\n",
|
| 53 |
+
" ))\n",
|
| 54 |
+
"with (model_dir / \"model.safetensors\").open(\"rb\") as stream:\n",
|
| 55 |
+
" actual_sha256 = file_digest(stream, \"sha256\").hexdigest()\n",
|
| 56 |
+
"expected_sha256 = \"cc1ac73225ccc6013b1e73d91a6299078f7acd1b67940bf5277328dac43b0fd2\"\n",
|
| 57 |
+
"if actual_sha256 != expected_sha256:\n",
|
| 58 |
+
" raise ValueError(f\"Unexpected SafeTensors SHA-256: {actual_sha256}\")\n",
|
| 59 |
+
"print(\"Approved weights verified.\")"
|
| 60 |
+
]
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"id": "load001",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": [],
|
| 68 |
+
"source": [
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
|
| 73 |
+
"dtype = torch.bfloat16 if device == \"cuda\" and torch.cuda.is_bf16_supported() else torch.float32\n",
|
| 74 |
+
"config = AutoConfig.from_pretrained(model_dir, trust_remote_code=True, local_files_only=True)\n",
|
| 75 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_dir, config=config, local_files_only=True)\n",
|
| 76 |
+
"model = AutoModelForCausalLM.from_pretrained(\n",
|
| 77 |
+
" model_dir, config=config, trust_remote_code=True, local_files_only=True, dtype=dtype,\n",
|
| 78 |
+
").to(device).eval()\n",
|
| 79 |
+
"print(f\"Loaded {type(model).__name__} on {device} ({dtype}).\")"
|
| 80 |
+
]
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"id": "gen0001",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": [],
|
| 88 |
+
"source": [
|
| 89 |
+
"prompt = \"The capital of France is\" # @param {type: \"string\"}\n",
|
| 90 |
+
"new_tokens = 16 # @param {type: \"integer\"}\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"inputs = tokenizer(prompt, return_tensors=\"pt\", add_special_tokens=False).to(device)\n",
|
| 93 |
+
"with torch.inference_mode():\n",
|
| 94 |
+
" output = model.generate(\n",
|
| 95 |
+
" **inputs, max_new_tokens=int(new_tokens), do_sample=False, use_cache=True,\n",
|
| 96 |
+
" pad_token_id=tokenizer.pad_token_id,\n",
|
| 97 |
+
" )\n",
|
| 98 |
+
"print(prompt + tokenizer.decode(output[0, inputs[\"input_ids\"].shape[-1]:], skip_special_tokens=True))"
|
| 99 |
+
]
|
| 100 |
+
}
|
| 101 |
+
],
|
| 102 |
+
"metadata": {
|
| 103 |
+
"colab": {
|
| 104 |
+
"name": "KERN_Lab_0.5_624M.ipynb",
|
| 105 |
+
"provenance": []
|
| 106 |
+
},
|
| 107 |
+
"kernelspec": {
|
| 108 |
+
"display_name": "Python 3",
|
| 109 |
+
"language": "python",
|
| 110 |
+
"name": "python3"
|
| 111 |
+
},
|
| 112 |
+
"language_info": {
|
| 113 |
+
"name": "python"
|
| 114 |
+
},
|
| 115 |
+
"accelerator": "GPU"
|
| 116 |
+
},
|
| 117 |
+
"nbformat": 4,
|
| 118 |
+
"nbformat_minor": 5
|
| 119 |
+
}
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright 2024 Alibaba Cloud
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NOTICE — KERN-Lab-0.5-624M
|
| 2 |
+
|
| 3 |
+
Project KERN adapted Qwen/Qwen3-0.6B-Base, distributed by the Qwen team under the Apache License, Version 2.0.
|
| 4 |
+
|
| 5 |
+
Upstream model: https://huggingface.co/Qwen/Qwen3-0.6B-Base
|
| 6 |
+
Pinned revision: da87bfb608c14b7cf20ba1ce41287e8de496c0cd
|
| 7 |
+
Upstream SafeTensors SHA-256: cd2a512003e2f9f3cd3c32a9c3573f820bb28c940f73c57b1ddaa983d9223eba
|
| 8 |
+
Upstream citation: Qwen Team, Qwen3 Technical Report, https://arxiv.org/abs/2505.09388
|
| 9 |
+
|
| 10 |
+
Modifications by Project KERN: zero-based layer 14 replaces the dense SwiGLU FFN with one shared expert and three routed experts, using top-2 routing, a shared weight of 0.5 and an FP32 router. The upstream tokenizer and the remaining Transformer layers are retained. The release adds a custom loader, AutoClass entries, example clients and documentation.
|
| 11 |
+
|
| 12 |
+
Attribution for documentation and code used in the adaptation training split:
|
| 13 |
+
- FastAPI contributors, https://github.com/fastapi/fastapi (MIT, revision a1b3be01aadc)
|
| 14 |
+
- Hugging Face Transformers contributors, https://github.com/huggingface/transformers (Apache-2.0, revision c44d29d8e7e8)
|
| 15 |
+
- Flask contributors, https://github.com/pallets/flask (BSD-3-Clause, revision 49943b5a9441)
|
| 16 |
+
- Requests contributors, https://github.com/psf/requests (Apache-2.0, revision 3c7baaa05ab4)
|
| 17 |
+
- SymPy contributors, https://github.com/sympy/sympy (BSD-3-Clause, revision 91dae8140170)
|
README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
library_name: transformers
|
| 4 |
+
pipeline_tag: text-generation
|
| 5 |
+
base_model: Qwen/Qwen3-0.6B-Base
|
| 6 |
+
base_model_relation: finetune
|
| 7 |
+
language:
|
| 8 |
+
- en
|
| 9 |
+
- pt
|
| 10 |
+
tags:
|
| 11 |
+
- kern
|
| 12 |
+
- sparse-moe
|
| 13 |
+
- experimental
|
| 14 |
+
- pytorch
|
| 15 |
+
- custom_code
|
| 16 |
---
|
| 17 |
+
|
| 18 |
+
# KERN-Lab-0.5-624M
|
| 19 |
+
|
| 20 |
+
An experimental [Project KERN](https://github.com/arthurvalentimfarias/Project-KERN) adaptation for text continuation. It replaces one feed-forward block of Qwen3-0.6B-Base with a sparse mixture of experts and retains the upstream tokenizer and the rest of the pretrained backbone.
|
| 21 |
+
|
| 22 |
+
| Property | Value |
|
| 23 |
+
|---|---|
|
| 24 |
+
| Public model name | KERN-Lab-0.5-624M |
|
| 25 |
+
| Unique resident parameters | 624,364,544 |
|
| 26 |
+
| Active parameters per token (counting convention) | 614,927,360 |
|
| 27 |
+
| Transformer layers | 28 |
|
| 28 |
+
| Base / tokenizer | [Qwen3-0.6B-Base](https://huggingface.co/Qwen/Qwen3-0.6B-Base), original tokenizer |
|
| 29 |
+
| Sparse block | Zero-based layer 14, one shared expert and three routed experts, top-2 |
|
| 30 |
+
| Weight precision | BF16, with an FP32 router |
|
| 31 |
+
| Configured context | 32,768 tokens, inherited from Qwen |
|
| 32 |
+
| Adaptation | 200 optimizer steps, 203,948 useful tokens |
|
| 33 |
+
| License | Apache-2.0 |
|
| 34 |
+
|
| 35 |
+
The 624M model name uses a rounded family label. The table gives exact counts.
|
| 36 |
+
|
| 37 |
+
## Development results
|
| 38 |
+
|
| 39 |
+
Bits per UTF-8 byte (BPB), lower is better. The development samples contain 45,088 bytes (A) and 262,144 bytes (B). Set B was used to select the checkpoint.
|
| 40 |
+
|
| 41 |
+
| Model | Set A BPB | Set B BPB |
|
| 42 |
+
|---|---:|---:|
|
| 43 |
+
| Original Qwen | 0.728382 | 1.091826 |
|
| 44 |
+
| Trained dense control | 0.720180 | 1.090734 |
|
| 45 |
+
| KERN MoE seed 42 (release checkpoint) | **0.720886** | **1.088243** |
|
| 46 |
+
| KERN MoE seed 1337 | 0.720581 | 1.088777 |
|
| 47 |
+
|
| 48 |
+
The result on B is a development observation. An independent final test would be needed to establish a general quality gain. The 155 passing tests were from the project's internal engineering suite. Short generation and KV-cache checks cover their tested inputs. Long-context quality, overall reasoning gains, runtime speedups and semantic expert specialization remain unverified.
|
| 49 |
+
|
| 50 |
+
## Run the model
|
| 51 |
+
|
| 52 |
+
[Open the Google Colab notebook](https://colab.research.google.com/github/arthurvalentimfarias/Project-KERN/blob/main/KERN_Colab.ipynb) for a guided setup. For a local run, use Python 3.12 and install [PyTorch for your platform](https://pytorch.org/get-started/locally/). Choose the CUDA build to run on an NVIDIA GPU.
|
| 53 |
+
|
| 54 |
+
~~~bash
|
| 55 |
+
python -m pip install "huggingface_hub>=1.0"
|
| 56 |
+
hf download VAL2409/KERN-Lab-0.5-624M --local-dir ./model
|
| 57 |
+
python -m pip install -r model/requirements.txt
|
| 58 |
+
python model/generate.py --model-dir ./model --prompt "The capital of France is" --max-new-tokens 16 --device cpu --dtype float32
|
| 59 |
+
~~~
|
| 60 |
+
|
| 61 |
+
For GPU, change the last two options to `--device cuda --dtype bfloat16` on a BF16-capable NVIDIA GPU. Use `--dtype float32` for GPU devices without BF16 support. Treat the prompt as a text prefix for the base model.
|
| 62 |
+
|
| 63 |
+
### Transformers AutoClass
|
| 64 |
+
|
| 65 |
+
AutoClass reconstructs the sparse layer using the model repository's Python module. Review that module and set `trust_remote_code=True` for the reviewed snapshot. The example below uses the downloaded local copy. For a reproducible download, pass `--revision` with the Hub commit SHA to `hf download`.
|
| 66 |
+
|
| 67 |
+
~~~python
|
| 68 |
+
import torch
|
| 69 |
+
from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
|
| 70 |
+
|
| 71 |
+
path = "./model"
|
| 72 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 73 |
+
dtype = torch.bfloat16 if device == "cuda" and torch.cuda.is_bf16_supported() else torch.float32
|
| 74 |
+
config = AutoConfig.from_pretrained(path, trust_remote_code=True)
|
| 75 |
+
tokenizer = AutoTokenizer.from_pretrained(path, config=config, local_files_only=True)
|
| 76 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
+
path, config=config, dtype=dtype, trust_remote_code=True, local_files_only=True
|
| 78 |
+
).to(device).eval()
|
| 79 |
+
inputs = tokenizer("The capital of France is", return_tensors="pt").to(device)
|
| 80 |
+
with torch.inference_mode():
|
| 81 |
+
generated = model.generate(**inputs, max_new_tokens=16, do_sample=False, use_cache=True)
|
| 82 |
+
print(tokenizer.decode(generated[0, inputs["input_ids"].shape[-1]:], skip_special_tokens=True))
|
| 83 |
+
~~~
|
| 84 |
+
|
| 85 |
+
### Optional local web interface
|
| 86 |
+
|
| 87 |
+
~~~bash
|
| 88 |
+
python -m pip install -r model/requirements-ui.txt
|
| 89 |
+
python model/app.py --model-dir ./model --device auto
|
| 90 |
+
~~~
|
| 91 |
+
|
| 92 |
+
Open the localhost URL printed by Gradio. One text box accepts a prefix and returns its continuation.
|
| 93 |
+
|
| 94 |
+
## Scope and provenance
|
| 95 |
+
|
| 96 |
+
This is an experimental base model for text continuation. It has no instruction tuning or chat alignment. Outputs can be incorrect, repetitive, or unsafe. Review outputs before relying on them.
|
| 97 |
+
|
| 98 |
+
The pinned upstream revision is `da87bfb608c14b7cf20ba1ce41287e8de496c0cd`. The approved release weights have SHA-256 `cc1ac73225ccc6013b1e73d91a6299078f7acd1b67940bf5277328dac43b0fd2`. See [NOTICE](NOTICE) for source attribution and modifications, [LICENSE](LICENSE) for license terms, and [TRADEMARK.md](TRADEMARK.md) for guidance on the Project KERN name.
|
TRADEMARK.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Project KERN name and marks
|
| 2 |
+
|
| 3 |
+
Section 6 of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0.html#trademarks) governs the use of names and marks associated with this release. The license for the code and model weights does not grant rights in the names KERN, KERN Lab, Project KERN, or their logos, except for customary and reasonable use in describing the origin of the work and reproducing its NOTICE.
|
| 4 |
+
|
| 5 |
+
When distributing a derivative, use a name and presentation that avoid suggesting authorship, official distribution, affiliation, or endorsement by Project KERN unless the maintainers authorize that use. Factual references and required attributions remain permitted. This guidance concerns names and marks. The Apache License 2.0 governs the licensed files.
|
app.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional localhost-only Gradio interface for text continuation."""
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoTokenizer
|
| 8 |
+
|
| 9 |
+
from modeling_kern_qwen06b_v1 import load_kern_qwen06b_v1
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def build_interface(model_dir: Path, device: str):
|
| 13 |
+
import gradio as gr
|
| 14 |
+
|
| 15 |
+
dtype = torch.bfloat16 if device == "cuda" and torch.cuda.is_bf16_supported() else torch.float32
|
| 16 |
+
model, _ = load_kern_qwen06b_v1(model_dir, device=device, dtype=dtype)
|
| 17 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 18 |
+
model_dir, config=model.config, local_files_only=True, trust_remote_code=False
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
def continue_text(prompt: str, max_new_tokens: int) -> str:
|
| 22 |
+
if not prompt.strip():
|
| 23 |
+
raise gr.Error("Enter a text prefix to continue.")
|
| 24 |
+
inputs = tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
|
| 25 |
+
prompt_tokens = inputs["input_ids"].shape[-1]
|
| 26 |
+
if prompt_tokens + int(max_new_tokens) > model.config.max_position_embeddings:
|
| 27 |
+
raise gr.Error("The prompt and requested continuation exceed the configured context.")
|
| 28 |
+
with torch.inference_mode():
|
| 29 |
+
output = model.generate(
|
| 30 |
+
**inputs,
|
| 31 |
+
max_new_tokens=int(max_new_tokens),
|
| 32 |
+
do_sample=False,
|
| 33 |
+
use_cache=True,
|
| 34 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 35 |
+
)
|
| 36 |
+
return tokenizer.decode(output[0, prompt_tokens:], skip_special_tokens=True)
|
| 37 |
+
|
| 38 |
+
return gr.Interface(
|
| 39 |
+
fn=continue_text,
|
| 40 |
+
inputs=[
|
| 41 |
+
gr.Textbox(label="Text to continue", lines=4, value="A group of researchers discovered"),
|
| 42 |
+
gr.Slider(1, 256, value=48, step=1, label="New tokens"),
|
| 43 |
+
],
|
| 44 |
+
outputs=gr.Textbox(label="Continuation", lines=6),
|
| 45 |
+
title="KERN-Lab-0.5-624M",
|
| 46 |
+
description="Experimental base model for text continuation. Runs locally.",
|
| 47 |
+
api_name="generate",
|
| 48 |
+
analytics_enabled=False,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main() -> None:
|
| 53 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 54 |
+
parser.add_argument("--model-dir", type=Path, default=Path(__file__).resolve().parent)
|
| 55 |
+
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
|
| 56 |
+
options = parser.parse_args()
|
| 57 |
+
device = options.device
|
| 58 |
+
if device == "auto":
|
| 59 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 60 |
+
build_interface(options.model_dir, device).launch(server_name="127.0.0.1", share=False)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
main()
|
config.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"KernQwen3ForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "modeling_kern_qwen06b_v1.KernQwen3Config",
|
| 7 |
+
"AutoModelForCausalLM": "modeling_kern_qwen06b_v1.KernQwen3ForCausalLM"
|
| 8 |
+
},
|
| 9 |
+
"attention_bias": false,
|
| 10 |
+
"attention_dropout": 0.0,
|
| 11 |
+
"bos_token_id": 151643,
|
| 12 |
+
"eos_token_id": 151643,
|
| 13 |
+
"head_dim": 128,
|
| 14 |
+
"hidden_act": "silu",
|
| 15 |
+
"hidden_size": 1024,
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 3072,
|
| 18 |
+
"max_position_embeddings": 32768,
|
| 19 |
+
"max_window_layers": 28,
|
| 20 |
+
"model_type": "kern_qwen3_moe",
|
| 21 |
+
"num_attention_heads": 16,
|
| 22 |
+
"num_hidden_layers": 28,
|
| 23 |
+
"num_key_value_heads": 8,
|
| 24 |
+
"rms_norm_eps": 1e-06,
|
| 25 |
+
"rope_parameters": {
|
| 26 |
+
"rope_type": "default",
|
| 27 |
+
"rope_theta": 1000000
|
| 28 |
+
},
|
| 29 |
+
"sliding_window": null,
|
| 30 |
+
"tie_word_embeddings": true,
|
| 31 |
+
"torch_dtype": "bfloat16",
|
| 32 |
+
"transformers_version": "4.51.0",
|
| 33 |
+
"use_cache": true,
|
| 34 |
+
"use_sliding_window": false,
|
| 35 |
+
"vocab_size": 151936,
|
| 36 |
+
"kern_adaptation": {
|
| 37 |
+
"schema_version": "kern.v1_qwen06b_moe.v1",
|
| 38 |
+
"topology": "upcycle_moe",
|
| 39 |
+
"target_layer_idx": 14,
|
| 40 |
+
"base_model_id": "Qwen/Qwen3-0.6B-Base",
|
| 41 |
+
"base_revision": "da87bfb608c14b7cf20ba1ce41287e8de496c0cd",
|
| 42 |
+
"base_weights_sha256": "cd2a512003e2f9f3cd3c32a9c3573f820bb28c940f73c57b1ddaa983d9223eba",
|
| 43 |
+
"source_checkpoint_id": "MS03-MOE-SYMBREAK-L14-FP32MASTER_s42",
|
| 44 |
+
"upcycle_config": {
|
| 45 |
+
"target_layer_idx": 14,
|
| 46 |
+
"num_shared_experts": 1,
|
| 47 |
+
"num_routed_experts": 3,
|
| 48 |
+
"top_k": 2,
|
| 49 |
+
"shared_alpha": 0.5,
|
| 50 |
+
"renormalize_topk": true,
|
| 51 |
+
"unnormalized_scale": 1.0
|
| 52 |
+
},
|
| 53 |
+
"router_dtype": "float32",
|
| 54 |
+
"expert_dtype": "bfloat16"
|
| 55 |
+
}
|
| 56 |
+
}
|
generate.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standalone text generation CLI for KERN v1 (Qwen3-0.6B-Base Layer-14 MoE adaptation)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
import time
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import AutoTokenizer
|
| 12 |
+
|
| 13 |
+
from modeling_kern_qwen06b_v1 import KernQwen3UpcycledMoEMLP, load_kern_qwen06b_v1
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def main() -> int:
|
| 17 |
+
parser = argparse.ArgumentParser(
|
| 18 |
+
description="Generate text from KERN v1 adapted Qwen3-0.6B-Base Layer-14 MoE package."
|
| 19 |
+
)
|
| 20 |
+
parser.add_argument("--model-dir", type=Path, default=Path(__file__).resolve().parent)
|
| 21 |
+
parser.add_argument("--prompt", type=str, required=True)
|
| 22 |
+
parser.add_argument("--max-new-tokens", type=int, default=64)
|
| 23 |
+
parser.add_argument("--temperature", type=float, default=0.0)
|
| 24 |
+
parser.add_argument("--top-p", type=float, default=0.95)
|
| 25 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 26 |
+
parser.add_argument("--device", choices=("auto", "cpu", "cuda"), default="auto")
|
| 27 |
+
parser.add_argument("--dtype", choices=("bfloat16", "float32"), default="bfloat16")
|
| 28 |
+
parser.add_argument("--no-cache", action="store_true")
|
| 29 |
+
parser.add_argument("--json", action="store_true", dest="as_json")
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
dev_str = "cuda" if (args.device == "auto" and torch.cuda.is_available()) else ("cpu" if args.device == "auto" else args.device)
|
| 33 |
+
dtype = torch.bfloat16 if args.dtype == "bfloat16" else torch.float32
|
| 34 |
+
|
| 35 |
+
torch.manual_seed(int(args.seed))
|
| 36 |
+
if torch.cuda.is_available():
|
| 37 |
+
torch.cuda.manual_seed_all(int(args.seed))
|
| 38 |
+
|
| 39 |
+
model, kern_meta = load_kern_qwen06b_v1(args.model_dir, device=dev_str, dtype=dtype)
|
| 40 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 41 |
+
args.model_dir, config=model.config, local_files_only=True, trust_remote_code=False
|
| 42 |
+
)
|
| 43 |
+
dev = next(model.parameters()).device
|
| 44 |
+
|
| 45 |
+
target_layer = int(kern_meta["target_layer_idx"])
|
| 46 |
+
moe_layer = model.model.layers[target_layer].mlp
|
| 47 |
+
if isinstance(moe_layer, KernQwen3UpcycledMoEMLP):
|
| 48 |
+
moe_layer.reset_routing_stats()
|
| 49 |
+
|
| 50 |
+
enc = tokenizer(args.prompt, return_tensors="pt", add_special_tokens=False)
|
| 51 |
+
input_ids = enc["input_ids"].to(dev)
|
| 52 |
+
attention_mask = enc["attention_mask"].to(dev)
|
| 53 |
+
|
| 54 |
+
if dev.type == "cuda":
|
| 55 |
+
torch.cuda.synchronize(dev)
|
| 56 |
+
torch.cuda.reset_peak_memory_stats(dev)
|
| 57 |
+
|
| 58 |
+
gen_kwargs = {
|
| 59 |
+
"input_ids": input_ids,
|
| 60 |
+
"attention_mask": attention_mask,
|
| 61 |
+
"max_new_tokens": int(args.max_new_tokens),
|
| 62 |
+
"use_cache": (not args.no_cache),
|
| 63 |
+
"pad_token_id": tokenizer.pad_token_id if tokenizer.pad_token_id is not None else model.config.eos_token_id,
|
| 64 |
+
"eos_token_id": model.config.eos_token_id,
|
| 65 |
+
}
|
| 66 |
+
if float(args.temperature) <= 0.0:
|
| 67 |
+
gen_kwargs["do_sample"] = False
|
| 68 |
+
else:
|
| 69 |
+
gen_kwargs["do_sample"] = True
|
| 70 |
+
gen_kwargs["temperature"] = float(args.temperature)
|
| 71 |
+
gen_kwargs["top_p"] = float(args.top_p)
|
| 72 |
+
|
| 73 |
+
t0 = time.perf_counter()
|
| 74 |
+
with torch.no_grad():
|
| 75 |
+
out_ids = model.generate(**gen_kwargs)
|
| 76 |
+
if dev.type == "cuda":
|
| 77 |
+
torch.cuda.synchronize(dev)
|
| 78 |
+
peak_alloc_mib = float(torch.cuda.max_memory_allocated(dev)) / (1024.0 ** 2)
|
| 79 |
+
peak_resv_mib = float(torch.cuda.max_memory_reserved(dev)) / (1024.0 ** 2)
|
| 80 |
+
else:
|
| 81 |
+
peak_alloc_mib = 0.0
|
| 82 |
+
peak_resv_mib = 0.0
|
| 83 |
+
wall_sec = max(1e-6, time.perf_counter() - t0)
|
| 84 |
+
|
| 85 |
+
gen_tokens = out_ids[0, input_ids.shape[1] :].tolist()
|
| 86 |
+
generated_text = tokenizer.decode(gen_tokens, skip_special_tokens=True)
|
| 87 |
+
|
| 88 |
+
routing_stats = moe_layer.get_routing_stats() if isinstance(moe_layer, KernQwen3UpcycledMoEMLP) else {}
|
| 89 |
+
payload = {
|
| 90 |
+
"prompt": args.prompt,
|
| 91 |
+
"generated_text": generated_text,
|
| 92 |
+
"prompt_tokens": int(input_ids.shape[1]),
|
| 93 |
+
"generated_tokens": len(gen_tokens),
|
| 94 |
+
"tokens_per_sec": round(len(gen_tokens) / wall_sec, 2),
|
| 95 |
+
"wall_sec": round(wall_sec, 4),
|
| 96 |
+
"device": str(dev),
|
| 97 |
+
"dtype": str(dtype).replace("torch.", ""),
|
| 98 |
+
"use_cache": (not args.no_cache),
|
| 99 |
+
"peak_alloc_mib": round(peak_alloc_mib, 2),
|
| 100 |
+
"peak_reserved_mib": round(peak_resv_mib, 2),
|
| 101 |
+
"weights_tied": bool(model.model.embed_tokens.weight.data_ptr() == model.lm_head.weight.data_ptr()),
|
| 102 |
+
"router_dtype": str(moe_layer.router.weight.dtype).replace("torch.", ""),
|
| 103 |
+
"routing_stats": routing_stats,
|
| 104 |
+
}
|
| 105 |
+
if args.as_json:
|
| 106 |
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
| 107 |
+
else:
|
| 108 |
+
print(generated_text)
|
| 109 |
+
return 0
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
if __name__ == "__main__":
|
| 113 |
+
raise SystemExit(main())
|
generation_config.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token_id": 151643,
|
| 3 |
+
"do_sample": false,
|
| 4 |
+
"eos_token_id": 151643,
|
| 5 |
+
"max_new_tokens": 2048,
|
| 6 |
+
"transformers_version": "4.37.0"
|
| 7 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc1ac73225ccc6013b1e73d91a6299078f7acd1b67940bf5277328dac43b0fd2
|
| 3 |
+
size 1248772100
|
modeling_kern_qwen06b_v1.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""KERN-Lab-0.5-624M runtime for Transformers AutoClass and the standalone loader."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from safetensors.torch import load_model
|
| 14 |
+
from transformers import Qwen3Config, Qwen3ForCausalLM
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class QwenSwiGLUExpert(nn.Module):
|
| 18 |
+
"""Exact structural twin of Qwen3MLP (SwiGLU without bias)."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, hidden_size: int, intermediate_size: int, dtype: torch.dtype | None = None) -> None:
|
| 21 |
+
super().__init__()
|
| 22 |
+
factory = {"dtype": dtype} if dtype is not None else {}
|
| 23 |
+
self.hidden_size = int(hidden_size)
|
| 24 |
+
self.intermediate_size = int(intermediate_size)
|
| 25 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False, **factory)
|
| 26 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False, **factory)
|
| 27 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False, **factory)
|
| 28 |
+
|
| 29 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 30 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class FP32RouterLinear(nn.Linear):
|
| 34 |
+
"""Linear router kept strictly in torch.float32 across device moves and dtype casts."""
|
| 35 |
+
|
| 36 |
+
def __init__(self, in_features: int, out_features: int) -> None:
|
| 37 |
+
super().__init__(in_features, out_features, bias=False, dtype=torch.float32)
|
| 38 |
+
|
| 39 |
+
def _apply(self, fn, recurse: bool = True): # type: ignore[override]
|
| 40 |
+
old_weight = self.weight.detach()
|
| 41 |
+
super()._apply(fn, recurse=recurse)
|
| 42 |
+
if self.weight.dtype != torch.float32:
|
| 43 |
+
self.weight.data = old_weight.to(device=self.weight.device, dtype=torch.float32)
|
| 44 |
+
return self
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class KernQwen3UpcycledMoEMLP(nn.Module):
|
| 48 |
+
"""Inference-safe Sparse MoE block (1 shared + N routed Top-K experts) for Qwen3 Layer 14."""
|
| 49 |
+
|
| 50 |
+
def __init__(
|
| 51 |
+
self,
|
| 52 |
+
hidden_size: int,
|
| 53 |
+
intermediate_size: int,
|
| 54 |
+
*,
|
| 55 |
+
num_routed_experts: int = 3,
|
| 56 |
+
top_k: int = 2,
|
| 57 |
+
shared_alpha: float = 0.5,
|
| 58 |
+
renormalize_topk: bool = True,
|
| 59 |
+
unnormalized_scale: float = 1.0,
|
| 60 |
+
dtype: torch.dtype | None = None,
|
| 61 |
+
) -> None:
|
| 62 |
+
super().__init__()
|
| 63 |
+
self.hidden_size = int(hidden_size)
|
| 64 |
+
self.intermediate_size = int(intermediate_size)
|
| 65 |
+
self.num_routed_experts = int(num_routed_experts)
|
| 66 |
+
self.top_k = int(top_k)
|
| 67 |
+
self.shared_alpha = float(shared_alpha)
|
| 68 |
+
self.renormalize_topk = bool(renormalize_topk)
|
| 69 |
+
self.unnormalized_scale = float(unnormalized_scale)
|
| 70 |
+
|
| 71 |
+
self.shared_expert = QwenSwiGLUExpert(self.hidden_size, self.intermediate_size, dtype=dtype)
|
| 72 |
+
self.routed_experts = nn.ModuleList(
|
| 73 |
+
[
|
| 74 |
+
QwenSwiGLUExpert(self.hidden_size, self.intermediate_size, dtype=dtype)
|
| 75 |
+
for _ in range(self.num_routed_experts)
|
| 76 |
+
]
|
| 77 |
+
)
|
| 78 |
+
self.router = FP32RouterLinear(self.hidden_size, self.num_routed_experts)
|
| 79 |
+
self.register_buffer("expert_bias", torch.zeros(self.num_routed_experts, dtype=torch.float32))
|
| 80 |
+
|
| 81 |
+
# Ephemeral routing telemetry (non-persistent; supports both prefill and KV-cache decode)
|
| 82 |
+
self.register_buffer(
|
| 83 |
+
"eval_cumulative_tokens_per_expert",
|
| 84 |
+
torch.zeros(self.num_routed_experts, dtype=torch.long),
|
| 85 |
+
persistent=False,
|
| 86 |
+
)
|
| 87 |
+
self.register_buffer("eval_valid_tokens_routed", torch.zeros((), dtype=torch.long), persistent=False)
|
| 88 |
+
self.register_buffer("eval_padding_tokens_ignored", torch.zeros((), dtype=torch.long), persistent=False)
|
| 89 |
+
self.register_buffer("eval_forward_calls", torch.zeros((), dtype=torch.long), persistent=False)
|
| 90 |
+
self._active_attention_mask: torch.Tensor | None = None
|
| 91 |
+
|
| 92 |
+
def _apply(self, fn, recurse: bool = True): # type: ignore[override]
|
| 93 |
+
old_bias = self.expert_bias
|
| 94 |
+
super()._apply(fn, recurse=recurse)
|
| 95 |
+
if self.expert_bias.dtype != torch.float32:
|
| 96 |
+
self.expert_bias = old_bias.to(device=self.expert_bias.device, dtype=torch.float32)
|
| 97 |
+
return self
|
| 98 |
+
|
| 99 |
+
def reset_routing_stats(self) -> None:
|
| 100 |
+
self.eval_cumulative_tokens_per_expert.zero_()
|
| 101 |
+
self.eval_valid_tokens_routed.zero_()
|
| 102 |
+
self.eval_padding_tokens_ignored.zero_()
|
| 103 |
+
self.eval_forward_calls.zero_()
|
| 104 |
+
|
| 105 |
+
def get_routing_stats(self) -> dict[str, Any]:
|
| 106 |
+
counts = [int(x) for x in self.eval_cumulative_tokens_per_expert.detach().cpu().tolist()]
|
| 107 |
+
total_disp = sum(counts)
|
| 108 |
+
shares = [round(c / float(total_disp), 6) for c in counts] if total_disp > 0 else [0.0] * self.num_routed_experts
|
| 109 |
+
if total_disp > 0:
|
| 110 |
+
ent = float(-sum(s * math.log(s) for s in shares if s > 0.0) / math.log(self.num_routed_experts))
|
| 111 |
+
max_load = float(max(counts) / (total_disp / float(self.num_routed_experts)))
|
| 112 |
+
else:
|
| 113 |
+
ent = 0.0
|
| 114 |
+
max_load = 0.0
|
| 115 |
+
return {
|
| 116 |
+
"forward_calls": int(self.eval_forward_calls.item()),
|
| 117 |
+
"valid_tokens_routed": int(self.eval_valid_tokens_routed.item()),
|
| 118 |
+
"padding_tokens_ignored": int(self.eval_padding_tokens_ignored.item()),
|
| 119 |
+
"cumulative_tokens_per_expert": counts,
|
| 120 |
+
"expert_token_fraction": shares,
|
| 121 |
+
"cumulative_dispatch_normalized_entropy": round(ent, 6),
|
| 122 |
+
"cumulative_max_load_ratio": round(max_load, 6),
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
def _resolve_valid_mask(
|
| 126 |
+
self,
|
| 127 |
+
num_tokens: int,
|
| 128 |
+
batch_prefix_shape: tuple[int, ...],
|
| 129 |
+
device: torch.device,
|
| 130 |
+
) -> torch.Tensor | None:
|
| 131 |
+
raw_mask = self._active_attention_mask
|
| 132 |
+
if raw_mask is None:
|
| 133 |
+
return None
|
| 134 |
+
if tuple(raw_mask.shape) == batch_prefix_shape:
|
| 135 |
+
return raw_mask.reshape(-1).to(device=device) > 0
|
| 136 |
+
if int(raw_mask.numel()) == num_tokens:
|
| 137 |
+
return raw_mask.reshape(-1).to(device=device) > 0
|
| 138 |
+
if (
|
| 139 |
+
raw_mask.ndim == 2
|
| 140 |
+
and len(batch_prefix_shape) == 2
|
| 141 |
+
and raw_mask.shape[0] == batch_prefix_shape[0]
|
| 142 |
+
and raw_mask.shape[1] >= batch_prefix_shape[1]
|
| 143 |
+
):
|
| 144 |
+
return raw_mask[:, -batch_prefix_shape[1] :].reshape(-1).to(device=device) > 0
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 148 |
+
orig_shape = x.shape
|
| 149 |
+
x_flat = x.reshape(-1, self.hidden_size)
|
| 150 |
+
num_tokens = x_flat.shape[0]
|
| 151 |
+
valid_mask = self._resolve_valid_mask(num_tokens, tuple(orig_shape[:-1]), x.device)
|
| 152 |
+
|
| 153 |
+
shared_out = self.shared_expert(x_flat)
|
| 154 |
+
|
| 155 |
+
with torch.amp.autocast(device_type=x.device.type if x.device.type in ("cuda", "cpu") else "cpu", enabled=False):
|
| 156 |
+
router_logits = F.linear(x_flat.float(), self.router.weight.float()) + self.expert_bias.float()
|
| 157 |
+
probs_full = torch.softmax(router_logits, dim=-1)
|
| 158 |
+
topk_vals, topk_idx = torch.topk(probs_full, k=self.top_k, dim=-1)
|
| 159 |
+
if self.renormalize_topk:
|
| 160 |
+
topk_weights = topk_vals / topk_vals.sum(dim=-1, keepdim=True).clamp_min(1e-12)
|
| 161 |
+
else:
|
| 162 |
+
topk_weights = topk_vals * self.unnormalized_scale
|
| 163 |
+
|
| 164 |
+
routed_out = torch.zeros_like(x_flat, dtype=torch.float32)
|
| 165 |
+
for e_idx in range(self.num_routed_experts):
|
| 166 |
+
mask = topk_idx == e_idx
|
| 167 |
+
if not mask.any():
|
| 168 |
+
continue
|
| 169 |
+
token_pos, k_pos = torch.nonzero(mask, as_tuple=True)
|
| 170 |
+
selected_x = x_flat.index_select(0, token_pos)
|
| 171 |
+
exp_y = self.routed_experts[e_idx](selected_x).float()
|
| 172 |
+
w = topk_weights[token_pos, k_pos].unsqueeze(-1)
|
| 173 |
+
routed_out.index_add_(0, token_pos, exp_y * w)
|
| 174 |
+
|
| 175 |
+
out = (self.shared_alpha * shared_out.float() + (1.0 - self.shared_alpha) * routed_out).to(dtype=x.dtype)
|
| 176 |
+
|
| 177 |
+
with torch.no_grad():
|
| 178 |
+
if valid_mask is not None:
|
| 179 |
+
topk_valid = topk_idx[valid_mask]
|
| 180 |
+
n_valid = int(valid_mask.sum().item())
|
| 181 |
+
n_pad = int(num_tokens - n_valid)
|
| 182 |
+
else:
|
| 183 |
+
topk_valid = topk_idx
|
| 184 |
+
n_valid = int(num_tokens)
|
| 185 |
+
n_pad = 0
|
| 186 |
+
if n_valid > 0:
|
| 187 |
+
counts = torch.bincount(topk_valid.reshape(-1), minlength=self.num_routed_experts).to(dtype=torch.long)
|
| 188 |
+
else:
|
| 189 |
+
counts = torch.zeros(self.num_routed_experts, dtype=torch.long, device=x.device)
|
| 190 |
+
self.eval_cumulative_tokens_per_expert.add_(counts)
|
| 191 |
+
self.eval_valid_tokens_routed.add_(n_valid)
|
| 192 |
+
self.eval_padding_tokens_ignored.add_(n_pad)
|
| 193 |
+
self.eval_forward_calls.add_(1)
|
| 194 |
+
|
| 195 |
+
return out.reshape(orig_shape)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _attach_mask_hooks(model: nn.Module) -> None:
|
| 199 |
+
if getattr(model, "_kern_moe_mask_hook_handles", None):
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
def _pre_hook(mod: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
| 203 |
+
attn = kwargs.get("attention_mask")
|
| 204 |
+
if attn is None and len(args) >= 2 and isinstance(args[1], torch.Tensor):
|
| 205 |
+
attn = args[1]
|
| 206 |
+
active = attn if isinstance(attn, torch.Tensor) else None
|
| 207 |
+
for child in mod.modules():
|
| 208 |
+
if isinstance(child, KernQwen3UpcycledMoEMLP):
|
| 209 |
+
child._active_attention_mask = active
|
| 210 |
+
|
| 211 |
+
def _post_hook(mod: nn.Module, _args: tuple[Any, ...], _out: Any) -> None:
|
| 212 |
+
for child in mod.modules():
|
| 213 |
+
if isinstance(child, KernQwen3UpcycledMoEMLP):
|
| 214 |
+
child._active_attention_mask = None
|
| 215 |
+
|
| 216 |
+
h_pre = model.register_forward_pre_hook(_pre_hook, with_kwargs=True)
|
| 217 |
+
h_post = model.register_forward_hook(_post_hook)
|
| 218 |
+
model._kern_moe_mask_hook_handles = (h_pre, h_post)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _install_moe(model: Qwen3ForCausalLM, meta: dict[str, Any], dtype: torch.dtype) -> None:
|
| 222 |
+
upcycle = meta["upcycle_config"]
|
| 223 |
+
layer = int(meta["target_layer_idx"])
|
| 224 |
+
if meta.get("topology") != "upcycle_moe" or int(upcycle["num_shared_experts"]) != 1:
|
| 225 |
+
raise ValueError("Expected the KERN sparse MoE topology with one shared expert")
|
| 226 |
+
if not 0 <= layer < len(model.model.layers) or int(upcycle["target_layer_idx"]) != layer:
|
| 227 |
+
raise ValueError("Invalid or inconsistent KERN layer index")
|
| 228 |
+
config = model.config
|
| 229 |
+
model.model.layers[layer].mlp = KernQwen3UpcycledMoEMLP(
|
| 230 |
+
config.hidden_size,
|
| 231 |
+
config.intermediate_size,
|
| 232 |
+
num_routed_experts=int(upcycle["num_routed_experts"]),
|
| 233 |
+
top_k=int(upcycle["top_k"]),
|
| 234 |
+
shared_alpha=float(upcycle["shared_alpha"]),
|
| 235 |
+
renormalize_topk=bool(upcycle["renormalize_topk"]),
|
| 236 |
+
unnormalized_scale=float(upcycle.get("unnormalized_scale", 1.0)),
|
| 237 |
+
dtype=dtype,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class KernQwen3Config(Qwen3Config):
|
| 242 |
+
"""Qwen3 configuration with a distinct AutoConfig identity for KERN."""
|
| 243 |
+
|
| 244 |
+
model_type = "kern_qwen3_moe"
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class KernQwen3ForCausalLM(Qwen3ForCausalLM):
|
| 248 |
+
"""Qwen3 with the KERN FFN installed before Transformers loads SafeTensors."""
|
| 249 |
+
|
| 250 |
+
config_class = KernQwen3Config
|
| 251 |
+
_keep_in_fp32_modules_strict = ["router", "expert_bias"]
|
| 252 |
+
|
| 253 |
+
def __init__(self, config: KernQwen3Config) -> None:
|
| 254 |
+
super().__init__(config)
|
| 255 |
+
_install_moe(self, config.kern_adaptation, self.model.embed_tokens.weight.dtype)
|
| 256 |
+
_attach_mask_hooks(self)
|
| 257 |
+
|
| 258 |
+
@classmethod
|
| 259 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 260 |
+
output_loading_info = kwargs.pop("output_loading_info", False)
|
| 261 |
+
model, loading_info = super().from_pretrained(
|
| 262 |
+
pretrained_model_name_or_path, *model_args, output_loading_info=True, **kwargs
|
| 263 |
+
)
|
| 264 |
+
problems = {
|
| 265 |
+
key: loading_info[key]
|
| 266 |
+
for key in ("missing_keys", "unexpected_keys", "mismatched_keys", "error_msgs")
|
| 267 |
+
if loading_info.get(key)
|
| 268 |
+
}
|
| 269 |
+
if problems:
|
| 270 |
+
raise RuntimeError(f"KERN checkpoint did not load exactly: {problems}")
|
| 271 |
+
moe = model.model.layers[int(model.config.kern_adaptation["target_layer_idx"])].mlp
|
| 272 |
+
if moe.router.weight.dtype != torch.float32 or moe.expert_bias.dtype != torch.float32:
|
| 273 |
+
raise RuntimeError("KERN requires FP32 routing tensors")
|
| 274 |
+
if model.model.embed_tokens.weight is not model.lm_head.weight:
|
| 275 |
+
raise RuntimeError("KERN expects tied input embeddings and LM head")
|
| 276 |
+
moe.reset_routing_stats()
|
| 277 |
+
return (model, loading_info) if output_loading_info else model
|
| 278 |
+
|
| 279 |
+
def _apply(self, fn, recurse: bool = True): # type: ignore[override]
|
| 280 |
+
rotary = self.model.rotary_emb
|
| 281 |
+
old_freq = rotary.inv_freq
|
| 282 |
+
old_original = rotary.original_inv_freq
|
| 283 |
+
super()._apply(fn, recurse=recurse)
|
| 284 |
+
if rotary.inv_freq.dtype != torch.float32:
|
| 285 |
+
rotary.inv_freq = old_freq.to(device=rotary.inv_freq.device, dtype=torch.float32)
|
| 286 |
+
if rotary.original_inv_freq.dtype != torch.float32:
|
| 287 |
+
rotary.original_inv_freq = old_original.to(device=rotary.original_inv_freq.device, dtype=torch.float32)
|
| 288 |
+
return self
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def load_kern_qwen06b_v1(
|
| 292 |
+
model_dir: str | Path,
|
| 293 |
+
*,
|
| 294 |
+
device: str | torch.device = "auto",
|
| 295 |
+
dtype: torch.dtype = torch.bfloat16,
|
| 296 |
+
) -> tuple[Qwen3ForCausalLM, dict[str, Any]]:
|
| 297 |
+
"""Load standalone KERN v1 adapted Qwen3-0.6B MoE weights preserving tying, FP32 router, and FP32 RoPE."""
|
| 298 |
+
base = Path(model_dir)
|
| 299 |
+
cfg_raw = json.loads((base / "config.json").read_text(encoding="utf-8"))
|
| 300 |
+
kern_meta = dict(cfg_raw.get("kern_adaptation", {}))
|
| 301 |
+
if kern_meta.get("topology") != "upcycle_moe":
|
| 302 |
+
raise ValueError(f"Expected kern_adaptation.topology == 'upcycle_moe', got {kern_meta.get('topology')!r}")
|
| 303 |
+
|
| 304 |
+
if isinstance(device, str) and device == "auto":
|
| 305 |
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 306 |
+
else:
|
| 307 |
+
dev = torch.device(device)
|
| 308 |
+
if dev.type == "cuda" and not torch.cuda.is_available():
|
| 309 |
+
raise RuntimeError("CUDA requested but torch.cuda.is_available() is False")
|
| 310 |
+
|
| 311 |
+
qwen_cfg = Qwen3Config.from_dict({**cfg_raw, "model_type": "qwen3"})
|
| 312 |
+
# Build on CPU first so non-persistent RoPE inv_freq stays exact float32
|
| 313 |
+
model = Qwen3ForCausalLM(qwen_cfg)
|
| 314 |
+
rotary = model.model.rotary_emb
|
| 315 |
+
inv_freq_f32 = rotary.inv_freq.detach().clone().to(dtype=torch.float32)
|
| 316 |
+
orig_inv_f32 = (
|
| 317 |
+
rotary.original_inv_freq.detach().clone().to(dtype=torch.float32)
|
| 318 |
+
if hasattr(rotary, "original_inv_freq")
|
| 319 |
+
else None
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
target_layer = int(kern_meta["target_layer_idx"])
|
| 323 |
+
up_cfg = dict(kern_meta["upcycle_config"])
|
| 324 |
+
_install_moe(model, kern_meta, torch.float32)
|
| 325 |
+
model = model.to(dtype=dtype)
|
| 326 |
+
|
| 327 |
+
# Restore exact float32 RoPE buffers before loading weights & moving to target device
|
| 328 |
+
rotary.inv_freq = inv_freq_f32
|
| 329 |
+
if orig_inv_f32 is not None:
|
| 330 |
+
rotary.original_inv_freq = orig_inv_f32
|
| 331 |
+
|
| 332 |
+
load_model(model, str(base / "model.safetensors"), strict=True)
|
| 333 |
+
model = model.to(device=dev)
|
| 334 |
+
rotary.inv_freq = inv_freq_f32.to(device=dev, dtype=torch.float32)
|
| 335 |
+
if orig_inv_f32 is not None:
|
| 336 |
+
rotary.original_inv_freq = orig_inv_f32.to(device=dev, dtype=torch.float32)
|
| 337 |
+
|
| 338 |
+
if qwen_cfg.tie_word_embeddings:
|
| 339 |
+
model.lm_head.weight = model.model.embed_tokens.weight
|
| 340 |
+
if model.model.embed_tokens.weight.data_ptr() != model.lm_head.weight.data_ptr():
|
| 341 |
+
raise RuntimeError("Failed to preserve tied embed_tokens/lm_head pointer after load_model")
|
| 342 |
+
|
| 343 |
+
loaded_mlp = model.model.layers[target_layer].mlp
|
| 344 |
+
if not isinstance(loaded_mlp, KernQwen3UpcycledMoEMLP):
|
| 345 |
+
raise RuntimeError(f"Layer {target_layer} mlp was not reconstructed as KernQwen3UpcycledMoEMLP")
|
| 346 |
+
if loaded_mlp.router.weight.dtype != torch.float32:
|
| 347 |
+
raise RuntimeError(f"Router weight drifted to {loaded_mlp.router.weight.dtype}, expected torch.float32")
|
| 348 |
+
if loaded_mlp.expert_bias.dtype != torch.float32:
|
| 349 |
+
raise RuntimeError(f"expert_bias drifted to {loaded_mlp.expert_bias.dtype}, expected torch.float32")
|
| 350 |
+
if len(loaded_mlp.routed_experts) != int(up_cfg["num_routed_experts"]):
|
| 351 |
+
raise RuntimeError("Missing routed_experts in reconstructed MoE block")
|
| 352 |
+
|
| 353 |
+
_attach_mask_hooks(model)
|
| 354 |
+
model.eval()
|
| 355 |
+
return model, kern_meta
|
requirements-ui.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements.txt
|
| 2 |
+
gradio>=5,<7
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.7.0
|
| 2 |
+
transformers>=5.23.0,<5.24.0
|
| 3 |
+
safetensors>=0.4.0
|
| 4 |
+
tokenizers>=0.20.0
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<tool_response>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": false
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "</tool_response>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": false
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<think>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": false
|
| 204 |
+
},
|
| 205 |
+
"151668": {
|
| 206 |
+
"content": "</think>",
|
| 207 |
+
"lstrip": false,
|
| 208 |
+
"normalized": false,
|
| 209 |
+
"rstrip": false,
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"special": false
|
| 212 |
+
}
|
| 213 |
+
},
|
| 214 |
+
"additional_special_tokens": [
|
| 215 |
+
"<|im_start|>",
|
| 216 |
+
"<|im_end|>",
|
| 217 |
+
"<|object_ref_start|>",
|
| 218 |
+
"<|object_ref_end|>",
|
| 219 |
+
"<|box_start|>",
|
| 220 |
+
"<|box_end|>",
|
| 221 |
+
"<|quad_start|>",
|
| 222 |
+
"<|quad_end|>",
|
| 223 |
+
"<|vision_start|>",
|
| 224 |
+
"<|vision_end|>",
|
| 225 |
+
"<|vision_pad|>",
|
| 226 |
+
"<|image_pad|>",
|
| 227 |
+
"<|video_pad|>"
|
| 228 |
+
],
|
| 229 |
+
"bos_token": null,
|
| 230 |
+
"chat_template": "{%- if tools %}\n {{- '<|im_start|>system\\n' }}\n {%- if messages[0].role == 'system' %}\n {{- messages[0].content + '\\n\\n' }}\n {%- endif %}\n {{- \"# 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>\" }}\n {%- for tool in tools %}\n {{- \"\\n\" }}\n {{- tool | tojson }}\n {%- endfor %}\n {{- \"\\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\" }}\n{%- else %}\n {%- if messages[0].role == 'system' %}\n {{- '<|im_start|>system\\n' + messages[0].content + '<|im_end|>\\n' }}\n {%- endif %}\n{%- endif %}\n{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}\n{%- for message in messages[::-1] %}\n {%- set index = (messages|length - 1) - loop.index0 %}\n {%- if ns.multi_step_tool and message.role == \"user\" and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}\n {%- set ns.multi_step_tool = false %}\n {%- set ns.last_query_index = index %}\n {%- endif %}\n{%- endfor %}\n{%- for message in messages %}\n {%- if (message.role == \"user\") or (message.role == \"system\" and not loop.first) %}\n {{- '<|im_start|>' + message.role + '\\n' + message.content + '<|im_end|>' + '\\n' }}\n {%- elif message.role == \"assistant\" %}\n {%- set content = message.content %}\n {%- set reasoning_content = '' %}\n {%- if message.reasoning_content is defined and message.reasoning_content is not none %}\n {%- set reasoning_content = message.reasoning_content %}\n {%- else %}\n {%- if '</think>' in message.content %}\n {%- set content = message.content.split('</think>')[-1].lstrip('\\n') %}\n {%- set reasoning_content = message.content.split('</think>')[0].rstrip('\\n').split('<think>')[-1].lstrip('\\n') %}\n {%- endif %}\n {%- endif %}\n {%- if loop.index0 > ns.last_query_index %}\n {%- if loop.last or (not loop.last and reasoning_content) %}\n {{- '<|im_start|>' + message.role + '\\n<think>\\n' + reasoning_content.strip('\\n') + '\\n</think>\\n\\n' + content.lstrip('\\n') }}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- else %}\n {{- '<|im_start|>' + message.role + '\\n' + content }}\n {%- endif %}\n {%- if message.tool_calls %}\n {%- for tool_call in message.tool_calls %}\n {%- if (loop.first and content) or (not loop.first) %}\n {{- '\\n' }}\n {%- endif %}\n {%- if tool_call.function %}\n {%- set tool_call = tool_call.function %}\n {%- endif %}\n {{- '<tool_call>\\n{\"name\": \"' }}\n {{- tool_call.name }}\n {{- '\", \"arguments\": ' }}\n {%- if tool_call.arguments is string %}\n {{- tool_call.arguments }}\n {%- else %}\n {{- tool_call.arguments | tojson }}\n {%- endif %}\n {{- '}\\n</tool_call>' }}\n {%- endfor %}\n {%- endif %}\n {{- '<|im_end|>\\n' }}\n {%- elif message.role == \"tool\" %}\n {%- if loop.first or (messages[loop.index0 - 1].role != \"tool\") %}\n {{- '<|im_start|>user' }}\n {%- endif %}\n {{- '\\n<tool_response>\\n' }}\n {{- message.content }}\n {{- '\\n</tool_response>' }}\n {%- if loop.last or (messages[loop.index0 + 1].role != \"tool\") %}\n {{- '<|im_end|>\\n' }}\n {%- endif %}\n {%- endif %}\n{%- endfor %}\n{%- if add_generation_prompt %}\n {{- '<|im_start|>assistant\\n' }}\n {%- if enable_thinking is defined and enable_thinking is false %}\n {{- '<think>\\n\\n</think>\\n\\n' }}\n {%- endif %}\n{%- endif %}",
|
| 231 |
+
"clean_up_tokenization_spaces": false,
|
| 232 |
+
"eos_token": "<|endoftext|>",
|
| 233 |
+
"errors": "replace",
|
| 234 |
+
"model_max_length": 131072,
|
| 235 |
+
"pad_token": "<|endoftext|>",
|
| 236 |
+
"split_special_tokens": false,
|
| 237 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 238 |
+
"unk_token": null
|
| 239 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|