Image-Text-to-Text
Transformers
Safetensors
modilify_mk1
text-generation
diffusion
multimodal
mixture-of-experts
trust-remote-code
conversational
custom_code
Instructions to use modilify/Modilify-Mk1-preview with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use modilify/Modilify-Mk1-preview with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="modilify/Modilify-Mk1-preview", trust_remote_code=True) messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("modilify/Modilify-Mk1-preview", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use modilify/Modilify-Mk1-preview with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "modilify/Modilify-Mk1-preview" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "modilify/Modilify-Mk1-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/modilify/Modilify-Mk1-preview
- SGLang
How to use modilify/Modilify-Mk1-preview 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 "modilify/Modilify-Mk1-preview" \ --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": "modilify/Modilify-Mk1-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'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 "modilify/Modilify-Mk1-preview" \ --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": "modilify/Modilify-Mk1-preview", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use modilify/Modilify-Mk1-preview with Docker Model Runner:
docker model run hf.co/modilify/Modilify-Mk1-preview
Publish Modilify Mk1 Preview
Browse files- .gitattributes +2 -34
- LICENSE +129 -0
- NOTICE.md +263 -0
- README.md +239 -0
- assets/01-LOGO.jpg +3 -0
- chat_template.jinja +387 -0
- commit_policy.py +287 -0
- config.json +156 -0
- configuration_modilify_mk1.py +168 -0
- generation_config.json +18 -0
- generation_modilify_mk1.py +782 -0
- latent_deliberation.py +401 -0
- model-00001-of-00011.safetensors +3 -0
- model-00002-of-00011.safetensors +3 -0
- model-00003-of-00011.safetensors +3 -0
- model-00004-of-00011.safetensors +3 -0
- model-00005-of-00011.safetensors +3 -0
- model-00006-of-00011.safetensors +3 -0
- model-00007-of-00011.safetensors +3 -0
- model-00008-of-00011.safetensors +3 -0
- model-00009-of-00011.safetensors +3 -0
- model-00010-of-00011.safetensors +3 -0
- model-00011-of-00011.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_modilify_mk1.py +473 -0
- modilify_mk1/__init__.py +25 -0
- modilify_mk1/commit_policy.py +287 -0
- modilify_mk1/configuration_modilify_mk1.py +168 -0
- modilify_mk1/generation_modilify_mk1.py +782 -0
- modilify_mk1/latent_deliberation.py +401 -0
- modilify_mk1/modeling_modilify_mk1.py +473 -0
- processor_config.json +75 -0
- tokenizer.json +3 -0
- tokenizer_config.json +96 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,3 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
assets/01-LOGO.jpg filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
LICENSE
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Modilify Open Model License 1.0
|
| 2 |
+
Draft for Independent Legal Review
|
| 3 |
+
|
| 4 |
+
Copyright 2026 Modilify
|
| 5 |
+
|
| 6 |
+
1. Definitions
|
| 7 |
+
|
| 8 |
+
"Model" means the weights, configuration, inference code, tokenizer, processor,
|
| 9 |
+
and documentation distributed with this license. "Derivative Model" means a
|
| 10 |
+
modified, fine-tuned, distilled, merged, quantized, or otherwise adapted version
|
| 11 |
+
of the Model. "You" means the individual or legal entity exercising permissions
|
| 12 |
+
under this license. "High-Risk Use" means a use that can materially affect a
|
| 13 |
+
person's safety, liberty, access to essential services, employment, housing,
|
| 14 |
+
credit, education, legal rights, or medical care, or that controls critical
|
| 15 |
+
infrastructure, weapons, or large-scale biometric surveillance.
|
| 16 |
+
|
| 17 |
+
2. Copyright Grant
|
| 18 |
+
|
| 19 |
+
Subject to this license, Modilify grants You a worldwide, perpetual,
|
| 20 |
+
non-exclusive, royalty-free, irrevocable copyright license to use, reproduce,
|
| 21 |
+
prepare derivative works of, publicly display, publicly perform, sublicense,
|
| 22 |
+
host as a service, and distribute the Model and Derivative Models, including for
|
| 23 |
+
commercial purposes.
|
| 24 |
+
|
| 25 |
+
3. Patent Grant
|
| 26 |
+
|
| 27 |
+
Each contributor grants You a worldwide, perpetual, non-exclusive, royalty-free,
|
| 28 |
+
irrevocable patent license, except as stated in this section, to make, have made,
|
| 29 |
+
use, offer to sell, sell, import, and otherwise transfer the Model where the
|
| 30 |
+
license applies only to patent claims necessarily infringed by that contributor's
|
| 31 |
+
contribution alone or in combination with the Model. If You institute patent
|
| 32 |
+
litigation alleging that the Model or a contribution constitutes patent
|
| 33 |
+
infringement, patent licenses granted to You under this license terminate as of
|
| 34 |
+
the filing date.
|
| 35 |
+
|
| 36 |
+
4. Conditions on Redistribution
|
| 37 |
+
|
| 38 |
+
If You distribute the Model or a Derivative Model, You must:
|
| 39 |
+
|
| 40 |
+
a. provide recipients a copy of this license;
|
| 41 |
+
b. retain copyright, patent, attribution, and NOTICE statements;
|
| 42 |
+
c. state clearly that You modified the Model and identify material modifications;
|
| 43 |
+
d. preserve applicable third-party license and attribution notices; and
|
| 44 |
+
e. publish with the distributed model a reasonably accessible impact statement
|
| 45 |
+
describing intended uses, material limitations, evaluation scope, known
|
| 46 |
+
safety risks, and risk mitigations for the Derivative Model.
|
| 47 |
+
|
| 48 |
+
The impact statement may be maintained in a public model card or equivalent
|
| 49 |
+
document. You are not required to submit it separately to Modilify.
|
| 50 |
+
|
| 51 |
+
5. Responsible Use and High-Risk Uses
|
| 52 |
+
|
| 53 |
+
You must not use the Model or a Derivative Model:
|
| 54 |
+
|
| 55 |
+
a. to develop, operate, or materially facilitate weapons, autonomous targeting,
|
| 56 |
+
or systems intended to cause physical harm;
|
| 57 |
+
b. for unlawful mass surveillance, biometric identification without lawful
|
| 58 |
+
authority and appropriate safeguards, or social scoring that determines
|
| 59 |
+
access to rights or essential services;
|
| 60 |
+
c. to exploit children or vulnerable persons, facilitate human trafficking, or
|
| 61 |
+
generate non-consensual intimate content;
|
| 62 |
+
d. to impersonate a person or deceptively represent machine output as an
|
| 63 |
+
authentic human communication where the deception is reasonably likely to
|
| 64 |
+
cause material harm; or
|
| 65 |
+
e. to make a final decision in a High-Risk Use without meaningful qualified
|
| 66 |
+
human review, proportionate testing, monitoring, appeal or correction paths,
|
| 67 |
+
and compliance with applicable law.
|
| 68 |
+
|
| 69 |
+
Before deploying the Model in a High-Risk Use, You must perform safety and impact
|
| 70 |
+
due diligence proportionate to foreseeable harm. At minimum, document the use
|
| 71 |
+
context, evaluate relevant failure modes and affected groups, apply reasonable
|
| 72 |
+
technical and organizational safeguards, monitor material incidents, and update
|
| 73 |
+
or suspend the deployment when its residual risk is not reasonable. Research,
|
| 74 |
+
testing, auditing, and defensive safety work are permitted when conducted with
|
| 75 |
+
appropriate safeguards.
|
| 76 |
+
|
| 77 |
+
6. Trademarks
|
| 78 |
+
|
| 79 |
+
This license does not grant permission to use the trade names, trademarks,
|
| 80 |
+
service marks, or product names of Modilify or any contributor, except as needed
|
| 81 |
+
for reasonable and customary attribution or to describe the origin of the Model.
|
| 82 |
+
|
| 83 |
+
7. Third-Party Components
|
| 84 |
+
|
| 85 |
+
The Model includes or derives from third-party components identified in
|
| 86 |
+
NOTICE.md. Those components remain subject to their applicable
|
| 87 |
+
licenses and terms. In particular, rights and obligations associated with the
|
| 88 |
+
Google DiffusionGemma base are not removed, narrowed, or replaced by this
|
| 89 |
+
license. You are responsible for complying with all applicable upstream terms.
|
| 90 |
+
|
| 91 |
+
8. Termination and Reinstatement
|
| 92 |
+
|
| 93 |
+
Your rights terminate automatically if You materially violate this license and
|
| 94 |
+
do not cure the violation within 30 days after becoming aware of it. Rights are
|
| 95 |
+
reinstated upon timely cure unless a rights holder provides written notice of a
|
| 96 |
+
substantially similar repeated violation. Sections intended by their nature to
|
| 97 |
+
survive termination remain effective.
|
| 98 |
+
|
| 99 |
+
9. Disclaimer of Warranty
|
| 100 |
+
|
| 101 |
+
THE MODEL IS PROVIDED "AS IS," WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
|
| 102 |
+
EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF TITLE, NON-INFRINGEMENT,
|
| 103 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, ACCURACY, OR SAFETY. YOU ARE
|
| 104 |
+
SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING
|
| 105 |
+
THE MODEL AND ASSUME ALL RISKS ASSOCIATED WITH YOUR EXERCISE OF PERMISSIONS.
|
| 106 |
+
|
| 107 |
+
10. Limitation of Liability
|
| 108 |
+
|
| 109 |
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR SHALL
|
| 110 |
+
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
| 111 |
+
CONSEQUENTIAL DAMAGES ARISING FROM THIS LICENSE OR THE USE OR INABILITY TO USE
|
| 112 |
+
THE MODEL, HOWEVER CAUSED AND UNDER ANY THEORY OF LIABILITY, EVEN IF ADVISED OF
|
| 113 |
+
THE POSSIBILITY OF SUCH DAMAGES.
|
| 114 |
+
|
| 115 |
+
11. Governing Law and Venue
|
| 116 |
+
|
| 117 |
+
This license is governed by the laws of the State of California, excluding its
|
| 118 |
+
conflict-of-law rules. Any dispute arising from this license must be brought in
|
| 119 |
+
the state or federal courts located in Santa Clara County, California, and each
|
| 120 |
+
party consents to their personal jurisdiction and venue.
|
| 121 |
+
|
| 122 |
+
12. Entire License; Severability
|
| 123 |
+
|
| 124 |
+
This document states the complete Modilify license for the Model, subject to
|
| 125 |
+
applicable third-party terms. If a provision is unenforceable, it will be limited
|
| 126 |
+
to the minimum extent necessary and the remaining provisions remain effective.
|
| 127 |
+
|
| 128 |
+
This is a pre-release license draft. Obtain independent legal review before
|
| 129 |
+
public distribution or production reliance.
|
NOTICE.md
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modilify Mk1 Preview — Notices
|
| 2 |
+
|
| 3 |
+
Copyright 2026 Modilify
|
| 4 |
+
|
| 5 |
+
This distribution is derived from `google/diffusiongemma-26B-A4B-it`, published
|
| 6 |
+
by Google DeepMind under Apache License 2.0. It retains the upstream multimodal
|
| 7 |
+
encoder, vision tower, vision projection, tokenizer, processor assets, and base
|
| 8 |
+
language-model parameters. Modilify merged the step-680 low-rank updates and
|
| 9 |
+
added recurrent latent deliberation plus a multiplicative
|
| 10 |
+
confidence-and-entropy commit policy.
|
| 11 |
+
|
| 12 |
+
The Modilify Open Model License 1.0 applies to Modilify's distribution and
|
| 13 |
+
original contributions. It does not erase, narrow, or replace rights and notices
|
| 14 |
+
applicable to upstream components. Users remain responsible for complying with
|
| 15 |
+
all applicable upstream terms.
|
| 16 |
+
|
| 17 |
+
- Upstream model: https://huggingface.co/google/diffusiongemma-26B-A4B-it
|
| 18 |
+
- Transformers project: https://github.com/huggingface/transformers
|
| 19 |
+
|
| 20 |
+
The remote model implementation subclasses public DiffusionGemma interfaces in
|
| 21 |
+
Hugging Face Transformers, which is also distributed under Apache License 2.0.
|
| 22 |
+
|
| 23 |
+
## Derivative Model Impact Statement Template
|
| 24 |
+
|
| 25 |
+
When distributing a derivative of Modilify Mk1, include a public impact
|
| 26 |
+
statement covering the following items. No separate submission to Modilify is
|
| 27 |
+
required.
|
| 28 |
+
|
| 29 |
+
### Identity and modifications
|
| 30 |
+
|
| 31 |
+
- Model name, version, publisher, and contact.
|
| 32 |
+
- Base version.
|
| 33 |
+
- Material modifications, data sources, merges, quantization, or adaptation.
|
| 34 |
+
|
| 35 |
+
### Intended and excluded uses
|
| 36 |
+
|
| 37 |
+
- Intended users and use cases.
|
| 38 |
+
- Explicitly excluded uses.
|
| 39 |
+
- Deployment context and degree of human oversight.
|
| 40 |
+
|
| 41 |
+
### Evaluation scope
|
| 42 |
+
|
| 43 |
+
- Evaluated capabilities and datasets.
|
| 44 |
+
- Languages, modalities, populations, or contexts not evaluated.
|
| 45 |
+
- Hardware and software used.
|
| 46 |
+
|
| 47 |
+
### Known limitations and foreseeable risks
|
| 48 |
+
|
| 49 |
+
- Reliability limitations.
|
| 50 |
+
- Safety, bias, privacy, security, and misuse risks.
|
| 51 |
+
- High-risk decisions the model must not make autonomously.
|
| 52 |
+
|
| 53 |
+
### Mitigations and monitoring
|
| 54 |
+
|
| 55 |
+
- Technical and organizational safeguards.
|
| 56 |
+
- Human review, appeal, and correction mechanisms.
|
| 57 |
+
- Monitoring, incident response, and update policy.
|
| 58 |
+
|
| 59 |
+
## Apache License 2.0
|
| 60 |
+
|
| 61 |
+
The complete license text applicable to the upstream components follows.
|
| 62 |
+
|
| 63 |
+
Apache License
|
| 64 |
+
Version 2.0, January 2004
|
| 65 |
+
http://www.apache.org/licenses/
|
| 66 |
+
|
| 67 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 68 |
+
|
| 69 |
+
1. Definitions.
|
| 70 |
+
|
| 71 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 72 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 73 |
+
|
| 74 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 75 |
+
the copyright owner that is granting the License.
|
| 76 |
+
|
| 77 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 78 |
+
other entities that control, are controlled by, or are under common
|
| 79 |
+
control with that entity. For the purposes of this definition,
|
| 80 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 81 |
+
direction or management of such entity, whether by contract or
|
| 82 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 83 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 84 |
+
|
| 85 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 86 |
+
exercising permissions granted by this License.
|
| 87 |
+
|
| 88 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 89 |
+
including but not limited to software source code, documentation
|
| 90 |
+
source, and configuration files.
|
| 91 |
+
|
| 92 |
+
"Object" form shall mean any form resulting from mechanical
|
| 93 |
+
transformation or translation of a Source form, including but
|
| 94 |
+
not limited to compiled object code, generated documentation,
|
| 95 |
+
and conversions to other media types.
|
| 96 |
+
|
| 97 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 98 |
+
Object form, made available under the License, as indicated by a
|
| 99 |
+
copyright notice that is included in or attached to the work
|
| 100 |
+
(an example is provided in the Appendix below).
|
| 101 |
+
|
| 102 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 103 |
+
form, that is based on (or derived from) the Work and for which the
|
| 104 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 105 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 106 |
+
of this License, Derivative Works shall not include works that remain
|
| 107 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 108 |
+
the Work and Derivative Works thereof.
|
| 109 |
+
|
| 110 |
+
"Contribution" shall mean any work of authorship, including
|
| 111 |
+
the original version of the Work and any modifications or additions
|
| 112 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 113 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 114 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 115 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 116 |
+
means any form of electronic, verbal, or written communication sent
|
| 117 |
+
to the Licensor or its representatives, including but not limited to
|
| 118 |
+
communication on electronic mailing lists, source code control systems,
|
| 119 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 120 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 121 |
+
excluding communication that is conspicuously marked or otherwise
|
| 122 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 123 |
+
|
| 124 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 125 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 126 |
+
subsequently incorporated within the Work.
|
| 127 |
+
|
| 128 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 129 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 130 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 131 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 132 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 133 |
+
Work and such Derivative Works in Source or Object form.
|
| 134 |
+
|
| 135 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 136 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 137 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 138 |
+
(except as stated in this section) patent license to make, have made,
|
| 139 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 140 |
+
where such license applies only to those patent claims licensable
|
| 141 |
+
by such Contributor that are necessarily infringed by their
|
| 142 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 143 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 144 |
+
institute patent litigation against any entity (including a
|
| 145 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 146 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 147 |
+
or contributory patent infringement, then any patent licenses
|
| 148 |
+
granted to You under this License for that Work shall terminate
|
| 149 |
+
as of the date such litigation is filed.
|
| 150 |
+
|
| 151 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 152 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 153 |
+
modifications, and in Source or Object form, provided that You
|
| 154 |
+
meet the following conditions:
|
| 155 |
+
|
| 156 |
+
(a) You must give any other recipients of the Work or
|
| 157 |
+
Derivative Works a copy of this License; and
|
| 158 |
+
|
| 159 |
+
(b) You must cause any modified files to carry prominent notices
|
| 160 |
+
stating that You changed the files; and
|
| 161 |
+
|
| 162 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 163 |
+
that You distribute, all copyright, patent, trademark, and
|
| 164 |
+
attribution notices from the Source form of the Work,
|
| 165 |
+
excluding those notices that do not pertain to any part of
|
| 166 |
+
the Derivative Works; and
|
| 167 |
+
|
| 168 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 169 |
+
distribution, then any Derivative Works that You distribute must
|
| 170 |
+
include a readable copy of the attribution notices contained
|
| 171 |
+
within such NOTICE file, excluding those notices that do not
|
| 172 |
+
pertain to any part of the Derivative Works, in at least one
|
| 173 |
+
of the following places: within a NOTICE text file distributed
|
| 174 |
+
as part of the Derivative Works; within the Source form or
|
| 175 |
+
documentation, if provided along with the Derivative Works; or,
|
| 176 |
+
within a display generated by the Derivative Works, if and
|
| 177 |
+
wherever such third-party notices normally appear. The contents
|
| 178 |
+
of the NOTICE file are for informational purposes only and
|
| 179 |
+
do not modify the License. You may add Your own attribution
|
| 180 |
+
notices within Derivative Works that You distribute, alongside
|
| 181 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 182 |
+
that such additional attribution notices cannot be construed
|
| 183 |
+
as modifying the License.
|
| 184 |
+
|
| 185 |
+
You may add Your own copyright statement to Your modifications and
|
| 186 |
+
may provide additional or different license terms and conditions
|
| 187 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 188 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 189 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 190 |
+
the conditions stated in this License.
|
| 191 |
+
|
| 192 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 193 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 194 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 195 |
+
this License, without any additional terms or conditions.
|
| 196 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 197 |
+
the terms of any separate license agreement you may have executed
|
| 198 |
+
with Licensor regarding such Contributions.
|
| 199 |
+
|
| 200 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 201 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 202 |
+
except as required for reasonable and customary use in describing the
|
| 203 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 204 |
+
|
| 205 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 206 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 207 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 208 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 209 |
+
implied, including, without limitation, any warranties or conditions
|
| 210 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 211 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 212 |
+
appropriateness of using or redistributing the Work and assume any
|
| 213 |
+
risks associated with Your exercise of permissions under this License.
|
| 214 |
+
|
| 215 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 216 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 217 |
+
unless required by applicable law (such as deliberate and grossly
|
| 218 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 219 |
+
liable to You for damages, including any direct, indirect, special,
|
| 220 |
+
incidental, or consequential damages of any character arising as a
|
| 221 |
+
result of this License or out of the use or inability to use the
|
| 222 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 223 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 224 |
+
other commercial damages or losses), even if such Contributor
|
| 225 |
+
has been advised of the possibility of such damages.
|
| 226 |
+
|
| 227 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 228 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 229 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 230 |
+
or other liability obligations and/or rights consistent with this
|
| 231 |
+
License. However, in accepting such obligations, You may act only
|
| 232 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 233 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 234 |
+
defend, and hold each Contributor harmless for any liability
|
| 235 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 236 |
+
of your accepting any such warranty or additional liability.
|
| 237 |
+
|
| 238 |
+
END OF TERMS AND CONDITIONS
|
| 239 |
+
|
| 240 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 241 |
+
|
| 242 |
+
To apply the Apache License to your work, attach the following
|
| 243 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 244 |
+
replaced with your own identifying information. (Don't include
|
| 245 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 246 |
+
comment syntax for the file format. We also recommend that a
|
| 247 |
+
file or class name and description of purpose be included on the
|
| 248 |
+
same "printed page" as the copyright notice for easier
|
| 249 |
+
identification within third-party archives.
|
| 250 |
+
|
| 251 |
+
Copyright [yyyy] [name of copyright owner]
|
| 252 |
+
|
| 253 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 254 |
+
you may not use this file except in compliance with the License.
|
| 255 |
+
You may obtain a copy of the License at
|
| 256 |
+
|
| 257 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 258 |
+
|
| 259 |
+
Unless required by applicable law or agreed to in writing, software
|
| 260 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 261 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 262 |
+
See the License for the specific language governing permissions and
|
| 263 |
+
limitations under the License.
|
README.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: modilify-open-model-license-1.0
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: image-text-to-text
|
| 7 |
+
base_model: google/diffusiongemma-26B-A4B-it
|
| 8 |
+
tags:
|
| 9 |
+
- diffusion
|
| 10 |
+
- multimodal
|
| 11 |
+
- image-text-to-text
|
| 12 |
+
- video-text-to-text
|
| 13 |
+
- mixture-of-experts
|
| 14 |
+
- trust-remote-code
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+

|
| 18 |
+
|
| 19 |
+
# Modilify Mk1 Preview
|
| 20 |
+
|
| 21 |
+
Modilify Mk1 Preview is a multimodal block-diffusion model developed by Modilify. It combines the original DiffusionGemma text, image, and video context encoder with recurrent latent deliberation and a multiplicative confidence-and-entropy commit policy. Its central advance is elastic inference: the model can spend more heavy-denoise work and produce a longer response for a difficult problem, or commit more tokens per pass and finish sooner when the problem is easier.
|
| 22 |
+
|
| 23 |
+
## Model Summary
|
| 24 |
+
|
| 25 |
+
| | |
|
| 26 |
+
| --- | ---: |
|
| 27 |
+
| Architecture | Mixture-of-Experts block diffusion |
|
| 28 |
+
| Total Parameters | 26.139B |
|
| 29 |
+
| Activated Parameters | 4.729B, including the vision encoder |
|
| 30 |
+
| Text Heavy-Denoise Activated Parameters | 4.159B |
|
| 31 |
+
| FLOPs per Heavy Denoise | ~2.12 TFLOPs at batch 1, 256-token canvas, empty KV prefix |
|
| 32 |
+
| Layers | 30 |
|
| 33 |
+
| Number of Experts | 128 |
|
| 34 |
+
| Selected Experts per Token | 8 |
|
| 35 |
+
| Number of Shared Experts | 1 |
|
| 36 |
+
| Vocabulary Size | 262,144 |
|
| 37 |
+
| Context Length | 262,144 tokens |
|
| 38 |
+
| Activation Function | GELU, tanh approximation |
|
| 39 |
+
| Vision Encoder | Gemma 4 Vision |
|
| 40 |
+
| Vision Encoder Parameters | 569.550M |
|
| 41 |
+
| Modality | Text, Image, Video |
|
| 42 |
+
| Sliding Window | 1024 tokens |
|
| 43 |
+
| Canvas Length | 256 |
|
| 44 |
+
|
| 45 |
+
The heavy-denoise FLOPs estimate counts multiply-adds as two FLOPs and covers decoder, expert, latent deliberation, and attention work only. It excludes the encoder pass, sampling/softmax, and elementwise ops. Batch size scales it roughly linearly: a 256-token prefix raises the estimate to ~2.16 TFLOPs, and a 4,096-token prefix to ~2.38 TFLOPs because some layers use full attention.
|
| 46 |
+
|
| 47 |
+
## Benchmark Results
|
| 48 |
+
|
| 49 |
+
| Benchmark | Modilify Mk1 Preview | Status |
|
| 50 |
+
| --- | ---: | --- |
|
| 51 |
+
| MMLU Pro | ~78.0 | Partial, one-shot estimate |
|
| 52 |
+
| AIME 2026, no tools | ~70 | Partial, one-shot estimate |
|
| 53 |
+
|
| 54 |
+
These preliminary results use specialized inference settings: `denoise_temperature=0.4`, `commit_failure_budget=0.05`, `fused_entropy_weight=0.6`, and `jump_on_no_progress_after=32`. The defaults target substantially higher throughput and should not be expected to reproduce these estimates.
|
| 55 |
+
|
| 56 |
+
Only part of each dataset was evaluated, with one-shot prompting. Treat these values as unstable and non-comparable until the full benchmark release.
|
| 57 |
+
|
| 58 |
+
## Core Capabilities
|
| 59 |
+
|
| 60 |
+
- **Elastic reasoning length and throughput.** Unlike a fixed reasoning-token budget, each heavy denoise can commit a variable-length prefix. Easier problems can converge in fewer passes with more tokens committed per pass; harder problems can keep deliberating and produce longer answers, up to the configured generation and ponder bounds. `commit_failure_budget`, `fused_entropy_weight`, and the progress limits let deployments move the throughput-quality operating point.
|
| 61 |
+
- **Implicit context through latent deliberation.** The model reasons over the complete noisy canvas inside each heavy denoise, then compresses the evolving trajectory into recurrent token latents and fixed memory slots. That compact state conditions the next heavy pass and survives rolling-canvas commits, providing an implicit context channel without copying the entire denoise history into visible output tokens.
|
| 62 |
+
- **120x faster trajectory training.** The current memory-bounded training system delivered a measured 120x throughput improvement over the project's original trajectory-training implementation under the matched internal setup. This figure describes the training implementation comparison, not a 120x inference speedup or a comparison with unrelated systems.
|
| 63 |
+
- Text generation supports the native optional thinking-channel protocol, and input context extends to the configured 262,144-token limit.
|
| 64 |
+
|
| 65 |
+
## Getting Started
|
| 66 |
+
|
| 67 |
+
Transformers 5.14.1 is the minimum supported version. To get started, install Transformers, PyTorch, and Accelerate in your environment:
|
| 68 |
+
|
| 69 |
+
```shell
|
| 70 |
+
pip install -U transformers torch accelerate
|
| 71 |
+
```
|
| 72 |
+
|
| 73 |
+
### Text generation
|
| 74 |
+
|
| 75 |
+
```python
|
| 76 |
+
import torch
|
| 77 |
+
from transformers import AutoModelForMultimodalLM, AutoProcessor
|
| 78 |
+
|
| 79 |
+
model_id = "modilify/Modilify-Mk1-preview"
|
| 80 |
+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
|
| 81 |
+
model = AutoModelForMultimodalLM.from_pretrained(
|
| 82 |
+
model_id,
|
| 83 |
+
trust_remote_code=True,
|
| 84 |
+
dtype=torch.bfloat16,
|
| 85 |
+
device_map="auto",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
messages = [{"role": "user", "content": "Explain why the sky is blue."}]
|
| 89 |
+
inputs = processor.apply_chat_template(
|
| 90 |
+
messages,
|
| 91 |
+
tokenize=True,
|
| 92 |
+
add_generation_prompt=True,
|
| 93 |
+
enable_thinking=False,
|
| 94 |
+
return_dict=True,
|
| 95 |
+
return_tensors="pt",
|
| 96 |
+
).to(model.device)
|
| 97 |
+
|
| 98 |
+
output = model.generate(**inputs, max_new_tokens=256)
|
| 99 |
+
new_tokens = output.sequences[:, inputs["input_ids"].shape[1]:]
|
| 100 |
+
print(processor.batch_decode(new_tokens, skip_special_tokens=False)[0])
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
### Image input
|
| 104 |
+
|
| 105 |
+
```python
|
| 106 |
+
from PIL import Image
|
| 107 |
+
|
| 108 |
+
image = Image.open("example.jpg").convert("RGB")
|
| 109 |
+
messages = [{
|
| 110 |
+
"role": "user",
|
| 111 |
+
"content": [
|
| 112 |
+
{"type": "image", "image": image},
|
| 113 |
+
{"type": "text", "text": "Describe the image and identify uncertainty."},
|
| 114 |
+
],
|
| 115 |
+
}]
|
| 116 |
+
inputs = processor.apply_chat_template(
|
| 117 |
+
messages,
|
| 118 |
+
tokenize=True,
|
| 119 |
+
add_generation_prompt=True,
|
| 120 |
+
enable_thinking=True,
|
| 121 |
+
return_dict=True,
|
| 122 |
+
return_tensors="pt",
|
| 123 |
+
).to(model.device)
|
| 124 |
+
output = model.generate(**inputs, max_new_tokens=256)
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
### Video-frame input
|
| 128 |
+
|
| 129 |
+
The processor represents video as a sampled sequence of frames. The following
|
| 130 |
+
example uses PyAV to decode a short local clip and samples at most 32 RGB frames.
|
| 131 |
+
|
| 132 |
+
```python
|
| 133 |
+
import av
|
| 134 |
+
from PIL import Image
|
| 135 |
+
|
| 136 |
+
container = av.open("short_clip.mp4")
|
| 137 |
+
decoded = [Image.fromarray(frame.to_rgb().to_ndarray()) for frame in container.decode(video=0)]
|
| 138 |
+
stride = max(1, len(decoded) // 32)
|
| 139 |
+
frames = decoded[::stride][:32]
|
| 140 |
+
|
| 141 |
+
messages = [{
|
| 142 |
+
"role": "user",
|
| 143 |
+
"content": [
|
| 144 |
+
{"type": "video", "video": frames},
|
| 145 |
+
{"type": "text", "text": "Summarize the main visual events in order."},
|
| 146 |
+
],
|
| 147 |
+
}]
|
| 148 |
+
inputs = processor.apply_chat_template(
|
| 149 |
+
messages,
|
| 150 |
+
tokenize=True,
|
| 151 |
+
add_generation_prompt=True,
|
| 152 |
+
enable_thinking=True,
|
| 153 |
+
return_dict=True,
|
| 154 |
+
return_tensors="pt",
|
| 155 |
+
).to(model.device)
|
| 156 |
+
output = model.generate(**inputs, max_new_tokens=256)
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
## Thinking mode
|
| 160 |
+
|
| 161 |
+
The Gemma chat template controls thinking markup. Set `enable_thinking=True` in `apply_chat_template` to request the native thinking/channel protocol, or set it to `False` for a direct answer. Applications should not assume hidden reasoning is complete, correct, or appropriate to expose to end users.
|
| 162 |
+
|
| 163 |
+
## Configurable inference parameters
|
| 164 |
+
|
| 165 |
+
All model-owned values below are serialized in `config.json` and may be changed before loading or through a copied configuration object.
|
| 166 |
+
|
| 167 |
+
| Parameter | Default | Meaning |
|
| 168 |
+
| --- | ---: | --- |
|
| 169 |
+
| `canvas_length` | 256 | Rolling diffusion canvas length |
|
| 170 |
+
| `denoise_temperature` | 0.8 | Sampling temperature |
|
| 171 |
+
| `commit_failure_budget` | 0.2 | Normal cumulative prefix risk limit |
|
| 172 |
+
| `fused_entropy_weight` | 0.5 | Entropy multiplier coefficient |
|
| 173 |
+
| `jump_failure_budget` | 2.0 | Forced-jump cumulative risk limit |
|
| 174 |
+
| `vocab_chunk_size` | 65,536 | Serialized projection planning size; standard tensor operations are used |
|
| 175 |
+
| `jump_on_no_progress_after` | 12 | Stagnation threshold |
|
| 176 |
+
| `max_ponder_steps` | 64 | Watchdog multiplier per requested token |
|
| 177 |
+
| `min_trajectory_progress` | 0.005 | Minimum fused-risk improvement |
|
| 178 |
+
| `latent_dim` | 1,536 | Latent state width |
|
| 179 |
+
| `latent_memory_slots` | 64 | Persistent memory slot count |
|
| 180 |
+
| `latent_num_layers` | 4 | Latent Transformer depth |
|
| 181 |
+
| `latent_num_heads` | 16 | Latent attention heads |
|
| 182 |
+
| `latent_local_attention_window` | 128 | Local token-attention window |
|
| 183 |
+
| `latent_dropout` | 0.0 | Inference dropout probability |
|
| 184 |
+
| `turn_end_token_id` | 106 | Gemma turn terminator |
|
| 185 |
+
|
| 186 |
+
Example override:
|
| 187 |
+
|
| 188 |
+
```python
|
| 189 |
+
from transformers import AutoConfig
|
| 190 |
+
|
| 191 |
+
config = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
|
| 192 |
+
config.max_ponder_steps = 32
|
| 193 |
+
config.commit_failure_budget = 0.15
|
| 194 |
+
model = AutoModelForMultimodalLM.from_pretrained(
|
| 195 |
+
model_id,
|
| 196 |
+
config=config,
|
| 197 |
+
trust_remote_code=True,
|
| 198 |
+
dtype=torch.bfloat16,
|
| 199 |
+
device_map="auto",
|
| 200 |
+
)
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
Generation supports left-padded batches with independent stopping and
|
| 204 |
+
`generated_lengths` for every row. Batch prompts of similar lengths together
|
| 205 |
+
for the best throughput; KV-cache and canvas memory grow with batch size.
|
| 206 |
+
Streaming and caller-supplied KV caches remain limited to batch size 1.
|
| 207 |
+
|
| 208 |
+
## Details
|
| 209 |
+
|
| 210 |
+
Trained on Apple silicon.
|
| 211 |
+
|
| 212 |
+
Developed on Mac by Modilify.
|
| 213 |
+
|
| 214 |
+
## Evaluation status, limitations, and risks
|
| 215 |
+
|
| 216 |
+
The benchmark values above are partial one-shot estimates, not a complete evaluation. Export checks established checkpoint structure, exact adapter application, valid safetensors indexing, absence of residual adapters, and byte-level preservation of the vision tower and projection; they do not establish accuracy, robustness, calibration, fairness, safety, or fitness for use.
|
| 217 |
+
|
| 218 |
+
The model can hallucinate facts, citations, visual details, or temporal relationships; reproduce bias, unsafe content, personal information, or copyrighted material; and consume substantial time and memory during long iterative generation. Confidence-based commits are compute-control decisions, not guarantees of correctness. Visual performance can degrade with poor resolution, motion, occlusion, unusual aspect ratios, or domain shift.
|
| 219 |
+
|
| 220 |
+
Evaluate the exact deployment on representative, adversarial, and out-of-distribution inputs. Use layered safeguards, monitoring, incident response, and qualified human review, and never delegate autonomous high-risk medical, legal, financial, employment, housing, education, critical-infrastructure, or safety decisions to the model.
|
| 221 |
+
|
| 222 |
+
## License
|
| 223 |
+
|
| 224 |
+
Released under the draft [Modilify Open Model License 1.0](LICENSE), subject to its responsible-use and derivative-impact terms. Upstream rights, attribution, Apache-2.0 text, and the impact-statement template are retained in [NOTICE.md](NOTICE.md). Obtain independent legal review before public release.
|
| 225 |
+
|
| 226 |
+
## Citation
|
| 227 |
+
|
| 228 |
+
Until a formal paper is available, cite the model repository and its base:
|
| 229 |
+
|
| 230 |
+
```bibtex
|
| 231 |
+
@software{modilify_mk1_preview_2026,
|
| 232 |
+
title = {Modilify Mk1 Preview},
|
| 233 |
+
author = {Modilify},
|
| 234 |
+
year = {2026},
|
| 235 |
+
note = {A multimodal latent-deliberation derivative of DiffusionGemma}
|
| 236 |
+
}
|
| 237 |
+
```
|
| 238 |
+
|
| 239 |
+
Also cite the upstream DiffusionGemma release as requested by Google DeepMind.
|
assets/01-LOGO.jpg
ADDED
|
Git LFS Details
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{#
|
| 2 |
+
Template: Google Gemma 4 Canonical Chat Template
|
| 3 |
+
Author: Google Gemma Engineering Team
|
| 4 |
+
Published: 2026-07-09
|
| 5 |
+
Context: Fixed tool-calling loops, turn closures, and thinking content-ordering.
|
| 6 |
+
#}
|
| 7 |
+
{%- macro format_parameters(properties, required, filter_keys=false) -%}
|
| 8 |
+
{%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%}
|
| 9 |
+
{%- set ns = namespace(found_first=false) -%}
|
| 10 |
+
{%- for key, value in properties | dictsort -%}
|
| 11 |
+
{%- set add_comma = false -%}
|
| 12 |
+
{%- if not filter_keys or key not in standard_keys -%}
|
| 13 |
+
{%- if ns.found_first %},{% endif -%}
|
| 14 |
+
{%- set ns.found_first = true -%}
|
| 15 |
+
{{ key }}:{
|
| 16 |
+
{%- if value['description'] -%}
|
| 17 |
+
description:<|"|>{{ value['description'] }}<|"|>
|
| 18 |
+
{%- set add_comma = true -%}
|
| 19 |
+
{%- endif -%}
|
| 20 |
+
{%- if value['type'] | upper == 'STRING' -%}
|
| 21 |
+
{%- if value['enum'] -%}
|
| 22 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 23 |
+
enum:{{ format_argument(value['enum']) }}
|
| 24 |
+
{%- endif -%}
|
| 25 |
+
{%- elif value['type'] | upper == 'ARRAY' -%}
|
| 26 |
+
{%- if value['items'] is mapping and value['items'] -%}
|
| 27 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 28 |
+
items:{
|
| 29 |
+
{%- set ns_items = namespace(found_first=false) -%}
|
| 30 |
+
{%- for item_key, item_value in value['items'] | dictsort -%}
|
| 31 |
+
{%- if item_value is not none -%}
|
| 32 |
+
{%- if ns_items.found_first %},{% endif -%}
|
| 33 |
+
{%- set ns_items.found_first = true -%}
|
| 34 |
+
{%- if item_key == 'properties' -%}
|
| 35 |
+
properties:{
|
| 36 |
+
{%- if item_value is mapping -%}
|
| 37 |
+
{{- format_parameters(item_value, value['items']['required'] | default([])) -}}
|
| 38 |
+
{%- endif -%}
|
| 39 |
+
}
|
| 40 |
+
{%- elif item_key == 'required' -%}
|
| 41 |
+
required:[
|
| 42 |
+
{%- for req_item in item_value -%}
|
| 43 |
+
<|"|>{{- req_item -}}<|"|>
|
| 44 |
+
{%- if not loop.last %},{% endif -%}
|
| 45 |
+
{%- endfor -%}
|
| 46 |
+
]
|
| 47 |
+
{%- elif item_key == 'type' -%}
|
| 48 |
+
{%- if item_value is string -%}
|
| 49 |
+
type:{{ format_argument(item_value | upper) }}
|
| 50 |
+
{%- else -%}
|
| 51 |
+
type:{{ format_argument(item_value | map('upper') | list) }}
|
| 52 |
+
{%- endif -%}
|
| 53 |
+
{%- else -%}
|
| 54 |
+
{{ item_key }}:{{ format_argument(item_value) }}
|
| 55 |
+
{%- endif -%}
|
| 56 |
+
{%- endif -%}
|
| 57 |
+
{%- endfor -%}
|
| 58 |
+
}
|
| 59 |
+
{%- endif -%}
|
| 60 |
+
{%- endif -%}
|
| 61 |
+
{%- if value['nullable'] %}
|
| 62 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 63 |
+
nullable:true
|
| 64 |
+
{%- endif -%}
|
| 65 |
+
{%- if value['type'] | upper == 'OBJECT' -%}
|
| 66 |
+
{%- if value['properties'] is defined and value['properties'] is mapping -%}
|
| 67 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 68 |
+
properties:{
|
| 69 |
+
{{- format_parameters(value['properties'], value['required'] | default([])) -}}
|
| 70 |
+
}
|
| 71 |
+
{%- elif value is mapping -%}
|
| 72 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 73 |
+
properties:{
|
| 74 |
+
{{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}}
|
| 75 |
+
}
|
| 76 |
+
{%- endif -%}
|
| 77 |
+
{%- if value['required'] -%}
|
| 78 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 79 |
+
required:[
|
| 80 |
+
{%- for item in value['required'] | default([]) -%}
|
| 81 |
+
<|"|>{{- item -}}<|"|>
|
| 82 |
+
{%- if not loop.last %},{% endif -%}
|
| 83 |
+
{%- endfor -%}
|
| 84 |
+
]
|
| 85 |
+
{%- endif -%}
|
| 86 |
+
{%- endif -%}
|
| 87 |
+
{%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%}
|
| 88 |
+
type:<|"|>{{ value['type'] | upper }}<|"|>}
|
| 89 |
+
{%- endif -%}
|
| 90 |
+
{%- endfor -%}
|
| 91 |
+
{%- endmacro -%}
|
| 92 |
+
{%- macro format_function_declaration(tool_data) -%}
|
| 93 |
+
declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|>
|
| 94 |
+
{%- set params = tool_data['function']['parameters'] -%}
|
| 95 |
+
{%- if params -%}
|
| 96 |
+
,parameters:{
|
| 97 |
+
{%- if params['properties'] -%}
|
| 98 |
+
properties:{ {{- format_parameters(params['properties'], params['required']) -}} },
|
| 99 |
+
{%- endif -%}
|
| 100 |
+
{%- if params['required'] -%}
|
| 101 |
+
required:[
|
| 102 |
+
{%- for item in params['required'] -%}
|
| 103 |
+
<|"|>{{- item -}}<|"|>
|
| 104 |
+
{{- ',' if not loop.last -}}
|
| 105 |
+
{%- endfor -%}
|
| 106 |
+
],
|
| 107 |
+
{%- endif -%}
|
| 108 |
+
{%- if params['type'] -%}
|
| 109 |
+
type:<|"|>{{- params['type'] | upper -}}<|"|>}
|
| 110 |
+
{%- endif -%}
|
| 111 |
+
{%- endif -%}
|
| 112 |
+
{%- if 'response' in tool_data['function'] -%}
|
| 113 |
+
{%- set response_declaration = tool_data['function']['response'] -%}
|
| 114 |
+
,response:{
|
| 115 |
+
{%- if response_declaration['description'] -%}
|
| 116 |
+
description:<|"|>{{- response_declaration['description'] -}}<|"|>,
|
| 117 |
+
{%- endif -%}
|
| 118 |
+
{%- if response_declaration['type'] | upper == 'OBJECT' -%}
|
| 119 |
+
type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>}
|
| 120 |
+
{%- endif -%}
|
| 121 |
+
{%- endif -%}
|
| 122 |
+
}
|
| 123 |
+
{%- endmacro -%}
|
| 124 |
+
{%- macro format_argument(argument, escape_keys=True) -%}
|
| 125 |
+
{%- if argument is none -%}
|
| 126 |
+
{{- 'null' -}}
|
| 127 |
+
{%- elif argument is string -%}
|
| 128 |
+
{{- '<|"|>' + argument + '<|"|>' -}}
|
| 129 |
+
{%- elif argument is boolean -%}
|
| 130 |
+
{{- 'true' if argument else 'false' -}}
|
| 131 |
+
{%- elif argument is mapping -%}
|
| 132 |
+
{{- '{' -}}
|
| 133 |
+
{%- set ns = namespace(found_first=false) -%}
|
| 134 |
+
{%- for key, value in argument | dictsort -%}
|
| 135 |
+
{%- if ns.found_first %},{% endif -%}
|
| 136 |
+
{%- set ns.found_first = true -%}
|
| 137 |
+
{%- if escape_keys -%}
|
| 138 |
+
{{- '<|"|>' + key + '<|"|>' -}}
|
| 139 |
+
{%- else -%}
|
| 140 |
+
{{- key -}}
|
| 141 |
+
{%- endif -%}
|
| 142 |
+
:{{- format_argument(value, escape_keys=escape_keys) -}}
|
| 143 |
+
{%- endfor -%}
|
| 144 |
+
{{- '}' -}}
|
| 145 |
+
{%- elif argument is sequence -%}
|
| 146 |
+
{{- '[' -}}
|
| 147 |
+
{%- for item in argument -%}
|
| 148 |
+
{{- format_argument(item, escape_keys=escape_keys) -}}
|
| 149 |
+
{%- if not loop.last %},{% endif -%}
|
| 150 |
+
{%- endfor -%}
|
| 151 |
+
{{- ']' -}}
|
| 152 |
+
{%- else -%}
|
| 153 |
+
{{- argument -}}
|
| 154 |
+
{%- endif -%}
|
| 155 |
+
{%- endmacro -%}
|
| 156 |
+
{%- macro strip_thinking(text) -%}
|
| 157 |
+
{%- set ns = namespace(result='') -%}
|
| 158 |
+
{%- for part in text.split('<channel|>') -%}
|
| 159 |
+
{%- if '<|channel>' in part -%}
|
| 160 |
+
{%- set ns.result = ns.result + part.split('<|channel>')[0] -%}
|
| 161 |
+
{%- else -%}
|
| 162 |
+
{%- set ns.result = ns.result + part -%}
|
| 163 |
+
{%- endif -%}
|
| 164 |
+
{%- endfor -%}
|
| 165 |
+
{{- ns.result | trim -}}
|
| 166 |
+
{%- endmacro -%}
|
| 167 |
+
|
| 168 |
+
{%- macro format_tool_response_block(tool_name, response) -%}
|
| 169 |
+
{{- '<|tool_response>' -}}
|
| 170 |
+
{%- if response is mapping -%}
|
| 171 |
+
{{- 'response:' + tool_name + '{' -}}
|
| 172 |
+
{%- for key, value in response | dictsort -%}
|
| 173 |
+
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
| 174 |
+
{%- if not loop.last %},{% endif -%}
|
| 175 |
+
{%- endfor -%}
|
| 176 |
+
{{- '}' -}}
|
| 177 |
+
{%- else -%}
|
| 178 |
+
{{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}}
|
| 179 |
+
{%- endif -%}
|
| 180 |
+
{{- '<tool_response|>' -}}
|
| 181 |
+
{%- endmacro -%}
|
| 182 |
+
|
| 183 |
+
{#- ===== SETUP ===== -#}
|
| 184 |
+
{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%}
|
| 185 |
+
{%- set loop_messages = messages -%}
|
| 186 |
+
{%- set enable_thinking = enable_thinking | default(false) -%}
|
| 187 |
+
{%- set preserve_thinking = preserve_thinking | default(false) -%}
|
| 188 |
+
{{- bos_token -}}
|
| 189 |
+
{#- Handle System/Tool Definitions Block -#}
|
| 190 |
+
{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%}
|
| 191 |
+
{{- '<|turn>system\n' -}}
|
| 192 |
+
{#- Inject Thinking token at the very top of the FIRST system turn -#}
|
| 193 |
+
{%- if enable_thinking -%}
|
| 194 |
+
{{- '<|think|>\n' -}}
|
| 195 |
+
{%- set ns.prev_message_type = 'think' -%}
|
| 196 |
+
{%- endif -%}
|
| 197 |
+
{%- if messages and messages[0]['role'] in ['system', 'developer'] -%}
|
| 198 |
+
{%- if messages[0]['content'] is string -%}
|
| 199 |
+
{{- messages[0]['content'] | trim -}}
|
| 200 |
+
{%- elif messages[0]['content'] is sequence -%}
|
| 201 |
+
{%- for item in messages[0]['content'] -%}
|
| 202 |
+
{{- item['text'] | trim + ' '-}}
|
| 203 |
+
{%- endfor -%}
|
| 204 |
+
{%- endif -%}
|
| 205 |
+
{%- set loop_messages = messages[1:] -%}
|
| 206 |
+
{%- endif -%}
|
| 207 |
+
{%- if tools -%}
|
| 208 |
+
{%- for tool in tools %}
|
| 209 |
+
{{- '<|tool>' -}}
|
| 210 |
+
{{- format_function_declaration(tool) | trim -}}
|
| 211 |
+
{{- '<tool|>' -}}
|
| 212 |
+
{%- endfor %}
|
| 213 |
+
{%- set ns.prev_message_type = 'tool' -%}
|
| 214 |
+
{%- endif -%}
|
| 215 |
+
{{- '<turn|>\n' -}}
|
| 216 |
+
{%- endif %}
|
| 217 |
+
|
| 218 |
+
{#- Pre-scan: find last user message index for reasoning guard -#}
|
| 219 |
+
{%- set ns_turn = namespace(last_user_idx=-1) -%}
|
| 220 |
+
{%- for i in range(loop_messages | length) -%}
|
| 221 |
+
{%- if loop_messages[i]['role'] == 'user' -%}
|
| 222 |
+
{%- set ns_turn.last_user_idx = i -%}
|
| 223 |
+
{%- endif -%}
|
| 224 |
+
{%- endfor -%}
|
| 225 |
+
|
| 226 |
+
{#- Loop through messages -#}
|
| 227 |
+
{%- for message in loop_messages -%}
|
| 228 |
+
{%- if message['role'] != 'tool' -%}
|
| 229 |
+
{%- set ns.prev_message_type = None -%}
|
| 230 |
+
{%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%}
|
| 231 |
+
{#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#}
|
| 232 |
+
{%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%}
|
| 233 |
+
{%- if not continue_same_model_turn -%}
|
| 234 |
+
{{- '<|turn>' + role + '\n' }}
|
| 235 |
+
|
| 236 |
+
{%- endif -%}
|
| 237 |
+
|
| 238 |
+
{#- Render reasoning/reasoning_content as thinking channel -#}
|
| 239 |
+
{%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%}
|
| 240 |
+
{%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%}
|
| 241 |
+
{%- if thinking_text and thinking_gate -%}
|
| 242 |
+
{{- '<|channel>thought\n' + thinking_text + '\n<channel|>' -}}
|
| 243 |
+
{%- endif -%}
|
| 244 |
+
|
| 245 |
+
{%- if message.get('tool_calls') -%}
|
| 246 |
+
{%- for tool_call in message.get('tool_calls') -%}
|
| 247 |
+
{%- set function = tool_call['function'] -%}
|
| 248 |
+
{{- '<|tool_call>call:' + function['name'] + '{' -}}
|
| 249 |
+
{%- if function['arguments'] is mapping -%}
|
| 250 |
+
{%- set ns_args = namespace(found_first=false) -%}
|
| 251 |
+
{%- for key, value in function['arguments'] | dictsort -%}
|
| 252 |
+
{%- if ns_args.found_first %},{% endif -%}
|
| 253 |
+
{%- set ns_args.found_first = true -%}
|
| 254 |
+
{{- key -}}:{{- format_argument(value, escape_keys=False) -}}
|
| 255 |
+
{%- endfor -%}
|
| 256 |
+
{%- elif function['arguments'] is none -%}
|
| 257 |
+
{%- else -%}
|
| 258 |
+
{{- raise_exception(
|
| 259 |
+
"chat_template: tool_calls[].function.arguments must be a "
|
| 260 |
+
"JSON object (mapping), not a string. Deserialize arguments "
|
| 261 |
+
"before passing to the template."
|
| 262 |
+
) -}}
|
| 263 |
+
{%- endif -%}
|
| 264 |
+
{{- '}<tool_call|>' -}}
|
| 265 |
+
{%- endfor -%}
|
| 266 |
+
{%- set ns.prev_message_type = 'tool_call' -%}
|
| 267 |
+
{%- endif -%}
|
| 268 |
+
|
| 269 |
+
{%- set ns_tr_out = namespace(flag=false) -%}
|
| 270 |
+
{%- if message.get('tool_responses') -%}
|
| 271 |
+
{#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#}
|
| 272 |
+
{%- for tool_response in message.get('tool_responses') -%}
|
| 273 |
+
{{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}}
|
| 274 |
+
{%- set ns_tr_out.flag = true -%}
|
| 275 |
+
{%- set ns.prev_message_type = 'tool_response' -%}
|
| 276 |
+
{%- endfor -%}
|
| 277 |
+
{%- elif message.get('tool_calls') -%}
|
| 278 |
+
{#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#}
|
| 279 |
+
{%- set ns_tool_scan = namespace(stopped=false) -%}
|
| 280 |
+
{%- for k in range(loop.index0 + 1, loop_messages | length) -%}
|
| 281 |
+
{%- if ns_tool_scan.stopped -%}
|
| 282 |
+
{%- elif loop_messages[k]['role'] != 'tool' -%}
|
| 283 |
+
{%- set ns_tool_scan.stopped = true -%}
|
| 284 |
+
{%- else -%}
|
| 285 |
+
{%- set follow = loop_messages[k] -%}
|
| 286 |
+
{#- Resolve tool_call_id to function name -#}
|
| 287 |
+
{%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%}
|
| 288 |
+
{%- for tc in message.get('tool_calls') -%}
|
| 289 |
+
{%- if tc.get('id') == follow.get('tool_call_id') -%}
|
| 290 |
+
{%- set ns_tname.name = tc['function']['name'] -%}
|
| 291 |
+
{%- endif -%}
|
| 292 |
+
{%- endfor -%}
|
| 293 |
+
{#- Handle content as string or content-parts array -#}
|
| 294 |
+
{%- set tool_body = follow.get('content') -%}
|
| 295 |
+
{%- if tool_body is string -%}
|
| 296 |
+
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
| 297 |
+
{%- elif tool_body is sequence and tool_body is not string -%}
|
| 298 |
+
{%- set ns_txt = namespace(s='') -%}
|
| 299 |
+
{%- for part in tool_body -%}
|
| 300 |
+
{%- if part.get('type') == 'text' -%}
|
| 301 |
+
{%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%}
|
| 302 |
+
{%- endif -%}
|
| 303 |
+
{%- endfor -%}
|
| 304 |
+
{{- format_tool_response_block(ns_tname.name, ns_txt.s) -}}
|
| 305 |
+
{%- for part in tool_body -%}
|
| 306 |
+
{%- if part.get('type') in ['image', 'image_url'] -%}
|
| 307 |
+
{{- '<|image|>' -}}
|
| 308 |
+
{%- elif part.get('type') in ['audio', 'input_audio'] -%}
|
| 309 |
+
{{- '<|audio|>' -}}
|
| 310 |
+
{%- elif part.get('type') == 'video' -%}
|
| 311 |
+
{{- '<|video|>' -}}
|
| 312 |
+
{%- endif -%}
|
| 313 |
+
{%- endfor -%}
|
| 314 |
+
{%- else -%}
|
| 315 |
+
{{- format_tool_response_block(ns_tname.name, tool_body) -}}
|
| 316 |
+
{%- endif -%}
|
| 317 |
+
{%- set ns_tr_out.flag = true -%}
|
| 318 |
+
{%- set ns.prev_message_type = 'tool_response' -%}
|
| 319 |
+
{%- endif -%}
|
| 320 |
+
{%- endfor -%}
|
| 321 |
+
{%- endif -%}
|
| 322 |
+
|
| 323 |
+
{%- set captured_content -%}
|
| 324 |
+
{%- if message.get('content') is string -%}
|
| 325 |
+
{%- if role == 'model' -%}
|
| 326 |
+
{{- strip_thinking(message['content']) -}}
|
| 327 |
+
{%- else -%}
|
| 328 |
+
{{- message['content'] | trim -}}
|
| 329 |
+
{%- endif -%}
|
| 330 |
+
{%- elif message.get('content') is sequence -%}
|
| 331 |
+
{%- for item in message['content'] -%}
|
| 332 |
+
{%- if item.get('type') == 'text' -%}
|
| 333 |
+
{%- if role == 'model' -%}
|
| 334 |
+
{{- strip_thinking(item['text']) -}}
|
| 335 |
+
{%- else -%}
|
| 336 |
+
{{- item['text'] | trim -}}
|
| 337 |
+
{%- endif -%}
|
| 338 |
+
{%- elif item.get('type') in ['image', 'image_url'] -%}
|
| 339 |
+
{{- '<|image|>' -}}
|
| 340 |
+
{%- elif item.get('type') in ['audio', 'input_audio'] -%}
|
| 341 |
+
{{- '<|audio|>' -}}
|
| 342 |
+
{%- elif item.get('type') == 'video' -%}
|
| 343 |
+
{{- '<|video|>' -}}
|
| 344 |
+
{%- endif -%}
|
| 345 |
+
{%- endfor -%}
|
| 346 |
+
{%- endif -%}
|
| 347 |
+
{%- endset -%}
|
| 348 |
+
|
| 349 |
+
{{- captured_content -}}
|
| 350 |
+
{%- set has_content = captured_content | trim | length > 0 -%}
|
| 351 |
+
|
| 352 |
+
{#- Forward-scan: find next non-tool message role for continuation detection -#}
|
| 353 |
+
{%- set next_nt = namespace(role=None, found=false) -%}
|
| 354 |
+
{%- for j in range(loop.index0 + 1, loop_messages | length) -%}
|
| 355 |
+
{%- if not next_nt.found -%}
|
| 356 |
+
{%- if loop_messages[j]['role'] != 'tool' -%}
|
| 357 |
+
{%- set next_nt.role = loop_messages[j]['role'] -%}
|
| 358 |
+
{%- set next_nt.found = true -%}
|
| 359 |
+
{%- endif -%}
|
| 360 |
+
{%- endif -%}
|
| 361 |
+
{%- endfor -%}
|
| 362 |
+
|
| 363 |
+
{%- set continues_into_next = (
|
| 364 |
+
role == 'model'
|
| 365 |
+
and next_nt.role == 'assistant'
|
| 366 |
+
and (not message.get('tool_calls') or ns_tr_out.flag)
|
| 367 |
+
) -%}
|
| 368 |
+
|
| 369 |
+
{%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%}
|
| 370 |
+
{{- '<|tool_response>' -}}
|
| 371 |
+
{%- elif continues_into_next -%}
|
| 372 |
+
{%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%}
|
| 373 |
+
{{- '<turn|>\n' -}}
|
| 374 |
+
{%- endif -%}
|
| 375 |
+
{%- endif -%}
|
| 376 |
+
|
| 377 |
+
{#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#}
|
| 378 |
+
{%- set ns.prev_non_tool_role = message['role'] -%}
|
| 379 |
+
{%- endfor -%}
|
| 380 |
+
|
| 381 |
+
{%- if add_generation_prompt -%}
|
| 382 |
+
{%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
|
| 383 |
+
{{- '<|turn>model\n' -}}
|
| 384 |
+
{%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}
|
| 385 |
+
{{- '<|channel>thought\n' -}}
|
| 386 |
+
{%- endif -%}
|
| 387 |
+
{%- endif -%}
|
commit_policy.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Confidence-and-entropy commit policy for inference."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from .latent_deliberation import (
|
| 14 |
+
advance_trajectory_clocks,
|
| 15 |
+
should_force_trajectory_jump,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
FUSED_EPS = 1e-6
|
| 19 |
+
FUSED_ENTROPY_WEIGHT = 0.5
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def fused_commit_confidence(
|
| 23 |
+
proposal_confidence: torch.Tensor,
|
| 24 |
+
token_entropy: torch.Tensor,
|
| 25 |
+
*,
|
| 26 |
+
vocab_size: int = 256000,
|
| 27 |
+
entropy_weight: float = FUSED_ENTROPY_WEIGHT,
|
| 28 |
+
eps: float = FUSED_EPS,
|
| 29 |
+
) -> torch.Tensor:
|
| 30 |
+
"""Fuse proposal confidence with token entropy into effective commit confidence.
|
| 31 |
+
|
| 32 |
+
Effective confidence is defined using a multiplicative entropy penalty:
|
| 33 |
+
|
| 34 |
+
fused = confidence * exp(-entropy_weight * token_entropy)
|
| 35 |
+
|
| 36 |
+
This scales proposal confidence by the entropy discount factor e^(-alpha * H),
|
| 37 |
+
penalizing token predictions with high distribution disorder.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
if vocab_size <= 1:
|
| 41 |
+
raise ValueError("`vocab_size` must be greater than one.")
|
| 42 |
+
if not math.isfinite(entropy_weight) or entropy_weight < 0.0:
|
| 43 |
+
raise ValueError("`entropy_weight` must be finite and non-negative.")
|
| 44 |
+
confidence = proposal_confidence.float().clamp(min=eps, max=1.0)
|
| 45 |
+
entropy = token_entropy.float().clamp(0.0, math.log(vocab_size))
|
| 46 |
+
entropy_penalty = torch.exp(-entropy_weight * entropy)
|
| 47 |
+
fused = confidence * entropy_penalty
|
| 48 |
+
return fused.clamp(min=eps, max=1.0)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def fused_commit_failure_rate(
|
| 52 |
+
proposal_confidence: torch.Tensor,
|
| 53 |
+
token_entropy: torch.Tensor,
|
| 54 |
+
**kwargs: object,
|
| 55 |
+
) -> torch.Tensor:
|
| 56 |
+
"""Return ``1 - effective_confidence`` from the shared fusion helper."""
|
| 57 |
+
|
| 58 |
+
return 1.0 - fused_commit_confidence(
|
| 59 |
+
proposal_confidence, token_entropy, **kwargs
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(frozen=True)
|
| 64 |
+
class CommitPolicyDecision:
|
| 65 |
+
"""One inference transition from proposal to committed prefix."""
|
| 66 |
+
|
| 67 |
+
normal_lengths: torch.LongTensor
|
| 68 |
+
commit_lengths: torch.LongTensor
|
| 69 |
+
commit_token_ids: torch.LongTensor
|
| 70 |
+
jump_rows: torch.BoolTensor
|
| 71 |
+
ponder_steps: torch.IntTensor
|
| 72 |
+
stagnation_steps: torch.IntTensor
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def prefix_failure_commit_lengths(
|
| 76 |
+
failure_rate: torch.Tensor,
|
| 77 |
+
*,
|
| 78 |
+
failure_budget: float,
|
| 79 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 80 |
+
) -> torch.LongTensor:
|
| 81 |
+
"""Return the longest valid prefix satisfying ``cumsum(failure_rate) < budget``."""
|
| 82 |
+
|
| 83 |
+
if failure_rate.ndim != 2:
|
| 84 |
+
raise ValueError("Failure rate must have shape [batch, canvas].")
|
| 85 |
+
if not math.isfinite(failure_budget) or failure_budget <= 0:
|
| 86 |
+
raise ValueError("Commit failure budget must be finite and positive.")
|
| 87 |
+
if valid_mask is None:
|
| 88 |
+
valid_mask = torch.ones_like(failure_rate, dtype=torch.bool)
|
| 89 |
+
if valid_mask.shape != failure_rate.shape:
|
| 90 |
+
raise ValueError("Commit validity mask must match failure rate.")
|
| 91 |
+
|
| 92 |
+
risk = failure_rate.float().clamp(0.0, 1.0) * valid_mask.to(torch.float32)
|
| 93 |
+
cumulative_risk = risk.cumsum(dim=-1)
|
| 94 |
+
contiguous_valid = valid_mask.long().cumprod(dim=-1).bool()
|
| 95 |
+
allowed = cumulative_risk.lt(float(failure_budget)) & contiguous_valid
|
| 96 |
+
return allowed.long().cumprod(dim=-1).sum(dim=-1)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def first_committed_token_lengths(
|
| 100 |
+
proposal: torch.LongTensor,
|
| 101 |
+
commit_lengths: torch.LongTensor,
|
| 102 |
+
token_id: int | Sequence[int],
|
| 103 |
+
) -> torch.LongTensor:
|
| 104 |
+
"""Clip each committed prefix immediately after its first matching stop token."""
|
| 105 |
+
|
| 106 |
+
if proposal.ndim != 2 or commit_lengths.shape != proposal.shape[:1]:
|
| 107 |
+
raise ValueError("Proposal and commit lengths must share a batch dimension.")
|
| 108 |
+
positions = torch.arange(proposal.shape[1], device=proposal.device).unsqueeze(0)
|
| 109 |
+
committed = positions.lt(commit_lengths[:, None])
|
| 110 |
+
stop_token_ids = (
|
| 111 |
+
(int(token_id),)
|
| 112 |
+
if isinstance(token_id, int)
|
| 113 |
+
else tuple(dict.fromkeys(int(value) for value in token_id))
|
| 114 |
+
)
|
| 115 |
+
if not stop_token_ids:
|
| 116 |
+
raise ValueError("At least one stop token ID is required.")
|
| 117 |
+
matches = proposal.eq(stop_token_ids[0])
|
| 118 |
+
for value in stop_token_ids[1:]:
|
| 119 |
+
matches |= proposal.eq(value)
|
| 120 |
+
matches &= committed
|
| 121 |
+
sentinel = torch.full_like(positions, proposal.shape[1])
|
| 122 |
+
first = torch.where(matches, positions, sentinel).min(dim=-1).values
|
| 123 |
+
clipped = torch.where(first.lt(proposal.shape[1]), first + 1, commit_lengths)
|
| 124 |
+
return torch.minimum(clipped, commit_lengths)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def bounded_prefix_failure_commit_lengths(
|
| 128 |
+
committed_token_ids: torch.LongTensor,
|
| 129 |
+
failure_rate: torch.Tensor,
|
| 130 |
+
*,
|
| 131 |
+
failure_budget: float,
|
| 132 |
+
remaining_lengths: torch.LongTensor,
|
| 133 |
+
stop_token_id: int | Sequence[int],
|
| 134 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 135 |
+
) -> torch.LongTensor:
|
| 136 |
+
"""Apply length and stop-token bounds to the shared failure-rate policy."""
|
| 137 |
+
|
| 138 |
+
if committed_token_ids.shape != failure_rate.shape:
|
| 139 |
+
raise ValueError("Committed token IDs and failure rate must share [batch, canvas].")
|
| 140 |
+
if remaining_lengths.shape != committed_token_ids.shape[:1]:
|
| 141 |
+
raise ValueError("Remaining lengths must have shape [batch].")
|
| 142 |
+
commit_lengths = prefix_failure_commit_lengths(
|
| 143 |
+
failure_rate,
|
| 144 |
+
failure_budget=failure_budget,
|
| 145 |
+
valid_mask=valid_mask,
|
| 146 |
+
)
|
| 147 |
+
commit_lengths = torch.minimum(commit_lengths, remaining_lengths.clamp_min(0))
|
| 148 |
+
return first_committed_token_lengths(
|
| 149 |
+
committed_token_ids,
|
| 150 |
+
commit_lengths,
|
| 151 |
+
stop_token_id,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def select_commit_lengths(
|
| 156 |
+
sampled_token_ids: torch.LongTensor,
|
| 157 |
+
normal_failure_rate: torch.Tensor,
|
| 158 |
+
previous_failure_rate: torch.Tensor,
|
| 159 |
+
greedy_token_ids: torch.LongTensor,
|
| 160 |
+
jump_failure_rate: torch.Tensor,
|
| 161 |
+
*,
|
| 162 |
+
ponder_steps: torch.Tensor,
|
| 163 |
+
stagnation_steps: torch.Tensor,
|
| 164 |
+
active_rows: torch.BoolTensor,
|
| 165 |
+
remaining_lengths: torch.LongTensor,
|
| 166 |
+
failure_budget: float,
|
| 167 |
+
jump_failure_budget: float,
|
| 168 |
+
stop_token_id: int | Sequence[int],
|
| 169 |
+
max_ponder_steps: int,
|
| 170 |
+
stagnation_threshold: int,
|
| 171 |
+
min_progress: float,
|
| 172 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 173 |
+
) -> CommitPolicyDecision:
|
| 174 |
+
"""Use normal sampled commits and a fixed-budget greedy JUMP.
|
| 175 |
+
|
| 176 |
+
Progress is measured from the signed change in fused failure rate over the
|
| 177 |
+
frontier region (the union of the previous and current commit prefixes plus
|
| 178 |
+
one blocking position), not from raw confidence/entropy deltas.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
if not (
|
| 182 |
+
sampled_token_ids.shape
|
| 183 |
+
== normal_failure_rate.shape
|
| 184 |
+
== previous_failure_rate.shape
|
| 185 |
+
== greedy_token_ids.shape
|
| 186 |
+
== jump_failure_rate.shape
|
| 187 |
+
):
|
| 188 |
+
raise ValueError("Sampled and greedy statistics must share [batch, canvas].")
|
| 189 |
+
|
| 190 |
+
normal = bounded_prefix_failure_commit_lengths(
|
| 191 |
+
sampled_token_ids,
|
| 192 |
+
normal_failure_rate,
|
| 193 |
+
failure_budget=failure_budget,
|
| 194 |
+
remaining_lengths=remaining_lengths,
|
| 195 |
+
stop_token_id=stop_token_id,
|
| 196 |
+
valid_mask=valid_mask,
|
| 197 |
+
)
|
| 198 |
+
canvas_length = normal_failure_rate.shape[1]
|
| 199 |
+
previous_prefix_length = prefix_failure_commit_lengths(
|
| 200 |
+
previous_failure_rate,
|
| 201 |
+
failure_budget=failure_budget,
|
| 202 |
+
valid_mask=valid_mask,
|
| 203 |
+
)
|
| 204 |
+
frontier_length = torch.maximum(previous_prefix_length, normal) + 1
|
| 205 |
+
valid_lengths = (
|
| 206 |
+
valid_mask.long().sum(dim=-1)
|
| 207 |
+
if valid_mask is not None
|
| 208 |
+
else torch.full_like(frontier_length, canvas_length)
|
| 209 |
+
)
|
| 210 |
+
frontier_length = torch.minimum(frontier_length, valid_lengths)
|
| 211 |
+
positions = torch.arange(canvas_length, device=normal_failure_rate.device)[None, :]
|
| 212 |
+
progress_mask = positions < frontier_length[:, None]
|
| 213 |
+
if valid_mask is not None:
|
| 214 |
+
progress_mask &= valid_mask
|
| 215 |
+
progress_mask &= active_rows[:, None]
|
| 216 |
+
signed_improvement = (
|
| 217 |
+
previous_failure_rate.float() - normal_failure_rate.float()
|
| 218 |
+
)
|
| 219 |
+
weights = progress_mask.float()
|
| 220 |
+
progress = (
|
| 221 |
+
signed_improvement * weights
|
| 222 |
+
).sum(dim=-1) / weights.sum(dim=-1).clamp_min(1.0)
|
| 223 |
+
next_ponder, next_stagnation = advance_trajectory_clocks(
|
| 224 |
+
ponder_steps,
|
| 225 |
+
stagnation_steps,
|
| 226 |
+
commit_lengths=normal,
|
| 227 |
+
active_rows=active_rows,
|
| 228 |
+
progress_scores=progress,
|
| 229 |
+
min_progress=min_progress,
|
| 230 |
+
)
|
| 231 |
+
jump_rows = normal.eq(0) & active_rows & should_force_trajectory_jump(
|
| 232 |
+
next_ponder,
|
| 233 |
+
next_stagnation,
|
| 234 |
+
max_ponder_steps=max_ponder_steps,
|
| 235 |
+
stagnation_threshold=stagnation_threshold,
|
| 236 |
+
)
|
| 237 |
+
jump_commit = bounded_prefix_failure_commit_lengths(
|
| 238 |
+
greedy_token_ids,
|
| 239 |
+
jump_failure_rate,
|
| 240 |
+
failure_budget=jump_failure_budget,
|
| 241 |
+
remaining_lengths=remaining_lengths,
|
| 242 |
+
stop_token_id=stop_token_id,
|
| 243 |
+
valid_mask=valid_mask,
|
| 244 |
+
)
|
| 245 |
+
committed = torch.where(jump_rows, jump_commit, normal)
|
| 246 |
+
commit_token_ids = torch.where(
|
| 247 |
+
jump_rows[:, None],
|
| 248 |
+
greedy_token_ids,
|
| 249 |
+
sampled_token_ids,
|
| 250 |
+
)
|
| 251 |
+
committed = first_committed_token_lengths(
|
| 252 |
+
commit_token_ids,
|
| 253 |
+
committed,
|
| 254 |
+
stop_token_id,
|
| 255 |
+
)
|
| 256 |
+
committed = torch.where(active_rows, committed, 0)
|
| 257 |
+
jump_rows &= committed.gt(0)
|
| 258 |
+
next_ponder = torch.where(
|
| 259 |
+
committed.gt(0),
|
| 260 |
+
0,
|
| 261 |
+
next_ponder,
|
| 262 |
+
).to(torch.int32)
|
| 263 |
+
next_stagnation = torch.where(
|
| 264 |
+
committed.gt(0),
|
| 265 |
+
0,
|
| 266 |
+
next_stagnation,
|
| 267 |
+
).to(torch.int32)
|
| 268 |
+
return CommitPolicyDecision(
|
| 269 |
+
normal_lengths=normal,
|
| 270 |
+
commit_lengths=committed,
|
| 271 |
+
commit_token_ids=commit_token_ids,
|
| 272 |
+
jump_rows=jump_rows,
|
| 273 |
+
ponder_steps=next_ponder,
|
| 274 |
+
stagnation_steps=next_stagnation,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
__all__ = [
|
| 279 |
+
"CommitPolicyDecision",
|
| 280 |
+
"FUSED_ENTROPY_WEIGHT",
|
| 281 |
+
"bounded_prefix_failure_commit_lengths",
|
| 282 |
+
"first_committed_token_lengths",
|
| 283 |
+
"fused_commit_confidence",
|
| 284 |
+
"fused_commit_failure_rate",
|
| 285 |
+
"prefix_failure_commit_lengths",
|
| 286 |
+
"select_commit_lengths",
|
| 287 |
+
]
|
config.json
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"ModilifyMk1ForBlockDiffusion"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration_modilify_mk1.ModilifyMk1Config",
|
| 7 |
+
"AutoModel": "modeling_modilify_mk1.ModilifyMk1Model",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_modilify_mk1.ModilifyMk1ForBlockDiffusion",
|
| 9 |
+
"AutoModelForMultimodalLM": "modeling_modilify_mk1.ModilifyMk1ForBlockDiffusion"
|
| 10 |
+
},
|
| 11 |
+
"boi_token_id": 255999,
|
| 12 |
+
"bos_token_id": 2,
|
| 13 |
+
"canvas_length": 256,
|
| 14 |
+
"commit_failure_budget": 0.2,
|
| 15 |
+
"denoise_temperature": 0.8,
|
| 16 |
+
"dtype": "bfloat16",
|
| 17 |
+
"eoi_token_id": 258882,
|
| 18 |
+
"eos_token_id": [
|
| 19 |
+
1,
|
| 20 |
+
106
|
| 21 |
+
],
|
| 22 |
+
"fused_entropy_weight": 0.5,
|
| 23 |
+
"image_token_id": 258880,
|
| 24 |
+
"initializer_range": 0.02,
|
| 25 |
+
"jump_failure_budget": 2.0,
|
| 26 |
+
"jump_on_no_progress_after": 12,
|
| 27 |
+
"latent_dim": 1536,
|
| 28 |
+
"latent_dropout": 0.0,
|
| 29 |
+
"latent_local_attention_window": 128,
|
| 30 |
+
"latent_memory_slots": 64,
|
| 31 |
+
"latent_num_heads": 16,
|
| 32 |
+
"latent_num_layers": 4,
|
| 33 |
+
"max_ponder_steps": 64,
|
| 34 |
+
"min_trajectory_progress": 0.005,
|
| 35 |
+
"model_type": "modilify_mk1",
|
| 36 |
+
"pad_token_id": 0,
|
| 37 |
+
"text_config": {
|
| 38 |
+
"attention_bias": false,
|
| 39 |
+
"attention_dropout": 0.0,
|
| 40 |
+
"bos_token_id": 2,
|
| 41 |
+
"dtype": "bfloat16",
|
| 42 |
+
"eos_token_id": 1,
|
| 43 |
+
"final_logit_softcapping": 30.0,
|
| 44 |
+
"global_head_dim": 512,
|
| 45 |
+
"head_dim": 256,
|
| 46 |
+
"hidden_activation": "gelu_pytorch_tanh",
|
| 47 |
+
"hidden_size": 2816,
|
| 48 |
+
"initializer_range": 0.02,
|
| 49 |
+
"intermediate_size": 2112,
|
| 50 |
+
"layer_types": [
|
| 51 |
+
"sliding_attention",
|
| 52 |
+
"sliding_attention",
|
| 53 |
+
"sliding_attention",
|
| 54 |
+
"sliding_attention",
|
| 55 |
+
"sliding_attention",
|
| 56 |
+
"full_attention",
|
| 57 |
+
"sliding_attention",
|
| 58 |
+
"sliding_attention",
|
| 59 |
+
"sliding_attention",
|
| 60 |
+
"sliding_attention",
|
| 61 |
+
"sliding_attention",
|
| 62 |
+
"full_attention",
|
| 63 |
+
"sliding_attention",
|
| 64 |
+
"sliding_attention",
|
| 65 |
+
"sliding_attention",
|
| 66 |
+
"sliding_attention",
|
| 67 |
+
"sliding_attention",
|
| 68 |
+
"full_attention",
|
| 69 |
+
"sliding_attention",
|
| 70 |
+
"sliding_attention",
|
| 71 |
+
"sliding_attention",
|
| 72 |
+
"sliding_attention",
|
| 73 |
+
"sliding_attention",
|
| 74 |
+
"full_attention",
|
| 75 |
+
"sliding_attention",
|
| 76 |
+
"sliding_attention",
|
| 77 |
+
"sliding_attention",
|
| 78 |
+
"sliding_attention",
|
| 79 |
+
"sliding_attention",
|
| 80 |
+
"full_attention"
|
| 81 |
+
],
|
| 82 |
+
"max_position_embeddings": 262144,
|
| 83 |
+
"model_type": "modilify_mk1_text",
|
| 84 |
+
"moe_intermediate_size": 704,
|
| 85 |
+
"num_attention_heads": 16,
|
| 86 |
+
"num_experts": 128,
|
| 87 |
+
"num_global_key_value_heads": 2,
|
| 88 |
+
"num_hidden_layers": 30,
|
| 89 |
+
"num_key_value_heads": 8,
|
| 90 |
+
"pad_token_id": 0,
|
| 91 |
+
"rms_norm_eps": 1e-06,
|
| 92 |
+
"rope_parameters": {
|
| 93 |
+
"full_attention": {
|
| 94 |
+
"partial_rotary_factor": 0.25,
|
| 95 |
+
"rope_theta": 1000000.0,
|
| 96 |
+
"rope_type": "proportional"
|
| 97 |
+
},
|
| 98 |
+
"sliding_attention": {
|
| 99 |
+
"rope_theta": 10000.0,
|
| 100 |
+
"rope_type": "default"
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
"sliding_window": 1024,
|
| 104 |
+
"tie_word_embeddings": true,
|
| 105 |
+
"top_k_experts": 8,
|
| 106 |
+
"use_bidirectional_attention": "vision",
|
| 107 |
+
"vocab_size": 262144
|
| 108 |
+
},
|
| 109 |
+
"tie_word_embeddings": true,
|
| 110 |
+
"transformers_version": "5.14.1",
|
| 111 |
+
"turn_end_token_id": 106,
|
| 112 |
+
"vision_config": {
|
| 113 |
+
"_name_or_path": "",
|
| 114 |
+
"architectures": null,
|
| 115 |
+
"attention_bias": false,
|
| 116 |
+
"attention_dropout": 0.0,
|
| 117 |
+
"chunk_size_feed_forward": 0,
|
| 118 |
+
"default_output_length": 280,
|
| 119 |
+
"dtype": "bfloat16",
|
| 120 |
+
"global_head_dim": 72,
|
| 121 |
+
"head_dim": 72,
|
| 122 |
+
"hidden_activation": "gelu_pytorch_tanh",
|
| 123 |
+
"hidden_size": 1152,
|
| 124 |
+
"id2label": {
|
| 125 |
+
"0": "LABEL_0",
|
| 126 |
+
"1": "LABEL_1"
|
| 127 |
+
},
|
| 128 |
+
"initializer_range": 0.02,
|
| 129 |
+
"intermediate_size": 4304,
|
| 130 |
+
"is_encoder_decoder": false,
|
| 131 |
+
"label2id": {
|
| 132 |
+
"LABEL_0": 0,
|
| 133 |
+
"LABEL_1": 1
|
| 134 |
+
},
|
| 135 |
+
"max_position_embeddings": 131072,
|
| 136 |
+
"model_type": "gemma4_vision",
|
| 137 |
+
"num_attention_heads": 16,
|
| 138 |
+
"num_hidden_layers": 27,
|
| 139 |
+
"num_key_value_heads": 16,
|
| 140 |
+
"output_attentions": false,
|
| 141 |
+
"output_hidden_states": false,
|
| 142 |
+
"patch_size": 16,
|
| 143 |
+
"pooling_kernel_size": 3,
|
| 144 |
+
"position_embedding_size": 10240,
|
| 145 |
+
"problem_type": null,
|
| 146 |
+
"return_dict": true,
|
| 147 |
+
"rms_norm_eps": 1e-06,
|
| 148 |
+
"rope_parameters": {
|
| 149 |
+
"rope_theta": 100.0,
|
| 150 |
+
"rope_type": "default"
|
| 151 |
+
},
|
| 152 |
+
"standardize": true,
|
| 153 |
+
"use_clipped_linears": false
|
| 154 |
+
},
|
| 155 |
+
"vocab_chunk_size": 65536
|
| 156 |
+
}
|
configuration_modilify_mk1.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
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| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Configuration classes for Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from transformers.models.diffusion_gemma import (
|
| 11 |
+
DiffusionGemmaConfig,
|
| 12 |
+
DiffusionGemmaTextConfig,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ModilifyMk1TextConfig(DiffusionGemmaTextConfig):
|
| 17 |
+
"""Text configuration for the Modilify Mk1 decoder.
|
| 18 |
+
|
| 19 |
+
This class preserves the standard DiffusionGemma text schema while giving
|
| 20 |
+
the exported model an independent, stable model type.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
model_type = "modilify_mk1_text"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ModilifyMk1Config(DiffusionGemmaConfig):
|
| 27 |
+
"""Serializable multimodal inference configuration for Modilify Mk1.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
text_config: DiffusionGemma text configuration or its serialized form.
|
| 31 |
+
vision_config: Gemma 4 vision configuration or its serialized form.
|
| 32 |
+
denoise_temperature: Sampling temperature used at every denoising step.
|
| 33 |
+
commit_failure_budget: Maximum cumulative failure risk for normal commits.
|
| 34 |
+
fused_entropy_weight: Multiplicative entropy penalty coefficient.
|
| 35 |
+
jump_failure_budget: Maximum cumulative failure risk for forced jumps.
|
| 36 |
+
vocab_chunk_size: Vocabulary projection planning size recorded with the
|
| 37 |
+
model. Inference uses standard PyTorch tensor operations.
|
| 38 |
+
latent_dim: Width of the recurrent latent state.
|
| 39 |
+
latent_memory_slots: Number of persistent latent memory slots.
|
| 40 |
+
latent_num_layers: Number of latent Transformer blocks.
|
| 41 |
+
latent_num_heads: Number of latent attention heads.
|
| 42 |
+
latent_local_attention_window: Local token-attention radius.
|
| 43 |
+
latent_dropout: Latent Transformer dropout probability.
|
| 44 |
+
jump_on_no_progress_after: Stagnation steps before a forced jump.
|
| 45 |
+
max_ponder_steps: Maximum denoising iterations per requested token.
|
| 46 |
+
min_trajectory_progress: Minimum fused-risk improvement counted as progress.
|
| 47 |
+
turn_end_token_id: Native Gemma turn terminator.
|
| 48 |
+
kwargs: Standard DiffusionGemma configuration values.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
model_type = "modilify_mk1"
|
| 52 |
+
sub_configs = {
|
| 53 |
+
"text_config": ModilifyMk1TextConfig,
|
| 54 |
+
**{
|
| 55 |
+
key: value
|
| 56 |
+
for key, value in DiffusionGemmaConfig.sub_configs.items()
|
| 57 |
+
if key != "text_config"
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
text_config: (
|
| 64 |
+
ModilifyMk1TextConfig
|
| 65 |
+
| DiffusionGemmaTextConfig
|
| 66 |
+
| dict[str, Any]
|
| 67 |
+
| None
|
| 68 |
+
) = None,
|
| 69 |
+
vision_config: Any | dict[str, Any] | None = None,
|
| 70 |
+
*,
|
| 71 |
+
denoise_temperature: float = 0.8,
|
| 72 |
+
commit_failure_budget: float = 0.2,
|
| 73 |
+
fused_entropy_weight: float = 0.5,
|
| 74 |
+
jump_failure_budget: float = 2.0,
|
| 75 |
+
vocab_chunk_size: int = 65_536,
|
| 76 |
+
latent_dim: int = 1536,
|
| 77 |
+
latent_memory_slots: int = 64,
|
| 78 |
+
latent_num_layers: int = 4,
|
| 79 |
+
latent_num_heads: int = 16,
|
| 80 |
+
latent_local_attention_window: int = 128,
|
| 81 |
+
latent_dropout: float = 0.0,
|
| 82 |
+
jump_on_no_progress_after: int = 12,
|
| 83 |
+
max_ponder_steps: int = 64,
|
| 84 |
+
min_trajectory_progress: float = 0.005,
|
| 85 |
+
turn_end_token_id: int = 106,
|
| 86 |
+
**kwargs: Any,
|
| 87 |
+
) -> None:
|
| 88 |
+
kwargs.pop("model_type", None)
|
| 89 |
+
if isinstance(text_config, DiffusionGemmaTextConfig):
|
| 90 |
+
text_payload = text_config.to_dict()
|
| 91 |
+
text_payload.pop("model_type", None)
|
| 92 |
+
text_config = ModilifyMk1TextConfig(**text_payload)
|
| 93 |
+
elif isinstance(text_config, dict):
|
| 94 |
+
text_payload = dict(text_config)
|
| 95 |
+
text_payload.pop("model_type", None)
|
| 96 |
+
text_config = ModilifyMk1TextConfig(**text_payload)
|
| 97 |
+
elif text_config is None:
|
| 98 |
+
text_config = ModilifyMk1TextConfig()
|
| 99 |
+
|
| 100 |
+
self.denoise_temperature = float(denoise_temperature)
|
| 101 |
+
self.commit_failure_budget = float(commit_failure_budget)
|
| 102 |
+
self.fused_entropy_weight = float(fused_entropy_weight)
|
| 103 |
+
self.jump_failure_budget = float(jump_failure_budget)
|
| 104 |
+
self.vocab_chunk_size = int(vocab_chunk_size)
|
| 105 |
+
self.latent_dim = int(latent_dim)
|
| 106 |
+
self.latent_memory_slots = int(latent_memory_slots)
|
| 107 |
+
self.latent_num_layers = int(latent_num_layers)
|
| 108 |
+
self.latent_num_heads = int(latent_num_heads)
|
| 109 |
+
self.latent_local_attention_window = int(latent_local_attention_window)
|
| 110 |
+
self.latent_dropout = float(latent_dropout)
|
| 111 |
+
self.jump_on_no_progress_after = int(jump_on_no_progress_after)
|
| 112 |
+
self.max_ponder_steps = int(max_ponder_steps)
|
| 113 |
+
self.min_trajectory_progress = float(min_trajectory_progress)
|
| 114 |
+
self.turn_end_token_id = int(turn_end_token_id)
|
| 115 |
+
super().__init__(
|
| 116 |
+
text_config=text_config,
|
| 117 |
+
vision_config=vision_config,
|
| 118 |
+
**kwargs,
|
| 119 |
+
)
|
| 120 |
+
self.model_type = type(self).model_type
|
| 121 |
+
if not hasattr(self, "eos_token_id"):
|
| 122 |
+
self.eos_token_id = self.text_config.eos_token_id
|
| 123 |
+
if not hasattr(self, "pad_token_id"):
|
| 124 |
+
self.pad_token_id = self.text_config.pad_token_id
|
| 125 |
+
if not hasattr(self, "bos_token_id"):
|
| 126 |
+
self.bos_token_id = self.text_config.bos_token_id
|
| 127 |
+
self._validate_modilify()
|
| 128 |
+
|
| 129 |
+
def _validate_modilify(self) -> None:
|
| 130 |
+
"""Validate inference-only extension values."""
|
| 131 |
+
|
| 132 |
+
policy_values = (
|
| 133 |
+
self.denoise_temperature,
|
| 134 |
+
self.commit_failure_budget,
|
| 135 |
+
self.fused_entropy_weight,
|
| 136 |
+
self.jump_failure_budget,
|
| 137 |
+
self.min_trajectory_progress,
|
| 138 |
+
)
|
| 139 |
+
if any(not math.isfinite(value) for value in policy_values):
|
| 140 |
+
raise ValueError("Modilify Mk1 policy values must be finite.")
|
| 141 |
+
positive = (
|
| 142 |
+
self.denoise_temperature,
|
| 143 |
+
self.commit_failure_budget,
|
| 144 |
+
self.jump_failure_budget,
|
| 145 |
+
self.vocab_chunk_size,
|
| 146 |
+
self.latent_dim,
|
| 147 |
+
self.latent_memory_slots,
|
| 148 |
+
self.latent_num_layers,
|
| 149 |
+
self.latent_num_heads,
|
| 150 |
+
self.latent_local_attention_window,
|
| 151 |
+
self.jump_on_no_progress_after,
|
| 152 |
+
self.max_ponder_steps,
|
| 153 |
+
)
|
| 154 |
+
if any(value <= 0 for value in positive):
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"Modilify Mk1 dimensions, budgets, and intervals must be positive."
|
| 157 |
+
)
|
| 158 |
+
if self.fused_entropy_weight < 0:
|
| 159 |
+
raise ValueError("`fused_entropy_weight` must be non-negative.")
|
| 160 |
+
if self.latent_dim % self.latent_num_heads:
|
| 161 |
+
raise ValueError("`latent_dim` must be divisible by `latent_num_heads`.")
|
| 162 |
+
if not 0.0 <= self.latent_dropout < 1.0:
|
| 163 |
+
raise ValueError("`latent_dropout` must be in [0, 1).")
|
| 164 |
+
if self.min_trajectory_progress < 0:
|
| 165 |
+
raise ValueError("`min_trajectory_progress` must be non-negative.")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
__all__ = ["ModilifyMk1Config", "ModilifyMk1TextConfig"]
|
generation_config.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"confidence_threshold": null,
|
| 3 |
+
"denoise_temperature": 0.8,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
1,
|
| 6 |
+
106
|
| 7 |
+
],
|
| 8 |
+
"max_denoising_steps": null,
|
| 9 |
+
"max_new_tokens": 256,
|
| 10 |
+
"one_token_per_denoise_step": false,
|
| 11 |
+
"return_dict_in_generate": true,
|
| 12 |
+
"sampler_config": null,
|
| 13 |
+
"stability_threshold": null,
|
| 14 |
+
"t_max": 0.8,
|
| 15 |
+
"t_min": 0.8,
|
| 16 |
+
"transformers_version": "5.14.1",
|
| 17 |
+
"turn_end_token_id": 106
|
| 18 |
+
}
|
generation_modilify_mk1.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Rolling generation for latent-memory Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
+
import math
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from transformers.cache_utils import Cache
|
| 13 |
+
from transformers.generation import LogitsProcessorList
|
| 14 |
+
from transformers.generation.streamers import BaseStreamer
|
| 15 |
+
from transformers.modeling_outputs import ModelOutput
|
| 16 |
+
|
| 17 |
+
from transformers.models.diffusion_gemma import (
|
| 18 |
+
DiffusionGemmaGenerationConfig,
|
| 19 |
+
DiffusionGemmaGenerationMixin,
|
| 20 |
+
)
|
| 21 |
+
from .commit_policy import fused_commit_failure_rate, select_commit_lengths
|
| 22 |
+
from .latent_deliberation import LatentDeliberationState
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ModilifyMk1GenerationConfig(DiffusionGemmaGenerationConfig):
|
| 26 |
+
"""Generation controls for the Modilify Mk1 commit policy.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
turn_end_token_id: Token that closes a native Gemma turn.
|
| 30 |
+
denoise_temperature: Sampling temperature used for every canvas step.
|
| 31 |
+
kwargs: Standard DiffusionGemma generation arguments.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
*,
|
| 37 |
+
turn_end_token_id: int | None = None,
|
| 38 |
+
denoise_temperature: float = 0.8,
|
| 39 |
+
**kwargs: Any,
|
| 40 |
+
) -> None:
|
| 41 |
+
self.turn_end_token_id = turn_end_token_id
|
| 42 |
+
self.denoise_temperature = float(denoise_temperature)
|
| 43 |
+
kwargs.pop("one_token_per_denoise_step", None)
|
| 44 |
+
kwargs["t_min"] = self.denoise_temperature
|
| 45 |
+
kwargs["t_max"] = self.denoise_temperature
|
| 46 |
+
super().__init__(**kwargs)
|
| 47 |
+
self.one_token_per_denoise_step = False
|
| 48 |
+
|
| 49 |
+
def update(self, **kwargs: Any) -> dict[str, Any]:
|
| 50 |
+
"""Apply standard generation overrides and one temperature override."""
|
| 51 |
+
|
| 52 |
+
if "denoise_temperature" in kwargs:
|
| 53 |
+
self.denoise_temperature = float(kwargs.pop("denoise_temperature"))
|
| 54 |
+
kwargs["t_min"] = self.denoise_temperature
|
| 55 |
+
kwargs["t_max"] = self.denoise_temperature
|
| 56 |
+
unused = super().update(**kwargs)
|
| 57 |
+
self.one_token_per_denoise_step = False
|
| 58 |
+
self.t_min = self.denoise_temperature
|
| 59 |
+
self.t_max = self.denoise_temperature
|
| 60 |
+
return unused
|
| 61 |
+
|
| 62 |
+
def validate(self, **kwargs: Any) -> None:
|
| 63 |
+
"""Validate fixed-temperature generation values.
|
| 64 |
+
|
| 65 |
+
DiffusionGemma's parent validator requires a non-empty temperature
|
| 66 |
+
interval. Modilify Mk1 intentionally uses one fixed temperature, so the
|
| 67 |
+
equivalent ``t_min == t_max`` configuration is validated here.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
del kwargs
|
| 71 |
+
if (
|
| 72 |
+
not math.isfinite(self.denoise_temperature)
|
| 73 |
+
or self.denoise_temperature <= 0
|
| 74 |
+
):
|
| 75 |
+
raise ValueError("`denoise_temperature` must be positive.")
|
| 76 |
+
if self.max_denoising_steps is not None and (
|
| 77 |
+
not isinstance(self.max_denoising_steps, int)
|
| 78 |
+
or self.max_denoising_steps <= 0
|
| 79 |
+
):
|
| 80 |
+
raise ValueError("`max_denoising_steps` must be a positive integer.")
|
| 81 |
+
if self.turn_end_token_id is not None and (
|
| 82 |
+
not isinstance(self.turn_end_token_id, int) or self.turn_end_token_id < 0
|
| 83 |
+
):
|
| 84 |
+
raise ValueError("`turn_end_token_id` must be a non-negative integer.")
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def from_model_config(cls, model_config: Any) -> "ModilifyMk1GenerationConfig":
|
| 88 |
+
"""Build generation defaults from a model configuration."""
|
| 89 |
+
|
| 90 |
+
return cls(
|
| 91 |
+
turn_end_token_id=model_config.turn_end_token_id,
|
| 92 |
+
denoise_temperature=model_config.denoise_temperature,
|
| 93 |
+
eos_token_id=getattr(
|
| 94 |
+
model_config,
|
| 95 |
+
"eos_token_id",
|
| 96 |
+
model_config.text_config.eos_token_id,
|
| 97 |
+
),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def _get_default_generation_params() -> dict[str, object]:
|
| 102 |
+
"""Return defaults with no inherited entropy/readiness commit controls."""
|
| 103 |
+
|
| 104 |
+
return {
|
| 105 |
+
"max_new_tokens": 256,
|
| 106 |
+
"max_denoising_steps": 48,
|
| 107 |
+
"t_min": 0.8,
|
| 108 |
+
"t_max": 0.8,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class ModilifyMk1GenerationOutput(ModelOutput):
|
| 114 |
+
"""Structured result returned by rolling block-diffusion generation."""
|
| 115 |
+
|
| 116 |
+
sequences: torch.LongTensor
|
| 117 |
+
generated_lengths: torch.LongTensor | None = None
|
| 118 |
+
tokens_per_forward: torch.FloatTensor | None = None
|
| 119 |
+
past_key_values: Cache | None = None
|
| 120 |
+
stop_reason: str | tuple[str, ...] | None = None
|
| 121 |
+
committed_tokens: int | torch.LongTensor | None = None
|
| 122 |
+
denoise_steps: int | torch.LongTensor | None = None
|
| 123 |
+
no_progress_steps: int | torch.LongTensor | None = None
|
| 124 |
+
jump_count: int | torch.LongTensor | None = None
|
| 125 |
+
forced_jump_bad_count: int | torch.LongTensor | None = None
|
| 126 |
+
heavy_forward_count: int | torch.LongTensor | None = None
|
| 127 |
+
latent_context_update_count: int | torch.LongTensor | None = None
|
| 128 |
+
average_commit_len: float | torch.FloatTensor | None = None
|
| 129 |
+
state_shift_count: int | torch.LongTensor | None = None
|
| 130 |
+
latent_memory_norm: float | torch.FloatTensor | None = None
|
| 131 |
+
state_retention_score: float | torch.FloatTensor | None = None
|
| 132 |
+
logits: None = None
|
| 133 |
+
scores: None = None
|
| 134 |
+
hidden_states: None = None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dataclass
|
| 138 |
+
class _RollingState:
|
| 139 |
+
"""All real iterative state; no vocabulary-sized tensor is retained."""
|
| 140 |
+
|
| 141 |
+
canvas: torch.LongTensor
|
| 142 |
+
confidence: torch.FloatTensor
|
| 143 |
+
entropy: torch.FloatTensor
|
| 144 |
+
age: torch.IntTensor
|
| 145 |
+
latent_state: LatentDeliberationState
|
| 146 |
+
history_hidden_state: torch.FloatTensor | None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _retain_denoise_proposals(proposal: torch.LongTensor) -> torch.LongTensor:
|
| 150 |
+
"""Keep every latest denoise token; confidence controls commit, not writeback."""
|
| 151 |
+
if proposal.ndim != 2:
|
| 152 |
+
raise ValueError("Denoise proposals must have shape [batch, canvas].")
|
| 153 |
+
return proposal.clone()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class _NoiseCanvasSampler:
|
| 157 |
+
"""Uniform diffusion noise source with no commit-policy responsibilities."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, *, canvas_length: int, vocab_size: int) -> None:
|
| 160 |
+
self.canvas_length = int(canvas_length)
|
| 161 |
+
self.vocab_size = int(vocab_size)
|
| 162 |
+
self.initial_entropy = math.log(self.vocab_size)
|
| 163 |
+
|
| 164 |
+
def initialize_canvas(
|
| 165 |
+
self,
|
| 166 |
+
batch_size: int,
|
| 167 |
+
device: torch.device,
|
| 168 |
+
) -> torch.LongTensor:
|
| 169 |
+
"""Sample a uniformly random starting canvas.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
batch_size: Number of canvases to create.
|
| 173 |
+
device: Device on which token IDs are allocated.
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
Random token IDs with shape ``[batch_size, canvas_length]``.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
return torch.randint(
|
| 180 |
+
self.vocab_size,
|
| 181 |
+
(batch_size, self.canvas_length),
|
| 182 |
+
device=device,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class ModilifyMk1GenerationMixin(DiffusionGemmaGenerationMixin):
|
| 187 |
+
"""Transformers-compatible rolling latent-deliberation generator."""
|
| 188 |
+
|
| 189 |
+
def _prepare_sampler(
|
| 190 |
+
self,
|
| 191 |
+
generation_config: ModilifyMk1GenerationConfig,
|
| 192 |
+
canvas_length: int | None = None,
|
| 193 |
+
) -> _NoiseCanvasSampler:
|
| 194 |
+
del generation_config
|
| 195 |
+
return _NoiseCanvasSampler(
|
| 196 |
+
canvas_length=canvas_length or self.config.canvas_length,
|
| 197 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
@staticmethod
|
| 201 |
+
def _shift_state_rows(
|
| 202 |
+
state: _RollingState,
|
| 203 |
+
commit_lengths: torch.LongTensor,
|
| 204 |
+
sampler: _NoiseCanvasSampler,
|
| 205 |
+
) -> _RollingState:
|
| 206 |
+
"""Shift every rolling row by its own committed prefix length."""
|
| 207 |
+
|
| 208 |
+
batch_size, canvas_length = state.canvas.shape
|
| 209 |
+
if commit_lengths.shape != (batch_size,):
|
| 210 |
+
raise ValueError("Commit lengths must have shape [batch].")
|
| 211 |
+
if not bool(commit_lengths.gt(0).any()):
|
| 212 |
+
return state
|
| 213 |
+
positions = torch.arange(canvas_length, device=state.canvas.device)[None, :]
|
| 214 |
+
source = positions + commit_lengths[:, None]
|
| 215 |
+
retained = source.lt(canvas_length)
|
| 216 |
+
|
| 217 |
+
def shift(value: torch.Tensor, fill_value: float | int = 0) -> torch.Tensor:
|
| 218 |
+
index = source.clamp_max(canvas_length - 1)
|
| 219 |
+
index = index.view(
|
| 220 |
+
batch_size, canvas_length, *([1] * (value.ndim - 2))
|
| 221 |
+
).expand_as(value)
|
| 222 |
+
gathered = value.gather(1, index)
|
| 223 |
+
mask = retained.view(
|
| 224 |
+
batch_size, canvas_length, *([1] * (value.ndim - 2))
|
| 225 |
+
)
|
| 226 |
+
fill = torch.as_tensor(fill_value, device=value.device, dtype=value.dtype)
|
| 227 |
+
return torch.where(mask, gathered, fill)
|
| 228 |
+
|
| 229 |
+
tail = sampler.initialize_canvas(batch_size, state.canvas.device)
|
| 230 |
+
canvas = torch.cat((state.canvas, tail), dim=1).gather(1, source)
|
| 231 |
+
unknown_entropy = float(sampler.initial_entropy)
|
| 232 |
+
latent = state.latent_state
|
| 233 |
+
committed = commit_lengths.gt(0)
|
| 234 |
+
shifted_latent = LatentDeliberationState(
|
| 235 |
+
token_latents=shift(latent.token_latents),
|
| 236 |
+
memory_slots=latent.memory_slots.clone(),
|
| 237 |
+
confidence=shift(latent.confidence),
|
| 238 |
+
entropy=shift(latent.entropy, unknown_entropy),
|
| 239 |
+
age=shift(latent.age),
|
| 240 |
+
token_changed=shift(latent.token_changed),
|
| 241 |
+
confidence_delta=shift(latent.confidence_delta),
|
| 242 |
+
entropy_delta=shift(latent.entropy_delta),
|
| 243 |
+
ponder_steps=torch.where(
|
| 244 |
+
committed, torch.zeros_like(latent.ponder_steps), latent.ponder_steps
|
| 245 |
+
),
|
| 246 |
+
stagnation_steps=torch.where(
|
| 247 |
+
committed, torch.zeros_like(latent.stagnation_steps), latent.stagnation_steps
|
| 248 |
+
),
|
| 249 |
+
)
|
| 250 |
+
return _RollingState(
|
| 251 |
+
canvas=canvas,
|
| 252 |
+
confidence=shift(state.confidence),
|
| 253 |
+
entropy=shift(state.entropy, unknown_entropy),
|
| 254 |
+
age=shift(state.age),
|
| 255 |
+
latent_state=shifted_latent,
|
| 256 |
+
history_hidden_state=(
|
| 257 |
+
None
|
| 258 |
+
if state.history_hidden_state is None
|
| 259 |
+
else shift(state.history_hidden_state)
|
| 260 |
+
),
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def _merge_state_rows(
|
| 265 |
+
previous: _RollingState,
|
| 266 |
+
updated: _RollingState,
|
| 267 |
+
update_mask: torch.BoolTensor,
|
| 268 |
+
) -> _RollingState:
|
| 269 |
+
"""Advance active rows while leaving completed rows unchanged."""
|
| 270 |
+
|
| 271 |
+
def choose(old: torch.Tensor, new: torch.Tensor) -> torch.Tensor:
|
| 272 |
+
mask = update_mask.view(
|
| 273 |
+
update_mask.shape[0],
|
| 274 |
+
*([1] * (old.ndim - 1)),
|
| 275 |
+
)
|
| 276 |
+
return torch.where(mask, new, old)
|
| 277 |
+
|
| 278 |
+
old_latent = previous.latent_state
|
| 279 |
+
new_latent = updated.latent_state
|
| 280 |
+
latent = LatentDeliberationState(
|
| 281 |
+
token_latents=choose(
|
| 282 |
+
old_latent.token_latents,
|
| 283 |
+
new_latent.token_latents,
|
| 284 |
+
),
|
| 285 |
+
memory_slots=choose(old_latent.memory_slots, new_latent.memory_slots),
|
| 286 |
+
confidence=choose(old_latent.confidence, new_latent.confidence),
|
| 287 |
+
entropy=choose(old_latent.entropy, new_latent.entropy),
|
| 288 |
+
age=choose(old_latent.age, new_latent.age),
|
| 289 |
+
token_changed=choose(
|
| 290 |
+
old_latent.token_changed,
|
| 291 |
+
new_latent.token_changed,
|
| 292 |
+
),
|
| 293 |
+
confidence_delta=choose(
|
| 294 |
+
old_latent.confidence_delta,
|
| 295 |
+
new_latent.confidence_delta,
|
| 296 |
+
),
|
| 297 |
+
entropy_delta=choose(
|
| 298 |
+
old_latent.entropy_delta,
|
| 299 |
+
new_latent.entropy_delta,
|
| 300 |
+
),
|
| 301 |
+
ponder_steps=choose(
|
| 302 |
+
old_latent.ponder_steps,
|
| 303 |
+
new_latent.ponder_steps,
|
| 304 |
+
),
|
| 305 |
+
stagnation_steps=choose(
|
| 306 |
+
old_latent.stagnation_steps,
|
| 307 |
+
new_latent.stagnation_steps,
|
| 308 |
+
),
|
| 309 |
+
)
|
| 310 |
+
history = previous.history_hidden_state
|
| 311 |
+
if updated.history_hidden_state is not None:
|
| 312 |
+
history = (
|
| 313 |
+
updated.history_hidden_state
|
| 314 |
+
if history is None
|
| 315 |
+
else choose(history, updated.history_hidden_state)
|
| 316 |
+
)
|
| 317 |
+
return _RollingState(
|
| 318 |
+
canvas=choose(previous.canvas, updated.canvas),
|
| 319 |
+
confidence=choose(previous.confidence, updated.confidence),
|
| 320 |
+
entropy=choose(previous.entropy, updated.entropy),
|
| 321 |
+
age=choose(previous.age, updated.age),
|
| 322 |
+
latent_state=latent,
|
| 323 |
+
history_hidden_state=history,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
@torch.inference_mode()
|
| 327 |
+
def generate(
|
| 328 |
+
self,
|
| 329 |
+
input_ids: torch.LongTensor | None = None,
|
| 330 |
+
past_key_values: Cache | None = None,
|
| 331 |
+
streamer: BaseStreamer | None = None,
|
| 332 |
+
generation_config: ModilifyMk1GenerationConfig | None = None,
|
| 333 |
+
logits_processor: LogitsProcessorList | None = None,
|
| 334 |
+
**kwargs,
|
| 335 |
+
) -> ModilifyMk1GenerationOutput:
|
| 336 |
+
"""Generate one or more responses with rolling block diffusion.
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
input_ids: Tokenized prompts with shape ``[batch, sequence]``.
|
| 340 |
+
past_key_values: Optional existing encoder cache.
|
| 341 |
+
streamer: Optional standard Transformers token streamer.
|
| 342 |
+
generation_config: Generation limits and token IDs.
|
| 343 |
+
logits_processor: Unsupported custom logits processors.
|
| 344 |
+
**kwargs: Standard multimodal encoder inputs and generation values.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
Generated sequences and diffusion diagnostics.
|
| 348 |
+
|
| 349 |
+
Raises:
|
| 350 |
+
ValueError: If inputs are invalid or unsupported logits processing
|
| 351 |
+
is requested.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
generation_config, model_kwargs = self._prepare_generation_config(
|
| 355 |
+
generation_config,
|
| 356 |
+
**kwargs,
|
| 357 |
+
)
|
| 358 |
+
if input_ids is None or input_ids.ndim != 2 or input_ids.shape[0] < 1:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
"Modilify Mk1 generation requires `input_ids` with shape "
|
| 361 |
+
"[batch, sequence]."
|
| 362 |
+
)
|
| 363 |
+
if logits_processor:
|
| 364 |
+
raise ValueError(
|
| 365 |
+
"Modilify Mk1 samples the configured fixed-temperature distribution "
|
| 366 |
+
"and does not accept custom logits processors."
|
| 367 |
+
)
|
| 368 |
+
batch_size, input_width = input_ids.shape
|
| 369 |
+
if batch_size > 1 and streamer is not None:
|
| 370 |
+
raise ValueError("Streamers currently support batch size 1 only.")
|
| 371 |
+
if batch_size > 1 and past_key_values is not None:
|
| 372 |
+
raise ValueError("Batched generation requires a fresh KV cache.")
|
| 373 |
+
device = input_ids.device
|
| 374 |
+
dtype = self.model.decoder.embed_tokens.weight.dtype
|
| 375 |
+
canvas_length = self.config.canvas_length
|
| 376 |
+
cached_length = (
|
| 377 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 378 |
+
)
|
| 379 |
+
_, max_new_tokens = self._prepare_generated_length(
|
| 380 |
+
generation_config, cached_length + input_width
|
| 381 |
+
)
|
| 382 |
+
max_iterations = max(1, max_new_tokens * self.config.max_ponder_steps)
|
| 383 |
+
if past_key_values is None:
|
| 384 |
+
past_key_values = self._prepare_cache_for_generation(
|
| 385 |
+
generation_config,
|
| 386 |
+
batch_size=batch_size,
|
| 387 |
+
# Ragged rows append dense masked blocks. If different rows
|
| 388 |
+
# advance in different iterations, physical cache width can
|
| 389 |
+
# reach the sum of all per-row generation limits.
|
| 390 |
+
max_length=input_width + batch_size * max_new_tokens,
|
| 391 |
+
)
|
| 392 |
+
expected_mask_width = cached_length + input_width
|
| 393 |
+
cache_attention_mask = model_kwargs.pop(
|
| 394 |
+
"attention_mask",
|
| 395 |
+
torch.ones(
|
| 396 |
+
batch_size, expected_mask_width, dtype=torch.bool, device=device
|
| 397 |
+
),
|
| 398 |
+
).bool()
|
| 399 |
+
if cache_attention_mask.shape != (batch_size, expected_mask_width):
|
| 400 |
+
raise ValueError(
|
| 401 |
+
"`attention_mask` must have shape [batch, cached_length + sequence]."
|
| 402 |
+
)
|
| 403 |
+
provided_position_ids = model_kwargs.pop("position_ids", None)
|
| 404 |
+
if provided_position_ids is not None:
|
| 405 |
+
if provided_position_ids.shape != input_ids.shape:
|
| 406 |
+
raise ValueError("`position_ids` must have the same shape as `input_ids`.")
|
| 407 |
+
prompt_positions = provided_position_ids.to(device=device, dtype=torch.int32)
|
| 408 |
+
elif cached_length:
|
| 409 |
+
prompt_positions = torch.arange(
|
| 410 |
+
cached_length,
|
| 411 |
+
cached_length + input_width,
|
| 412 |
+
device=device,
|
| 413 |
+
dtype=torch.int32,
|
| 414 |
+
).unsqueeze(0)
|
| 415 |
+
else:
|
| 416 |
+
input_mask = cache_attention_mask[:, -input_width:]
|
| 417 |
+
prompt_positions = (
|
| 418 |
+
input_mask.long()
|
| 419 |
+
.cumsum(dim=-1)
|
| 420 |
+
.sub(1)
|
| 421 |
+
.clamp_min(0)
|
| 422 |
+
.to(torch.int32)
|
| 423 |
+
)
|
| 424 |
+
logical_lengths = cache_attention_mask.long().sum(dim=-1)
|
| 425 |
+
if input_width:
|
| 426 |
+
encoder_keys = ("pixel_values", "mm_token_type_ids", "image_position_ids")
|
| 427 |
+
encoder_kwargs = {
|
| 428 |
+
key: model_kwargs.pop(key)
|
| 429 |
+
for key in encoder_keys
|
| 430 |
+
if key in model_kwargs
|
| 431 |
+
}
|
| 432 |
+
past_key_values = self.model.encoder(
|
| 433 |
+
input_ids=input_ids,
|
| 434 |
+
attention_mask=cache_attention_mask,
|
| 435 |
+
past_key_values=past_key_values,
|
| 436 |
+
position_ids=prompt_positions,
|
| 437 |
+
**encoder_kwargs,
|
| 438 |
+
).past_key_values
|
| 439 |
+
|
| 440 |
+
sampler = self._prepare_sampler(generation_config, canvas_length)
|
| 441 |
+
latent = LatentDeliberationState.empty(
|
| 442 |
+
batch_size=batch_size,
|
| 443 |
+
canvas_length=canvas_length,
|
| 444 |
+
latent_dim=self.config.latent_dim,
|
| 445 |
+
memory_slots=self.config.latent_memory_slots,
|
| 446 |
+
device=device,
|
| 447 |
+
dtype=dtype,
|
| 448 |
+
)
|
| 449 |
+
state = _RollingState(
|
| 450 |
+
canvas=sampler.initialize_canvas(batch_size, device),
|
| 451 |
+
confidence=torch.zeros(
|
| 452 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 453 |
+
),
|
| 454 |
+
entropy=torch.full(
|
| 455 |
+
(batch_size, canvas_length),
|
| 456 |
+
math.log(self.config.text_config.vocab_size),
|
| 457 |
+
device=device,
|
| 458 |
+
dtype=torch.float32,
|
| 459 |
+
),
|
| 460 |
+
age=torch.zeros(
|
| 461 |
+
batch_size, canvas_length, device=device, dtype=torch.int32
|
| 462 |
+
),
|
| 463 |
+
latent_state=latent,
|
| 464 |
+
history_hidden_state=None,
|
| 465 |
+
)
|
| 466 |
+
turn_end = (
|
| 467 |
+
self.config.turn_end_token_id
|
| 468 |
+
if generation_config.turn_end_token_id is None
|
| 469 |
+
else generation_config.turn_end_token_id
|
| 470 |
+
)
|
| 471 |
+
configured_eos = generation_config.eos_token_id
|
| 472 |
+
if configured_eos is None:
|
| 473 |
+
configured_eos = self.config.eos_token_id
|
| 474 |
+
if isinstance(configured_eos, int):
|
| 475 |
+
configured_eos = [configured_eos]
|
| 476 |
+
stop_token_ids = tuple(
|
| 477 |
+
dict.fromkeys((int(turn_end), *(int(value) for value in configured_eos or ())))
|
| 478 |
+
)
|
| 479 |
+
pad_token_id = generation_config.pad_token_id
|
| 480 |
+
if pad_token_id is None:
|
| 481 |
+
pad_token_id = getattr(self.config, "pad_token_id", None)
|
| 482 |
+
if isinstance(pad_token_id, (list, tuple)):
|
| 483 |
+
pad_token_id = pad_token_id[0]
|
| 484 |
+
pad_token_id = int(0 if pad_token_id is None else pad_token_id)
|
| 485 |
+
generated = torch.full(
|
| 486 |
+
(batch_size, max_new_tokens),
|
| 487 |
+
pad_token_id,
|
| 488 |
+
dtype=input_ids.dtype,
|
| 489 |
+
device=device,
|
| 490 |
+
)
|
| 491 |
+
committed = torch.zeros(batch_size, dtype=torch.long, device=device)
|
| 492 |
+
denoise_steps = torch.zeros_like(committed)
|
| 493 |
+
jumps = torch.zeros_like(committed)
|
| 494 |
+
forced_jump_tokens = torch.zeros_like(committed)
|
| 495 |
+
shifts = torch.zeros_like(committed)
|
| 496 |
+
retention_scores = torch.zeros(batch_size, dtype=torch.float32, device=device)
|
| 497 |
+
stop_codes = torch.zeros_like(committed)
|
| 498 |
+
active_rows = torch.ones(batch_size, dtype=torch.bool, device=device)
|
| 499 |
+
canvas_positions = torch.arange(canvas_length, device=device)[None, :]
|
| 500 |
+
if streamer is not None:
|
| 501 |
+
streamer.put(input_ids.cpu())
|
| 502 |
+
|
| 503 |
+
while bool(active_rows.any()):
|
| 504 |
+
decoder_positions = (
|
| 505 |
+
logical_lengths[:, None]
|
| 506 |
+
+ canvas_positions
|
| 507 |
+
).to(torch.int32)
|
| 508 |
+
denoise_steps += active_rows.long()
|
| 509 |
+
decoder_attention_mask = torch.cat(
|
| 510 |
+
(
|
| 511 |
+
cache_attention_mask,
|
| 512 |
+
torch.ones(
|
| 513 |
+
batch_size,
|
| 514 |
+
canvas_length,
|
| 515 |
+
dtype=torch.bool,
|
| 516 |
+
device=device,
|
| 517 |
+
),
|
| 518 |
+
),
|
| 519 |
+
dim=-1,
|
| 520 |
+
)
|
| 521 |
+
output = self(
|
| 522 |
+
input_ids=None,
|
| 523 |
+
past_key_values=past_key_values,
|
| 524 |
+
decoder_input_ids=state.canvas,
|
| 525 |
+
previous_confidence=state.confidence,
|
| 526 |
+
previous_entropy=state.entropy,
|
| 527 |
+
token_age=state.age,
|
| 528 |
+
latent_state=state.latent_state,
|
| 529 |
+
history_hidden_state=state.history_hidden_state,
|
| 530 |
+
decoder_position_ids=decoder_positions,
|
| 531 |
+
decoder_read_cache=True,
|
| 532 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 533 |
+
return_proposal_statistics=True,
|
| 534 |
+
denoise_temperature=generation_config.denoise_temperature,
|
| 535 |
+
**model_kwargs,
|
| 536 |
+
)
|
| 537 |
+
if any(
|
| 538 |
+
value is None
|
| 539 |
+
for value in (
|
| 540 |
+
output.proposal,
|
| 541 |
+
output.proposal_confidence,
|
| 542 |
+
output.token_entropy,
|
| 543 |
+
output.greedy_proposal,
|
| 544 |
+
output.greedy_confidence,
|
| 545 |
+
)
|
| 546 |
+
):
|
| 547 |
+
raise RuntimeError("Model forward did not return proposal statistics.")
|
| 548 |
+
proposal = output.proposal
|
| 549 |
+
proposal_confidence = output.proposal_confidence
|
| 550 |
+
token_entropy = output.token_entropy
|
| 551 |
+
greedy_proposal = output.greedy_proposal
|
| 552 |
+
greedy_confidence = output.greedy_confidence
|
| 553 |
+
next_canvas = _retain_denoise_proposals(proposal)
|
| 554 |
+
next_confidence = proposal_confidence.float()
|
| 555 |
+
next_latent = replace(
|
| 556 |
+
output.next_latent_state,
|
| 557 |
+
confidence=next_confidence.detach().float(),
|
| 558 |
+
entropy=token_entropy.detach().float(),
|
| 559 |
+
age=state.age + 1,
|
| 560 |
+
token_changed=next_canvas.ne(state.canvas).detach().float(),
|
| 561 |
+
confidence_delta=next_confidence.detach().float() - state.confidence,
|
| 562 |
+
entropy_delta=token_entropy.detach().float() - state.entropy,
|
| 563 |
+
)
|
| 564 |
+
next_state = _RollingState(
|
| 565 |
+
canvas=next_canvas,
|
| 566 |
+
confidence=next_confidence,
|
| 567 |
+
entropy=token_entropy,
|
| 568 |
+
age=state.age + 1,
|
| 569 |
+
latent_state=next_latent,
|
| 570 |
+
history_hidden_state=output.heavy_hidden_state,
|
| 571 |
+
)
|
| 572 |
+
next_state = self._merge_state_rows(state, next_state, active_rows)
|
| 573 |
+
remaining = torch.tensor(
|
| 574 |
+
max_new_tokens, device=device, dtype=torch.long
|
| 575 |
+
).sub(committed)
|
| 576 |
+
normal_failure_rate = fused_commit_failure_rate(
|
| 577 |
+
proposal_confidence, token_entropy,
|
| 578 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 579 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 580 |
+
)
|
| 581 |
+
jump_failure_rate = fused_commit_failure_rate(
|
| 582 |
+
greedy_confidence, token_entropy,
|
| 583 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 584 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 585 |
+
)
|
| 586 |
+
previous_failure_rate = fused_commit_failure_rate(
|
| 587 |
+
state.confidence, state.entropy,
|
| 588 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 589 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 590 |
+
)
|
| 591 |
+
policy_decision = select_commit_lengths(
|
| 592 |
+
sampled_token_ids=proposal,
|
| 593 |
+
normal_failure_rate=normal_failure_rate,
|
| 594 |
+
previous_failure_rate=previous_failure_rate,
|
| 595 |
+
greedy_token_ids=greedy_proposal,
|
| 596 |
+
jump_failure_rate=jump_failure_rate,
|
| 597 |
+
ponder_steps=state.latent_state.ponder_steps,
|
| 598 |
+
stagnation_steps=state.latent_state.stagnation_steps,
|
| 599 |
+
active_rows=active_rows,
|
| 600 |
+
remaining_lengths=remaining,
|
| 601 |
+
failure_budget=self.config.commit_failure_budget,
|
| 602 |
+
jump_failure_budget=self.config.jump_failure_budget,
|
| 603 |
+
stop_token_id=stop_token_ids,
|
| 604 |
+
max_ponder_steps=self.config.max_ponder_steps,
|
| 605 |
+
stagnation_threshold=self.config.jump_on_no_progress_after,
|
| 606 |
+
min_progress=self.config.min_trajectory_progress,
|
| 607 |
+
)
|
| 608 |
+
next_ponder = policy_decision.ponder_steps
|
| 609 |
+
next_stagnation = policy_decision.stagnation_steps
|
| 610 |
+
commit_lengths = policy_decision.commit_lengths
|
| 611 |
+
jump_rows = policy_decision.jump_rows
|
| 612 |
+
jumps += jump_rows.long()
|
| 613 |
+
forced_jump_tokens += torch.where(
|
| 614 |
+
jump_rows, commit_lengths, torch.zeros_like(commit_lengths)
|
| 615 |
+
)
|
| 616 |
+
commit_positions = canvas_positions.lt(commit_lengths[:, None])
|
| 617 |
+
if bool(jump_rows.any()):
|
| 618 |
+
next_state = replace(
|
| 619 |
+
next_state,
|
| 620 |
+
canvas=torch.where(
|
| 621 |
+
commit_positions & jump_rows[:, None],
|
| 622 |
+
policy_decision.commit_token_ids,
|
| 623 |
+
next_state.canvas,
|
| 624 |
+
),
|
| 625 |
+
)
|
| 626 |
+
next_state = replace(
|
| 627 |
+
next_state,
|
| 628 |
+
latent_state=replace(
|
| 629 |
+
next_state.latent_state,
|
| 630 |
+
ponder_steps=next_ponder,
|
| 631 |
+
stagnation_steps=next_stagnation,
|
| 632 |
+
),
|
| 633 |
+
)
|
| 634 |
+
commit_token_ids = policy_decision.commit_token_ids
|
| 635 |
+
before = committed.clone()
|
| 636 |
+
write_rows = torch.arange(batch_size, device=device)[:, None].expand_as(
|
| 637 |
+
commit_token_ids
|
| 638 |
+
)
|
| 639 |
+
write_positions = before[:, None] + canvas_positions
|
| 640 |
+
generated[
|
| 641 |
+
write_rows[commit_positions], write_positions[commit_positions]
|
| 642 |
+
] = commit_token_ids[commit_positions]
|
| 643 |
+
|
| 644 |
+
commit_width = int(commit_lengths.max())
|
| 645 |
+
if commit_width:
|
| 646 |
+
block_mask = torch.arange(commit_width, device=device)[None, :].lt(
|
| 647 |
+
commit_lengths[:, None]
|
| 648 |
+
)
|
| 649 |
+
committed_block = torch.where(
|
| 650 |
+
block_mask,
|
| 651 |
+
commit_token_ids[:, :commit_width],
|
| 652 |
+
torch.full(
|
| 653 |
+
(batch_size, commit_width),
|
| 654 |
+
pad_token_id,
|
| 655 |
+
device=device,
|
| 656 |
+
dtype=input_ids.dtype,
|
| 657 |
+
),
|
| 658 |
+
)
|
| 659 |
+
block_positions = (
|
| 660 |
+
logical_lengths[:, None]
|
| 661 |
+
+ canvas_positions[:, :commit_width]
|
| 662 |
+
).to(torch.int32)
|
| 663 |
+
block_positions = torch.where(
|
| 664 |
+
block_mask, block_positions, torch.zeros_like(block_positions)
|
| 665 |
+
)
|
| 666 |
+
cache_attention_mask = torch.cat(
|
| 667 |
+
(cache_attention_mask, block_mask), dim=-1
|
| 668 |
+
)
|
| 669 |
+
past_key_values = self.model.encoder(
|
| 670 |
+
input_ids=committed_block,
|
| 671 |
+
attention_mask=cache_attention_mask,
|
| 672 |
+
past_key_values=past_key_values,
|
| 673 |
+
position_ids=block_positions,
|
| 674 |
+
).past_key_values
|
| 675 |
+
if streamer is not None:
|
| 676 |
+
streamer.put(committed_block.cpu())
|
| 677 |
+
committed += commit_lengths
|
| 678 |
+
logical_lengths += commit_lengths
|
| 679 |
+
committed_rows = commit_lengths.gt(0)
|
| 680 |
+
shifts += committed_rows.long()
|
| 681 |
+
shifted = self._shift_state_rows(next_state, commit_lengths, sampler)
|
| 682 |
+
retention_scores += committed_rows.float()
|
| 683 |
+
state = shifted
|
| 684 |
+
|
| 685 |
+
turn_hits = (
|
| 686 |
+
commit_token_ids.eq(turn_end) & commit_positions
|
| 687 |
+
).any(dim=-1)
|
| 688 |
+
eos_hits = torch.zeros_like(turn_hits)
|
| 689 |
+
for token_id in stop_token_ids:
|
| 690 |
+
if token_id != turn_end:
|
| 691 |
+
eos_hits |= (
|
| 692 |
+
commit_token_ids.eq(token_id) & commit_positions
|
| 693 |
+
).any(dim=-1)
|
| 694 |
+
stop_codes = torch.where(
|
| 695 |
+
stop_codes.eq(0) & turn_hits,
|
| 696 |
+
torch.ones_like(stop_codes),
|
| 697 |
+
stop_codes,
|
| 698 |
+
)
|
| 699 |
+
stop_codes = torch.where(
|
| 700 |
+
stop_codes.eq(0) & eos_hits,
|
| 701 |
+
torch.full_like(stop_codes, 2),
|
| 702 |
+
stop_codes,
|
| 703 |
+
)
|
| 704 |
+
stop_codes = torch.where(
|
| 705 |
+
stop_codes.eq(0) & committed.ge(max_new_tokens),
|
| 706 |
+
torch.full_like(stop_codes, 3),
|
| 707 |
+
stop_codes,
|
| 708 |
+
)
|
| 709 |
+
if generation_config.max_denoising_steps is not None:
|
| 710 |
+
stop_codes = torch.where(
|
| 711 |
+
stop_codes.eq(0)
|
| 712 |
+
& denoise_steps.ge(generation_config.max_denoising_steps),
|
| 713 |
+
torch.full_like(stop_codes, 4),
|
| 714 |
+
stop_codes,
|
| 715 |
+
)
|
| 716 |
+
stop_codes = torch.where(
|
| 717 |
+
stop_codes.eq(0) & denoise_steps.ge(max_iterations),
|
| 718 |
+
torch.full_like(stop_codes, 5),
|
| 719 |
+
stop_codes,
|
| 720 |
+
)
|
| 721 |
+
active_rows = stop_codes.eq(0)
|
| 722 |
+
|
| 723 |
+
output_width = int(committed.max())
|
| 724 |
+
sequences = torch.cat((input_ids, generated[:, :output_width]), dim=-1)
|
| 725 |
+
if streamer is not None:
|
| 726 |
+
streamer.end()
|
| 727 |
+
reason_names = {
|
| 728 |
+
1: "turn_end",
|
| 729 |
+
2: "eos",
|
| 730 |
+
3: "max_new_tokens",
|
| 731 |
+
4: "max_denoising_steps",
|
| 732 |
+
5: "episode_watchdog",
|
| 733 |
+
}
|
| 734 |
+
stop_reasons = tuple(
|
| 735 |
+
reason_names.get(code, "unknown")
|
| 736 |
+
for code in stop_codes.detach().cpu().tolist()
|
| 737 |
+
)
|
| 738 |
+
tokens_per_forward = committed.float() / denoise_steps.clamp_min(1).float()
|
| 739 |
+
average_commit_len = committed.float() / shifts.clamp_min(1).float()
|
| 740 |
+
latent_memory_norm = (
|
| 741 |
+
state.latent_state.memory_slots.float().norm(dim=-1).mean(dim=-1)
|
| 742 |
+
)
|
| 743 |
+
state_retention_score = retention_scores / shifts.clamp_min(1).float()
|
| 744 |
+
|
| 745 |
+
def scalar_or_tensor(
|
| 746 |
+
value: torch.Tensor,
|
| 747 |
+
*,
|
| 748 |
+
floating: bool = False,
|
| 749 |
+
) -> int | float | torch.Tensor:
|
| 750 |
+
if batch_size > 1:
|
| 751 |
+
return value
|
| 752 |
+
item = value[0].item()
|
| 753 |
+
return float(item) if floating else int(item)
|
| 754 |
+
|
| 755 |
+
return ModilifyMk1GenerationOutput(
|
| 756 |
+
sequences=sequences,
|
| 757 |
+
generated_lengths=committed.clone(),
|
| 758 |
+
tokens_per_forward=tokens_per_forward,
|
| 759 |
+
past_key_values=past_key_values,
|
| 760 |
+
stop_reason=stop_reasons[0] if batch_size == 1 else stop_reasons,
|
| 761 |
+
committed_tokens=scalar_or_tensor(committed),
|
| 762 |
+
denoise_steps=scalar_or_tensor(denoise_steps),
|
| 763 |
+
no_progress_steps=scalar_or_tensor(state.latent_state.stagnation_steps),
|
| 764 |
+
jump_count=scalar_or_tensor(jumps),
|
| 765 |
+
forced_jump_bad_count=scalar_or_tensor(forced_jump_tokens),
|
| 766 |
+
heavy_forward_count=scalar_or_tensor(denoise_steps),
|
| 767 |
+
latent_context_update_count=scalar_or_tensor(denoise_steps),
|
| 768 |
+
average_commit_len=scalar_or_tensor(average_commit_len, floating=True),
|
| 769 |
+
state_shift_count=scalar_or_tensor(shifts),
|
| 770 |
+
latent_memory_norm=scalar_or_tensor(latent_memory_norm, floating=True),
|
| 771 |
+
state_retention_score=scalar_or_tensor(
|
| 772 |
+
state_retention_score,
|
| 773 |
+
floating=True,
|
| 774 |
+
),
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
__all__ = [
|
| 779 |
+
"ModilifyMk1GenerationConfig",
|
| 780 |
+
"ModilifyMk1GenerationMixin",
|
| 781 |
+
"ModilifyMk1GenerationOutput",
|
| 782 |
+
]
|
latent_deliberation.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Fixed-shape latent deliberation state for Modilify Mk1 decoding.
|
| 4 |
+
|
| 5 |
+
The state deliberately contains no vocabulary-sized tensors. Keeping the
|
| 6 |
+
per-canvas information in a small latent space prevents iterative diffusion
|
| 7 |
+
rollouts from retaining one logits/probability allocation per denoise pass.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch import nn
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class LatentDeliberationState:
|
| 20 |
+
"""Persistent, fixed-size state for one or more canvas episodes."""
|
| 21 |
+
|
| 22 |
+
token_latents: torch.Tensor
|
| 23 |
+
memory_slots: torch.Tensor
|
| 24 |
+
confidence: torch.Tensor
|
| 25 |
+
entropy: torch.Tensor
|
| 26 |
+
age: torch.Tensor
|
| 27 |
+
token_changed: torch.Tensor
|
| 28 |
+
confidence_delta: torch.Tensor
|
| 29 |
+
entropy_delta: torch.Tensor
|
| 30 |
+
ponder_steps: torch.Tensor
|
| 31 |
+
stagnation_steps: torch.Tensor
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def empty(
|
| 35 |
+
cls,
|
| 36 |
+
*,
|
| 37 |
+
batch_size: int,
|
| 38 |
+
canvas_length: int,
|
| 39 |
+
latent_dim: int,
|
| 40 |
+
memory_slots: int,
|
| 41 |
+
device: torch.device,
|
| 42 |
+
dtype: torch.dtype,
|
| 43 |
+
) -> "LatentDeliberationState":
|
| 44 |
+
"""Create a zero-initialized recurrent state.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
batch_size: Number of independent sequences.
|
| 48 |
+
canvas_length: Number of rolling canvas positions.
|
| 49 |
+
latent_dim: Width of each latent token and memory slot.
|
| 50 |
+
memory_slots: Number of persistent memory slots.
|
| 51 |
+
device: Allocation device.
|
| 52 |
+
dtype: Floating-point dtype for latent tensors.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
A zero-initialized state with integer progress clocks.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
return cls(
|
| 59 |
+
token_latents=torch.zeros(
|
| 60 |
+
batch_size, canvas_length, latent_dim, device=device, dtype=dtype
|
| 61 |
+
),
|
| 62 |
+
memory_slots=torch.zeros(
|
| 63 |
+
batch_size, memory_slots, latent_dim, device=device, dtype=dtype
|
| 64 |
+
),
|
| 65 |
+
confidence=torch.zeros(
|
| 66 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 67 |
+
),
|
| 68 |
+
entropy=torch.zeros(
|
| 69 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 70 |
+
),
|
| 71 |
+
age=torch.zeros(
|
| 72 |
+
batch_size, canvas_length, device=device, dtype=torch.int32
|
| 73 |
+
),
|
| 74 |
+
token_changed=torch.zeros(
|
| 75 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 76 |
+
),
|
| 77 |
+
confidence_delta=torch.zeros(
|
| 78 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 79 |
+
),
|
| 80 |
+
entropy_delta=torch.zeros(
|
| 81 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 82 |
+
),
|
| 83 |
+
ponder_steps=torch.zeros(batch_size, device=device, dtype=torch.int32),
|
| 84 |
+
stagnation_steps=torch.zeros(batch_size, device=device, dtype=torch.int32),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def advance_trajectory_clocks(
|
| 89 |
+
ponder_steps: torch.Tensor,
|
| 90 |
+
stagnation_steps: torch.Tensor,
|
| 91 |
+
*,
|
| 92 |
+
commit_lengths: torch.LongTensor,
|
| 93 |
+
active_rows: torch.BoolTensor,
|
| 94 |
+
progress_scores: torch.Tensor,
|
| 95 |
+
min_progress: float,
|
| 96 |
+
) -> tuple[torch.IntTensor, torch.IntTensor]:
|
| 97 |
+
"""Advance useful-ponder and true-stagnation clocks for each row.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
ponder_steps: Total waiting steps for each row.
|
| 101 |
+
stagnation_steps: Consecutive non-improving steps for each row.
|
| 102 |
+
commit_lengths: Number of committed tokens for each row.
|
| 103 |
+
active_rows: Rows that are still generating.
|
| 104 |
+
progress_scores: Signed fused-risk improvements.
|
| 105 |
+
min_progress: Smallest improvement that resets stagnation.
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
Updated ponder and stagnation counters.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
if min_progress < 0:
|
| 112 |
+
raise ValueError("`min_progress` must be non-negative.")
|
| 113 |
+
if not (
|
| 114 |
+
ponder_steps.shape == stagnation_steps.shape == commit_lengths.shape
|
| 115 |
+
== active_rows.shape == progress_scores.shape
|
| 116 |
+
):
|
| 117 |
+
raise ValueError("Trajectory clock inputs must share shape [batch].")
|
| 118 |
+
committed = commit_lengths.gt(0)
|
| 119 |
+
waiting = active_rows & ~committed
|
| 120 |
+
improving = progress_scores.ge(min_progress)
|
| 121 |
+
next_ponder = torch.where(
|
| 122 |
+
committed, torch.zeros_like(ponder_steps), ponder_steps + waiting.to(torch.int32)
|
| 123 |
+
)
|
| 124 |
+
next_stagnation = torch.where(
|
| 125 |
+
committed,
|
| 126 |
+
torch.zeros_like(stagnation_steps),
|
| 127 |
+
torch.where(
|
| 128 |
+
waiting & improving,
|
| 129 |
+
torch.zeros_like(stagnation_steps),
|
| 130 |
+
stagnation_steps + waiting.to(torch.int32),
|
| 131 |
+
),
|
| 132 |
+
)
|
| 133 |
+
return next_ponder.to(torch.int32), next_stagnation.to(torch.int32)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def should_force_trajectory_jump(
|
| 137 |
+
ponder_steps: torch.Tensor,
|
| 138 |
+
stagnation_steps: torch.Tensor,
|
| 139 |
+
*,
|
| 140 |
+
max_ponder_steps: int,
|
| 141 |
+
stagnation_threshold: int,
|
| 142 |
+
) -> torch.BoolTensor:
|
| 143 |
+
"""Return rows that exhausted either inference progress clock.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
ponder_steps: Total waiting steps for each row.
|
| 147 |
+
stagnation_steps: Consecutive non-improving steps for each row.
|
| 148 |
+
max_ponder_steps: Maximum allowed waiting steps.
|
| 149 |
+
stagnation_threshold: Maximum consecutive stagnation steps.
|
| 150 |
+
|
| 151 |
+
Returns:
|
| 152 |
+
Boolean mask selecting rows that must use a forced jump.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
if max_ponder_steps <= 0 or stagnation_threshold <= 0:
|
| 156 |
+
raise ValueError("Trajectory jump limits must be positive.")
|
| 157 |
+
return ponder_steps.ge(max_ponder_steps) | stagnation_steps.ge(stagnation_threshold)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class _TemporalTransformerCell(nn.Module):
|
| 161 |
+
"""One-step recurrent token update with fixed-slot memory attention."""
|
| 162 |
+
|
| 163 |
+
def __init__(
|
| 164 |
+
self, latent_dim: int, num_heads: int, dropout: float,
|
| 165 |
+
local_attention_window: int,
|
| 166 |
+
) -> None:
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.state_norm = nn.LayerNorm(latent_dim)
|
| 169 |
+
self.observation_norm = nn.LayerNorm(latent_dim)
|
| 170 |
+
# A slot's learned identity is only used for attention addressing. The
|
| 171 |
+
# recurrent state itself remains pure memory content so commit shifts
|
| 172 |
+
# cannot accidentally write positional identity into persistent state.
|
| 173 |
+
self.memory_address_norm = nn.LayerNorm(latent_dim)
|
| 174 |
+
self.memory_value_norm = nn.LayerNorm(latent_dim)
|
| 175 |
+
self.temporal_update = nn.Linear(2 * latent_dim, 2 * latent_dim)
|
| 176 |
+
self.local_attention = nn.MultiheadAttention(
|
| 177 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 178 |
+
)
|
| 179 |
+
self.local_attention_window = local_attention_window
|
| 180 |
+
self.register_buffer("_local_attention_mask", torch.empty(0), persistent=False)
|
| 181 |
+
self.token_memory_attention = nn.MultiheadAttention(
|
| 182 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 183 |
+
)
|
| 184 |
+
self.memory_token_attention = nn.MultiheadAttention(
|
| 185 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 186 |
+
)
|
| 187 |
+
self.token_ff_norm = nn.LayerNorm(latent_dim)
|
| 188 |
+
self.memory_ff_norm = nn.LayerNorm(latent_dim)
|
| 189 |
+
self.stored_token_norm = nn.LayerNorm(latent_dim)
|
| 190 |
+
self.stored_memory_norm = nn.LayerNorm(latent_dim)
|
| 191 |
+
expansion = latent_dim * 4
|
| 192 |
+
self.token_ff = nn.Sequential(
|
| 193 |
+
nn.Linear(latent_dim, expansion),
|
| 194 |
+
nn.SiLU(),
|
| 195 |
+
nn.Linear(expansion, latent_dim),
|
| 196 |
+
)
|
| 197 |
+
self.memory_ff = nn.Sequential(
|
| 198 |
+
nn.Linear(latent_dim, expansion),
|
| 199 |
+
nn.SiLU(),
|
| 200 |
+
nn.Linear(expansion, latent_dim),
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
previous_tokens: torch.Tensor,
|
| 206 |
+
observation: torch.Tensor,
|
| 207 |
+
memory: torch.Tensor,
|
| 208 |
+
memory_slot_identity: torch.Tensor,
|
| 209 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 210 |
+
gate_logits, candidate = self.temporal_update(
|
| 211 |
+
torch.cat(
|
| 212 |
+
(self.state_norm(previous_tokens), self.observation_norm(observation)),
|
| 213 |
+
dim=-1,
|
| 214 |
+
)
|
| 215 |
+
).chunk(2, dim=-1)
|
| 216 |
+
gate = torch.sigmoid(gate_logits)
|
| 217 |
+
tokens = gate * previous_tokens + (1.0 - gate) * torch.nn.functional.silu(candidate)
|
| 218 |
+
if (
|
| 219 |
+
self._local_attention_mask.shape != (tokens.shape[1], tokens.shape[1])
|
| 220 |
+
or self._local_attention_mask.device != tokens.device
|
| 221 |
+
or self._local_attention_mask.dtype != tokens.dtype
|
| 222 |
+
):
|
| 223 |
+
positions = torch.arange(tokens.shape[1], device=tokens.device)
|
| 224 |
+
allowed = (
|
| 225 |
+
positions[:, None] - positions[None, :]
|
| 226 |
+
).abs() < self.local_attention_window
|
| 227 |
+
self._local_attention_mask = torch.zeros(
|
| 228 |
+
tokens.shape[1], tokens.shape[1], device=tokens.device, dtype=tokens.dtype
|
| 229 |
+
).masked_fill(~allowed, torch.finfo(tokens.dtype).min)
|
| 230 |
+
local_update, _ = self.local_attention(
|
| 231 |
+
self.state_norm(tokens), self.state_norm(tokens), self.state_norm(tokens),
|
| 232 |
+
attn_mask=self._local_attention_mask, need_weights=False,
|
| 233 |
+
)
|
| 234 |
+
tokens = tokens + local_update
|
| 235 |
+
|
| 236 |
+
addressed_memory = self.memory_address_norm(memory + memory_slot_identity)
|
| 237 |
+
memory_values = self.memory_value_norm(memory)
|
| 238 |
+
token_memory_update, _ = self.token_memory_attention(
|
| 239 |
+
self.state_norm(tokens), addressed_memory, memory_values, need_weights=False
|
| 240 |
+
)
|
| 241 |
+
tokens = tokens + token_memory_update
|
| 242 |
+
tokens = tokens + self.token_ff(self.token_ff_norm(tokens))
|
| 243 |
+
|
| 244 |
+
memory_token_update, _ = self.memory_token_attention(
|
| 245 |
+
addressed_memory,
|
| 246 |
+
self.state_norm(tokens),
|
| 247 |
+
self.state_norm(tokens),
|
| 248 |
+
need_weights=False,
|
| 249 |
+
)
|
| 250 |
+
memory = memory + memory_token_update
|
| 251 |
+
memory = memory + self.memory_ff(self.memory_ff_norm(memory))
|
| 252 |
+
# This module is a recurrent cell, not a depth-only Transformer block.
|
| 253 |
+
# Persist normalized state so repeated denoise updates cannot accumulate
|
| 254 |
+
# an unbounded residual magnitude across time.
|
| 255 |
+
return self.stored_token_norm(tokens), self.stored_memory_norm(memory)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class LatentDeliberationTransformer(nn.Module):
|
| 259 |
+
"""Small recurrent Transformer that compresses repeated denoise context."""
|
| 260 |
+
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
*,
|
| 264 |
+
hidden_size: int,
|
| 265 |
+
latent_dim: int = 512,
|
| 266 |
+
memory_slots: int = 16,
|
| 267 |
+
num_layers: int = 2,
|
| 268 |
+
num_heads: int = 8,
|
| 269 |
+
local_attention_window: int = 32,
|
| 270 |
+
dropout: float = 0.0,
|
| 271 |
+
) -> None:
|
| 272 |
+
super().__init__()
|
| 273 |
+
if latent_dim % num_heads:
|
| 274 |
+
raise ValueError("`latent_dim` must be divisible by `num_heads`.")
|
| 275 |
+
if local_attention_window <= 0:
|
| 276 |
+
raise ValueError("`local_attention_window` must be positive.")
|
| 277 |
+
self.hidden_size = hidden_size
|
| 278 |
+
self.latent_dim = latent_dim
|
| 279 |
+
self.memory_slots = memory_slots
|
| 280 |
+
self.heavy_projection = nn.Linear(hidden_size, latent_dim, bias=False)
|
| 281 |
+
self.embedding_projection = nn.Linear(hidden_size, latent_dim, bias=False)
|
| 282 |
+
self.scalar_projection = nn.Linear(11, latent_dim, bias=False)
|
| 283 |
+
self.blocks = nn.ModuleList(
|
| 284 |
+
[
|
| 285 |
+
_TemporalTransformerCell(
|
| 286 |
+
latent_dim, num_heads, dropout, local_attention_window
|
| 287 |
+
)
|
| 288 |
+
for _ in range(num_layers)
|
| 289 |
+
]
|
| 290 |
+
)
|
| 291 |
+
self.output_norm = nn.LayerNorm(latent_dim)
|
| 292 |
+
self.output_projection = nn.Linear(latent_dim, hidden_size, bias=False)
|
| 293 |
+
self.memory_slot_identity = nn.Parameter(torch.empty(memory_slots, latent_dim))
|
| 294 |
+
self.reset_memory_slot_identity()
|
| 295 |
+
|
| 296 |
+
@torch.no_grad()
|
| 297 |
+
def reset_memory_slot_identity(self) -> None:
|
| 298 |
+
"""Restore learned memory addresses after generic initialization."""
|
| 299 |
+
|
| 300 |
+
nn.init.normal_(self.memory_slot_identity, mean=0.0, std=0.02)
|
| 301 |
+
|
| 302 |
+
def project_context(self, token_latents: torch.Tensor) -> torch.Tensor:
|
| 303 |
+
"""Translate latent state into a self-conditioning embedding."""
|
| 304 |
+
|
| 305 |
+
normalized_tokens = self.output_norm(token_latents)
|
| 306 |
+
return self.output_projection(normalized_tokens)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
*,
|
| 311 |
+
heavy_hidden: torch.Tensor,
|
| 312 |
+
token_embeddings: torch.Tensor,
|
| 313 |
+
confidence: torch.Tensor,
|
| 314 |
+
entropy: torch.Tensor,
|
| 315 |
+
state: LatentDeliberationState,
|
| 316 |
+
) -> tuple[torch.Tensor, LatentDeliberationState]:
|
| 317 |
+
"""Advance latent memory and produce decoder self-conditioning.
|
| 318 |
+
|
| 319 |
+
Args:
|
| 320 |
+
heavy_hidden: Hidden states from the previous decoder pass.
|
| 321 |
+
token_embeddings: Embeddings of current noisy canvas tokens.
|
| 322 |
+
confidence: Proposal confidence for each canvas position.
|
| 323 |
+
entropy: Proposal entropy for each canvas position.
|
| 324 |
+
state: Persistent latent state from the preceding pass.
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
Self-conditioning embeddings and the next compact latent state.
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
if heavy_hidden.ndim != 3:
|
| 331 |
+
raise ValueError("`heavy_hidden` must have shape [batch, canvas, hidden].")
|
| 332 |
+
if heavy_hidden.shape != token_embeddings.shape:
|
| 333 |
+
raise ValueError("`heavy_hidden` and `token_embeddings` must have the same shape.")
|
| 334 |
+
batch_size, canvas_length, hidden_size = heavy_hidden.shape
|
| 335 |
+
if hidden_size != self.hidden_size:
|
| 336 |
+
raise ValueError("Unexpected hidden size for latent deliberation.")
|
| 337 |
+
expected_state = (batch_size, canvas_length, self.latent_dim)
|
| 338 |
+
if state.token_latents.shape != expected_state:
|
| 339 |
+
raise ValueError("State token latents do not match the current canvas.")
|
| 340 |
+
if state.memory_slots.shape != (batch_size, self.memory_slots, self.latent_dim):
|
| 341 |
+
raise ValueError("State memory slots do not match this module.")
|
| 342 |
+
if state.age.dtype is not torch.int32:
|
| 343 |
+
raise TypeError("Latent deliberation ages must use int32.")
|
| 344 |
+
|
| 345 |
+
scalars = torch.stack(
|
| 346 |
+
(
|
| 347 |
+
confidence.to(dtype=heavy_hidden.dtype),
|
| 348 |
+
entropy.to(dtype=heavy_hidden.dtype).log1p(),
|
| 349 |
+
state.age.to(dtype=heavy_hidden.dtype).clamp_max(32767).log1p(),
|
| 350 |
+
torch.linspace(
|
| 351 |
+
-1.0, 1.0, canvas_length, device=heavy_hidden.device,
|
| 352 |
+
dtype=heavy_hidden.dtype,
|
| 353 |
+
).unsqueeze(0).expand(batch_size, -1),
|
| 354 |
+
state.token_changed.to(dtype=heavy_hidden.dtype),
|
| 355 |
+
state.confidence_delta.to(dtype=heavy_hidden.dtype),
|
| 356 |
+
state.entropy_delta.to(dtype=heavy_hidden.dtype).sign()
|
| 357 |
+
* state.entropy_delta.to(dtype=heavy_hidden.dtype).abs().log1p(),
|
| 358 |
+
state.ponder_steps.to(dtype=heavy_hidden.dtype).log1p()[:, None]
|
| 359 |
+
.expand(-1, canvas_length),
|
| 360 |
+
state.stagnation_steps.to(dtype=heavy_hidden.dtype).log1p()[:, None]
|
| 361 |
+
.expand(-1, canvas_length),
|
| 362 |
+
confidence.to(dtype=heavy_hidden.dtype)
|
| 363 |
+
* torch.exp(-entropy.to(dtype=heavy_hidden.dtype).clamp_min(0.0)),
|
| 364 |
+
state.confidence_delta.to(dtype=heavy_hidden.dtype).clamp_min(0.0)
|
| 365 |
+
+ (-state.entropy_delta.to(dtype=heavy_hidden.dtype)).clamp_min(0.0).log1p(),
|
| 366 |
+
),
|
| 367 |
+
dim=-1,
|
| 368 |
+
)
|
| 369 |
+
observation = (
|
| 370 |
+
self.heavy_projection(heavy_hidden)
|
| 371 |
+
+ self.embedding_projection(token_embeddings)
|
| 372 |
+
+ self.scalar_projection(scalars)
|
| 373 |
+
)
|
| 374 |
+
tokens = state.token_latents
|
| 375 |
+
memory = state.memory_slots
|
| 376 |
+
slot_identity = self.memory_slot_identity.to(device=memory.device, dtype=memory.dtype)
|
| 377 |
+
slot_identity = slot_identity.unsqueeze(0).expand(batch_size, -1, -1)
|
| 378 |
+
for block in self.blocks:
|
| 379 |
+
tokens, memory = block(tokens, observation, memory, slot_identity)
|
| 380 |
+
observation = tokens
|
| 381 |
+
|
| 382 |
+
context = self.project_context(tokens)
|
| 383 |
+
next_state = LatentDeliberationState(
|
| 384 |
+
token_latents=tokens,
|
| 385 |
+
memory_slots=memory,
|
| 386 |
+
confidence=confidence.to(dtype=torch.float32),
|
| 387 |
+
entropy=entropy.to(dtype=torch.float32),
|
| 388 |
+
age=state.age,
|
| 389 |
+
token_changed=state.token_changed,
|
| 390 |
+
confidence_delta=state.confidence_delta,
|
| 391 |
+
entropy_delta=state.entropy_delta,
|
| 392 |
+
ponder_steps=state.ponder_steps,
|
| 393 |
+
stagnation_steps=state.stagnation_steps,
|
| 394 |
+
)
|
| 395 |
+
return context, next_state
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
__all__ = [
|
| 399 |
+
"LatentDeliberationState", "LatentDeliberationTransformer",
|
| 400 |
+
"advance_trajectory_clocks", "should_force_trajectory_jump",
|
| 401 |
+
]
|
model-00001-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:135514d54da5b9cb01dd79a1997a1fbad2e09f9a8d2f4dfe8fa279aefd60fc11
|
| 3 |
+
size 4242778850
|
model-00002-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:96f91fedb74337b58c99bb601f6e1cc6a63a70e2b5caba17aaa16e2ab536dc68
|
| 3 |
+
size 4884578006
|
model-00003-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ea4ac8914c430b28f4e31191e07b1304adb5adcbf831f8831aeee91ba44bf80
|
| 3 |
+
size 4913414750
|
model-00004-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:971648eba5fe25b8886933176233fdd77185accdde29eb8cec260d0003eca425
|
| 3 |
+
size 4884578006
|
model-00005-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f5991d942f31e81d638e65b8e4d7aa487c66f014a5d2402f0ea8019b0fcc5efa
|
| 3 |
+
size 4913414814
|
model-00006-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1953c0a2a5757d4046e936d6f194024fef8f202f2367f5e3053291c417dbce83
|
| 3 |
+
size 4884578078
|
model-00007-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:363ac9d7c5cda20dc2f8d3420390f3934dfb16491f94bcfd754c2f298c3429e4
|
| 3 |
+
size 4913414814
|
model-00008-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0995bc965194819e4112dff96e0b56934a79ab4a9614eedb6d114d96a40a2bbc
|
| 3 |
+
size 4884578078
|
model-00009-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:26a1fda50be76b3e05d855b11bb69524696e8472f2a6de874d04d21146b33ff7
|
| 3 |
+
size 4913414814
|
model-00010-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:00f7cadf0e38ba1df7f3412dd4cc58d18c713bfdcd0c7ad625dc50f3296b8d33
|
| 3 |
+
size 4884578078
|
model-00011-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b18cabb13c1f957269498552fa4680a233279c074fb489aee431910cfb7d1f88
|
| 3 |
+
size 3959052896
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_modilify_mk1.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Standard PyTorch multimodal model implementation for Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
+
import math
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
from transformers.cache_utils import Cache
|
| 14 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 15 |
+
from transformers.utils import ModelOutput
|
| 16 |
+
from transformers.models.diffusion_gemma import (
|
| 17 |
+
DiffusionGemmaDecoderModel,
|
| 18 |
+
DiffusionGemmaEncoderModel,
|
| 19 |
+
DiffusionGemmaPreTrainedModel,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from .configuration_modilify_mk1 import ModilifyMk1Config
|
| 23 |
+
from .generation_modilify_mk1 import (
|
| 24 |
+
ModilifyMk1GenerationConfig,
|
| 25 |
+
ModilifyMk1GenerationMixin,
|
| 26 |
+
)
|
| 27 |
+
from .latent_deliberation import (
|
| 28 |
+
LatentDeliberationState,
|
| 29 |
+
LatentDeliberationTransformer,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class ModilifyMk1DecoderOutput(BaseModelOutputWithPast):
|
| 35 |
+
"""Decoder hidden states and latent-context diagnostics."""
|
| 36 |
+
|
| 37 |
+
token_embeddings: torch.FloatTensor | None = None
|
| 38 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class ModilifyMk1ModelOutput(BaseModelOutputWithPast):
|
| 43 |
+
"""Combined multimodal encoder and diffusion decoder output."""
|
| 44 |
+
|
| 45 |
+
token_embeddings: torch.FloatTensor | None = None
|
| 46 |
+
encoder_last_hidden_state: torch.FloatTensor | None = None
|
| 47 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class ModilifyMk1BlockDiffusionOutput(ModelOutput):
|
| 52 |
+
"""Inference output used by the rolling diffusion generator."""
|
| 53 |
+
|
| 54 |
+
logits: torch.FloatTensor | None = None
|
| 55 |
+
heavy_hidden_state: torch.FloatTensor | None = None
|
| 56 |
+
next_latent_state: LatentDeliberationState | None = None
|
| 57 |
+
past_key_values: Cache | None = None
|
| 58 |
+
encoder_last_hidden_state: torch.FloatTensor | None = None
|
| 59 |
+
temporal_context: torch.FloatTensor | None = None
|
| 60 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 61 |
+
proposal: torch.LongTensor | None = None
|
| 62 |
+
proposal_confidence: torch.FloatTensor | None = None
|
| 63 |
+
token_entropy: torch.FloatTensor | None = None
|
| 64 |
+
greedy_proposal: torch.LongTensor | None = None
|
| 65 |
+
greedy_confidence: torch.FloatTensor | None = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class ModilifyMk1EncoderModel(DiffusionGemmaEncoderModel):
|
| 69 |
+
"""Unmodified Transformers DiffusionGemma multimodal encoder."""
|
| 70 |
+
|
| 71 |
+
config_class = ModilifyMk1Config
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ModilifyMk1DecoderModel(DiffusionGemmaDecoderModel):
|
| 75 |
+
"""DiffusionGemma decoder conditioned by recurrent latent embeddings."""
|
| 76 |
+
|
| 77 |
+
config_class = ModilifyMk1Config
|
| 78 |
+
latent_residual_rms_ratio_cap = 0.5
|
| 79 |
+
|
| 80 |
+
def merge_latent_context(
|
| 81 |
+
self,
|
| 82 |
+
token_embeddings: torch.Tensor,
|
| 83 |
+
latent_context: torch.Tensor | None,
|
| 84 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 85 |
+
"""Apply the native self-conditioning bridge to latent context.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
token_embeddings: Embedded noisy canvas tokens.
|
| 89 |
+
latent_context: Context emitted by the latent Transformer.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
Merged embeddings and scalar diagnostic tensors.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
context = (
|
| 96 |
+
torch.zeros_like(token_embeddings)
|
| 97 |
+
if latent_context is None
|
| 98 |
+
else latent_context.to(token_embeddings)
|
| 99 |
+
)
|
| 100 |
+
if context.shape != token_embeddings.shape:
|
| 101 |
+
raise ValueError("Latent context must match the canvas embedding shape.")
|
| 102 |
+
mapper = self.self_conditioning
|
| 103 |
+
normalized = mapper.pre_norm(context)
|
| 104 |
+
mapped = mapper.down_proj(
|
| 105 |
+
mapper.act_fn(mapper.gate_proj(normalized)) * mapper.up_proj(normalized)
|
| 106 |
+
)
|
| 107 |
+
mapped_rms_per_token = mapped.float().square().mean(dim=-1, keepdim=True).sqrt()
|
| 108 |
+
token_rms_per_token = token_embeddings.float().square().mean(dim=-1, keepdim=True).sqrt()
|
| 109 |
+
cap = self.latent_residual_rms_ratio_cap * token_rms_per_token
|
| 110 |
+
scale = cap / torch.sqrt(mapped_rms_per_token.square() + cap.square() + 1.0e-12)
|
| 111 |
+
mapped = mapped * scale.to(mapped)
|
| 112 |
+
combined = mapper.post_norm(token_embeddings + mapped)
|
| 113 |
+
token_rms = token_embeddings.detach().float().square().mean().sqrt()
|
| 114 |
+
mapped_rms = mapped.detach().float().square().mean().sqrt()
|
| 115 |
+
diagnostics = {
|
| 116 |
+
"token_embedding_rms": token_rms,
|
| 117 |
+
"latent_context_rms": context.detach().float().square().mean().sqrt(),
|
| 118 |
+
"mapped_context_rms": mapped_rms,
|
| 119 |
+
"latent_to_embedding_rms_ratio": mapped_rms / token_rms.clamp_min(1.0e-12),
|
| 120 |
+
}
|
| 121 |
+
return combined, diagnostics
|
| 122 |
+
|
| 123 |
+
def forward(
|
| 124 |
+
self,
|
| 125 |
+
decoder_input_ids: torch.LongTensor,
|
| 126 |
+
past_key_values: Cache | None = None,
|
| 127 |
+
temporal_context_embeddings: torch.FloatTensor | None = None,
|
| 128 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 129 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 130 |
+
**kwargs: Any,
|
| 131 |
+
) -> ModilifyMk1DecoderOutput:
|
| 132 |
+
"""Decode one noisy canvas using only Transformers and PyTorch operations."""
|
| 133 |
+
|
| 134 |
+
token_embeddings = self.embed_tokens(decoder_input_ids)
|
| 135 |
+
inputs_embeds, diagnostics = self.merge_latent_context(
|
| 136 |
+
token_embeddings,
|
| 137 |
+
temporal_context_embeddings,
|
| 138 |
+
)
|
| 139 |
+
if decoder_position_ids is None:
|
| 140 |
+
prefix = past_key_values.get_seq_length(0) if past_key_values is not None else 0
|
| 141 |
+
decoder_position_ids = torch.arange(
|
| 142 |
+
prefix,
|
| 143 |
+
prefix + inputs_embeds.shape[1],
|
| 144 |
+
device=inputs_embeds.device,
|
| 145 |
+
).unsqueeze(0)
|
| 146 |
+
if not isinstance(mask_mapping := decoder_attention_mask, dict):
|
| 147 |
+
mask_mapping = self.create_diffusion_decoder_attention_mask(
|
| 148 |
+
config=self.text_config,
|
| 149 |
+
inputs_embeds=inputs_embeds,
|
| 150 |
+
past_key_values=past_key_values,
|
| 151 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 152 |
+
)
|
| 153 |
+
position_embeddings = {
|
| 154 |
+
layer_type: self.rotary_emb(inputs_embeds, decoder_position_ids, layer_type)
|
| 155 |
+
for layer_type in self.unique_layer_types
|
| 156 |
+
}
|
| 157 |
+
hidden_states = inputs_embeds
|
| 158 |
+
for index, layer in enumerate(self.layers[: self.text_config.num_hidden_layers]):
|
| 159 |
+
layer_type = self.text_config.layer_types[index]
|
| 160 |
+
hidden_states = layer(
|
| 161 |
+
hidden_states,
|
| 162 |
+
position_embeddings=position_embeddings[layer_type],
|
| 163 |
+
attention_mask=mask_mapping[layer_type],
|
| 164 |
+
position_ids=decoder_position_ids,
|
| 165 |
+
past_key_values=past_key_values,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
return ModilifyMk1DecoderOutput(
|
| 169 |
+
last_hidden_state=self.norm(hidden_states),
|
| 170 |
+
past_key_values=past_key_values,
|
| 171 |
+
token_embeddings=token_embeddings,
|
| 172 |
+
latent_residual_diagnostics=diagnostics,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class ModilifyMk1Model(DiffusionGemmaPreTrainedModel):
|
| 177 |
+
"""Multimodal encoder plus latent-conditioned block diffusion decoder."""
|
| 178 |
+
|
| 179 |
+
config_class = ModilifyMk1Config
|
| 180 |
+
_tied_weights_keys = {
|
| 181 |
+
"encoder.language_model.norm.weight": "decoder.norm.weight",
|
| 182 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*weight": r"decoder.layers\.(?:[^.]+\.)*weight",
|
| 183 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*scale": r"decoder.layers\.(?:[^.]+\.)*scale",
|
| 184 |
+
(
|
| 185 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*per_expert_scale"
|
| 186 |
+
): r"decoder.layers\.(?:[^.]+\.)*per_expert_scale",
|
| 187 |
+
(
|
| 188 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*gate_up_proj"
|
| 189 |
+
): r"decoder.layers\.(?:[^.]+\.)*gate_up_proj",
|
| 190 |
+
(
|
| 191 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*down_proj"
|
| 192 |
+
): r"decoder.layers\.(?:[^.]+\.)*down_proj",
|
| 193 |
+
"encoder.language_model.embed_tokens.weight": "decoder.embed_tokens.weight",
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
def __init__(self, config: ModilifyMk1Config) -> None:
|
| 197 |
+
super().__init__(config)
|
| 198 |
+
self.encoder = ModilifyMk1EncoderModel(config)
|
| 199 |
+
self.decoder = ModilifyMk1DecoderModel(config)
|
| 200 |
+
self.post_init()
|
| 201 |
+
|
| 202 |
+
def get_encoder(self) -> ModilifyMk1EncoderModel:
|
| 203 |
+
"""Return the standard multimodal encoder."""
|
| 204 |
+
|
| 205 |
+
return self.encoder
|
| 206 |
+
|
| 207 |
+
def get_decoder(self) -> ModilifyMk1DecoderModel:
|
| 208 |
+
"""Return the diffusion decoder."""
|
| 209 |
+
|
| 210 |
+
return self.decoder
|
| 211 |
+
|
| 212 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 213 |
+
"""Return the shared text embedding module."""
|
| 214 |
+
|
| 215 |
+
return self.encoder.get_input_embeddings()
|
| 216 |
+
|
| 217 |
+
def set_input_embeddings(self, value: nn.Module) -> None:
|
| 218 |
+
"""Set the shared text embedding module."""
|
| 219 |
+
|
| 220 |
+
self.encoder.set_input_embeddings(value)
|
| 221 |
+
self.decoder.embed_tokens = value
|
| 222 |
+
|
| 223 |
+
def forward(
|
| 224 |
+
self,
|
| 225 |
+
*,
|
| 226 |
+
input_ids: torch.LongTensor | None = None,
|
| 227 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 228 |
+
past_key_values: Cache | None = None,
|
| 229 |
+
position_ids: torch.LongTensor | None = None,
|
| 230 |
+
decoder_input_ids: torch.LongTensor,
|
| 231 |
+
temporal_context_embeddings: torch.FloatTensor | None = None,
|
| 232 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 233 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 234 |
+
**kwargs: Any,
|
| 235 |
+
) -> ModilifyMk1ModelOutput:
|
| 236 |
+
"""Encode multimodal context and decode one canvas."""
|
| 237 |
+
|
| 238 |
+
encoder_hidden_state = None
|
| 239 |
+
encoder_keys = ("pixel_values", "mm_token_type_ids", "image_position_ids", "inputs_embeds")
|
| 240 |
+
encoder_kwargs = {key: kwargs.pop(key) for key in encoder_keys if key in kwargs}
|
| 241 |
+
if input_ids is not None:
|
| 242 |
+
encoded = self.encoder(
|
| 243 |
+
input_ids=input_ids,
|
| 244 |
+
attention_mask=attention_mask,
|
| 245 |
+
past_key_values=past_key_values,
|
| 246 |
+
position_ids=position_ids,
|
| 247 |
+
**encoder_kwargs,
|
| 248 |
+
)
|
| 249 |
+
past_key_values = encoded.past_key_values
|
| 250 |
+
encoder_hidden_state = encoded.last_hidden_state
|
| 251 |
+
elif past_key_values is None:
|
| 252 |
+
raise ValueError("Either `input_ids` or `past_key_values` is required.")
|
| 253 |
+
decoded = self.decoder(
|
| 254 |
+
decoder_input_ids=decoder_input_ids,
|
| 255 |
+
past_key_values=past_key_values,
|
| 256 |
+
temporal_context_embeddings=temporal_context_embeddings,
|
| 257 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 258 |
+
decoder_position_ids=decoder_position_ids,
|
| 259 |
+
**kwargs,
|
| 260 |
+
)
|
| 261 |
+
return ModilifyMk1ModelOutput(
|
| 262 |
+
last_hidden_state=decoded.last_hidden_state,
|
| 263 |
+
past_key_values=past_key_values,
|
| 264 |
+
token_embeddings=decoded.token_embeddings,
|
| 265 |
+
encoder_last_hidden_state=encoder_hidden_state,
|
| 266 |
+
latent_residual_diagnostics=decoded.latent_residual_diagnostics,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class ModilifyMk1ForBlockDiffusion(
|
| 271 |
+
DiffusionGemmaPreTrainedModel,
|
| 272 |
+
ModilifyMk1GenerationMixin,
|
| 273 |
+
):
|
| 274 |
+
"""Inference-only multimodal Modilify Mk1 model."""
|
| 275 |
+
|
| 276 |
+
config_class = ModilifyMk1Config
|
| 277 |
+
_tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
|
| 278 |
+
generation_config_class = ModilifyMk1GenerationConfig
|
| 279 |
+
|
| 280 |
+
@torch.no_grad()
|
| 281 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 282 |
+
super()._init_weights(module)
|
| 283 |
+
if isinstance(module, LatentDeliberationTransformer):
|
| 284 |
+
module.reset_memory_slot_identity()
|
| 285 |
+
|
| 286 |
+
def __init__(self, config: ModilifyMk1Config) -> None:
|
| 287 |
+
super().__init__(config)
|
| 288 |
+
self.model = ModilifyMk1Model(config)
|
| 289 |
+
self.latent_deliberation = LatentDeliberationTransformer(
|
| 290 |
+
hidden_size=config.text_config.hidden_size,
|
| 291 |
+
latent_dim=config.latent_dim,
|
| 292 |
+
memory_slots=config.latent_memory_slots,
|
| 293 |
+
num_layers=config.latent_num_layers,
|
| 294 |
+
num_heads=config.latent_num_heads,
|
| 295 |
+
local_attention_window=config.latent_local_attention_window,
|
| 296 |
+
dropout=config.latent_dropout,
|
| 297 |
+
)
|
| 298 |
+
self.lm_head = nn.Linear(
|
| 299 |
+
config.text_config.hidden_size,
|
| 300 |
+
config.text_config.vocab_size,
|
| 301 |
+
bias=False,
|
| 302 |
+
)
|
| 303 |
+
self.final_logit_softcapping = config.text_config.final_logit_softcapping
|
| 304 |
+
self.post_init()
|
| 305 |
+
|
| 306 |
+
def _prepare_latent_context(
|
| 307 |
+
self,
|
| 308 |
+
decoder_input_ids: torch.LongTensor,
|
| 309 |
+
*,
|
| 310 |
+
history_hidden_state: torch.Tensor | None,
|
| 311 |
+
confidence: torch.Tensor | None,
|
| 312 |
+
entropy: torch.Tensor | None,
|
| 313 |
+
age: torch.Tensor | None,
|
| 314 |
+
latent_state: LatentDeliberationState | None,
|
| 315 |
+
) -> tuple[torch.Tensor, LatentDeliberationState]:
|
| 316 |
+
"""Advance recurrent latent state for the current canvas."""
|
| 317 |
+
|
| 318 |
+
batch_size, canvas_length = decoder_input_ids.shape
|
| 319 |
+
dtype = self.model.decoder.embed_tokens.weight.dtype
|
| 320 |
+
if latent_state is None:
|
| 321 |
+
latent_state = LatentDeliberationState.empty(
|
| 322 |
+
batch_size=batch_size,
|
| 323 |
+
canvas_length=canvas_length,
|
| 324 |
+
latent_dim=self.config.latent_dim,
|
| 325 |
+
memory_slots=self.config.latent_memory_slots,
|
| 326 |
+
device=decoder_input_ids.device,
|
| 327 |
+
dtype=dtype,
|
| 328 |
+
)
|
| 329 |
+
confidence = (
|
| 330 |
+
latent_state.confidence
|
| 331 |
+
if confidence is None
|
| 332 |
+
else confidence.squeeze(-1).float()
|
| 333 |
+
)
|
| 334 |
+
entropy = latent_state.entropy if entropy is None else entropy.squeeze(-1).float()
|
| 335 |
+
if age is not None:
|
| 336 |
+
latent_state = replace(
|
| 337 |
+
latent_state,
|
| 338 |
+
age=age.to(device=decoder_input_ids.device, dtype=torch.int32),
|
| 339 |
+
)
|
| 340 |
+
token_embeddings = self.model.decoder.embed_tokens(decoder_input_ids)
|
| 341 |
+
history = (
|
| 342 |
+
torch.zeros_like(token_embeddings)
|
| 343 |
+
if history_hidden_state is None
|
| 344 |
+
else history_hidden_state
|
| 345 |
+
)
|
| 346 |
+
return self.latent_deliberation(
|
| 347 |
+
heavy_hidden=history,
|
| 348 |
+
token_embeddings=token_embeddings,
|
| 349 |
+
confidence=confidence,
|
| 350 |
+
entropy=entropy,
|
| 351 |
+
state=latent_state,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
def _proposal_statistics(
|
| 355 |
+
self,
|
| 356 |
+
logits: torch.Tensor,
|
| 357 |
+
*,
|
| 358 |
+
denoise_temperature: float | None = None,
|
| 359 |
+
) -> tuple[
|
| 360 |
+
torch.LongTensor,
|
| 361 |
+
torch.Tensor,
|
| 362 |
+
torch.Tensor,
|
| 363 |
+
torch.LongTensor,
|
| 364 |
+
torch.Tensor,
|
| 365 |
+
]:
|
| 366 |
+
"""Compute exact proposal statistics with standard PyTorch operations."""
|
| 367 |
+
|
| 368 |
+
temperature = (
|
| 369 |
+
self.config.denoise_temperature
|
| 370 |
+
if denoise_temperature is None
|
| 371 |
+
else float(denoise_temperature)
|
| 372 |
+
)
|
| 373 |
+
if not math.isfinite(temperature) or temperature <= 0.0:
|
| 374 |
+
raise ValueError("`denoise_temperature` must be positive.")
|
| 375 |
+
scores = logits.float() / temperature
|
| 376 |
+
probabilities = torch.softmax(scores, dim=-1)
|
| 377 |
+
flat = probabilities.reshape(-1, probabilities.shape[-1])
|
| 378 |
+
proposal = torch.multinomial(flat, num_samples=1).view(logits.shape[:-1])
|
| 379 |
+
proposal_confidence = probabilities.gather(
|
| 380 |
+
-1,
|
| 381 |
+
proposal.unsqueeze(-1),
|
| 382 |
+
).squeeze(-1)
|
| 383 |
+
greedy_proposal = probabilities.argmax(dim=-1)
|
| 384 |
+
greedy_confidence = probabilities.gather(
|
| 385 |
+
-1,
|
| 386 |
+
greedy_proposal.unsqueeze(-1),
|
| 387 |
+
).squeeze(-1)
|
| 388 |
+
token_entropy = -(
|
| 389 |
+
probabilities * probabilities.clamp_min(1.0e-30).log()
|
| 390 |
+
).sum(dim=-1)
|
| 391 |
+
return (
|
| 392 |
+
proposal,
|
| 393 |
+
proposal_confidence,
|
| 394 |
+
token_entropy,
|
| 395 |
+
greedy_proposal,
|
| 396 |
+
greedy_confidence,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def forward(
|
| 400 |
+
self,
|
| 401 |
+
*,
|
| 402 |
+
input_ids: torch.LongTensor | None = None,
|
| 403 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 404 |
+
past_key_values: Cache | None = None,
|
| 405 |
+
position_ids: torch.LongTensor | None = None,
|
| 406 |
+
decoder_input_ids: torch.LongTensor,
|
| 407 |
+
previous_confidence: torch.FloatTensor | None = None,
|
| 408 |
+
previous_entropy: torch.FloatTensor | None = None,
|
| 409 |
+
token_age: torch.Tensor | None = None,
|
| 410 |
+
latent_state: LatentDeliberationState | None = None,
|
| 411 |
+
history_hidden_state: torch.FloatTensor | None = None,
|
| 412 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 413 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 414 |
+
return_proposal_statistics: bool = False,
|
| 415 |
+
denoise_temperature: float | None = None,
|
| 416 |
+
**kwargs: Any,
|
| 417 |
+
) -> ModilifyMk1BlockDiffusionOutput:
|
| 418 |
+
"""Run one inference step over a noisy diffusion canvas."""
|
| 419 |
+
|
| 420 |
+
latent_context, next_state = self._prepare_latent_context(
|
| 421 |
+
decoder_input_ids,
|
| 422 |
+
history_hidden_state=history_hidden_state,
|
| 423 |
+
confidence=previous_confidence,
|
| 424 |
+
entropy=previous_entropy,
|
| 425 |
+
age=token_age,
|
| 426 |
+
latent_state=latent_state,
|
| 427 |
+
)
|
| 428 |
+
outputs = self.model(
|
| 429 |
+
input_ids=input_ids,
|
| 430 |
+
attention_mask=attention_mask,
|
| 431 |
+
past_key_values=past_key_values,
|
| 432 |
+
position_ids=position_ids,
|
| 433 |
+
decoder_input_ids=decoder_input_ids,
|
| 434 |
+
temporal_context_embeddings=latent_context,
|
| 435 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 436 |
+
decoder_position_ids=decoder_position_ids,
|
| 437 |
+
**kwargs,
|
| 438 |
+
)
|
| 439 |
+
logits = self.lm_head(outputs.last_hidden_state)
|
| 440 |
+
logits = (
|
| 441 |
+
torch.tanh(logits / self.final_logit_softcapping)
|
| 442 |
+
* self.final_logit_softcapping
|
| 443 |
+
)
|
| 444 |
+
statistics = (None, None, None, None, None)
|
| 445 |
+
if return_proposal_statistics:
|
| 446 |
+
statistics = self._proposal_statistics(
|
| 447 |
+
logits,
|
| 448 |
+
denoise_temperature=denoise_temperature,
|
| 449 |
+
)
|
| 450 |
+
return ModilifyMk1BlockDiffusionOutput(
|
| 451 |
+
logits=None if return_proposal_statistics else logits,
|
| 452 |
+
heavy_hidden_state=outputs.last_hidden_state,
|
| 453 |
+
next_latent_state=next_state,
|
| 454 |
+
past_key_values=outputs.past_key_values,
|
| 455 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 456 |
+
temporal_context=latent_context,
|
| 457 |
+
latent_residual_diagnostics=outputs.latent_residual_diagnostics,
|
| 458 |
+
proposal=statistics[0],
|
| 459 |
+
proposal_confidence=statistics[1],
|
| 460 |
+
token_entropy=statistics[2],
|
| 461 |
+
greedy_proposal=statistics[3],
|
| 462 |
+
greedy_confidence=statistics[4],
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
__all__ = [
|
| 467 |
+
"ModilifyMk1BlockDiffusionOutput",
|
| 468 |
+
"ModilifyMk1Config",
|
| 469 |
+
"ModilifyMk1DecoderModel",
|
| 470 |
+
"ModilifyMk1EncoderModel",
|
| 471 |
+
"ModilifyMk1ForBlockDiffusion",
|
| 472 |
+
"ModilifyMk1Model",
|
| 473 |
+
]
|
modilify_mk1/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Public Transformers interface for Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from .configuration_modilify_mk1 import (
|
| 6 |
+
ModilifyMk1Config,
|
| 7 |
+
ModilifyMk1TextConfig,
|
| 8 |
+
)
|
| 9 |
+
from .generation_modilify_mk1 import (
|
| 10 |
+
ModilifyMk1GenerationConfig,
|
| 11 |
+
ModilifyMk1GenerationOutput,
|
| 12 |
+
)
|
| 13 |
+
from .modeling_modilify_mk1 import (
|
| 14 |
+
ModilifyMk1ForBlockDiffusion,
|
| 15 |
+
ModilifyMk1Model,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"ModilifyMk1Config",
|
| 20 |
+
"ModilifyMk1ForBlockDiffusion",
|
| 21 |
+
"ModilifyMk1GenerationConfig",
|
| 22 |
+
"ModilifyMk1GenerationOutput",
|
| 23 |
+
"ModilifyMk1Model",
|
| 24 |
+
"ModilifyMk1TextConfig",
|
| 25 |
+
]
|
modilify_mk1/commit_policy.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Confidence-and-entropy commit policy for inference."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
from .latent_deliberation import (
|
| 14 |
+
advance_trajectory_clocks,
|
| 15 |
+
should_force_trajectory_jump,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
FUSED_EPS = 1e-6
|
| 19 |
+
FUSED_ENTROPY_WEIGHT = 0.5
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def fused_commit_confidence(
|
| 23 |
+
proposal_confidence: torch.Tensor,
|
| 24 |
+
token_entropy: torch.Tensor,
|
| 25 |
+
*,
|
| 26 |
+
vocab_size: int = 256000,
|
| 27 |
+
entropy_weight: float = FUSED_ENTROPY_WEIGHT,
|
| 28 |
+
eps: float = FUSED_EPS,
|
| 29 |
+
) -> torch.Tensor:
|
| 30 |
+
"""Fuse proposal confidence with token entropy into effective commit confidence.
|
| 31 |
+
|
| 32 |
+
Effective confidence is defined using a multiplicative entropy penalty:
|
| 33 |
+
|
| 34 |
+
fused = confidence * exp(-entropy_weight * token_entropy)
|
| 35 |
+
|
| 36 |
+
This scales proposal confidence by the entropy discount factor e^(-alpha * H),
|
| 37 |
+
penalizing token predictions with high distribution disorder.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
if vocab_size <= 1:
|
| 41 |
+
raise ValueError("`vocab_size` must be greater than one.")
|
| 42 |
+
if not math.isfinite(entropy_weight) or entropy_weight < 0.0:
|
| 43 |
+
raise ValueError("`entropy_weight` must be finite and non-negative.")
|
| 44 |
+
confidence = proposal_confidence.float().clamp(min=eps, max=1.0)
|
| 45 |
+
entropy = token_entropy.float().clamp(0.0, math.log(vocab_size))
|
| 46 |
+
entropy_penalty = torch.exp(-entropy_weight * entropy)
|
| 47 |
+
fused = confidence * entropy_penalty
|
| 48 |
+
return fused.clamp(min=eps, max=1.0)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def fused_commit_failure_rate(
|
| 52 |
+
proposal_confidence: torch.Tensor,
|
| 53 |
+
token_entropy: torch.Tensor,
|
| 54 |
+
**kwargs: object,
|
| 55 |
+
) -> torch.Tensor:
|
| 56 |
+
"""Return ``1 - effective_confidence`` from the shared fusion helper."""
|
| 57 |
+
|
| 58 |
+
return 1.0 - fused_commit_confidence(
|
| 59 |
+
proposal_confidence, token_entropy, **kwargs
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
@dataclass(frozen=True)
|
| 64 |
+
class CommitPolicyDecision:
|
| 65 |
+
"""One inference transition from proposal to committed prefix."""
|
| 66 |
+
|
| 67 |
+
normal_lengths: torch.LongTensor
|
| 68 |
+
commit_lengths: torch.LongTensor
|
| 69 |
+
commit_token_ids: torch.LongTensor
|
| 70 |
+
jump_rows: torch.BoolTensor
|
| 71 |
+
ponder_steps: torch.IntTensor
|
| 72 |
+
stagnation_steps: torch.IntTensor
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def prefix_failure_commit_lengths(
|
| 76 |
+
failure_rate: torch.Tensor,
|
| 77 |
+
*,
|
| 78 |
+
failure_budget: float,
|
| 79 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 80 |
+
) -> torch.LongTensor:
|
| 81 |
+
"""Return the longest valid prefix satisfying ``cumsum(failure_rate) < budget``."""
|
| 82 |
+
|
| 83 |
+
if failure_rate.ndim != 2:
|
| 84 |
+
raise ValueError("Failure rate must have shape [batch, canvas].")
|
| 85 |
+
if not math.isfinite(failure_budget) or failure_budget <= 0:
|
| 86 |
+
raise ValueError("Commit failure budget must be finite and positive.")
|
| 87 |
+
if valid_mask is None:
|
| 88 |
+
valid_mask = torch.ones_like(failure_rate, dtype=torch.bool)
|
| 89 |
+
if valid_mask.shape != failure_rate.shape:
|
| 90 |
+
raise ValueError("Commit validity mask must match failure rate.")
|
| 91 |
+
|
| 92 |
+
risk = failure_rate.float().clamp(0.0, 1.0) * valid_mask.to(torch.float32)
|
| 93 |
+
cumulative_risk = risk.cumsum(dim=-1)
|
| 94 |
+
contiguous_valid = valid_mask.long().cumprod(dim=-1).bool()
|
| 95 |
+
allowed = cumulative_risk.lt(float(failure_budget)) & contiguous_valid
|
| 96 |
+
return allowed.long().cumprod(dim=-1).sum(dim=-1)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def first_committed_token_lengths(
|
| 100 |
+
proposal: torch.LongTensor,
|
| 101 |
+
commit_lengths: torch.LongTensor,
|
| 102 |
+
token_id: int | Sequence[int],
|
| 103 |
+
) -> torch.LongTensor:
|
| 104 |
+
"""Clip each committed prefix immediately after its first matching stop token."""
|
| 105 |
+
|
| 106 |
+
if proposal.ndim != 2 or commit_lengths.shape != proposal.shape[:1]:
|
| 107 |
+
raise ValueError("Proposal and commit lengths must share a batch dimension.")
|
| 108 |
+
positions = torch.arange(proposal.shape[1], device=proposal.device).unsqueeze(0)
|
| 109 |
+
committed = positions.lt(commit_lengths[:, None])
|
| 110 |
+
stop_token_ids = (
|
| 111 |
+
(int(token_id),)
|
| 112 |
+
if isinstance(token_id, int)
|
| 113 |
+
else tuple(dict.fromkeys(int(value) for value in token_id))
|
| 114 |
+
)
|
| 115 |
+
if not stop_token_ids:
|
| 116 |
+
raise ValueError("At least one stop token ID is required.")
|
| 117 |
+
matches = proposal.eq(stop_token_ids[0])
|
| 118 |
+
for value in stop_token_ids[1:]:
|
| 119 |
+
matches |= proposal.eq(value)
|
| 120 |
+
matches &= committed
|
| 121 |
+
sentinel = torch.full_like(positions, proposal.shape[1])
|
| 122 |
+
first = torch.where(matches, positions, sentinel).min(dim=-1).values
|
| 123 |
+
clipped = torch.where(first.lt(proposal.shape[1]), first + 1, commit_lengths)
|
| 124 |
+
return torch.minimum(clipped, commit_lengths)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def bounded_prefix_failure_commit_lengths(
|
| 128 |
+
committed_token_ids: torch.LongTensor,
|
| 129 |
+
failure_rate: torch.Tensor,
|
| 130 |
+
*,
|
| 131 |
+
failure_budget: float,
|
| 132 |
+
remaining_lengths: torch.LongTensor,
|
| 133 |
+
stop_token_id: int | Sequence[int],
|
| 134 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 135 |
+
) -> torch.LongTensor:
|
| 136 |
+
"""Apply length and stop-token bounds to the shared failure-rate policy."""
|
| 137 |
+
|
| 138 |
+
if committed_token_ids.shape != failure_rate.shape:
|
| 139 |
+
raise ValueError("Committed token IDs and failure rate must share [batch, canvas].")
|
| 140 |
+
if remaining_lengths.shape != committed_token_ids.shape[:1]:
|
| 141 |
+
raise ValueError("Remaining lengths must have shape [batch].")
|
| 142 |
+
commit_lengths = prefix_failure_commit_lengths(
|
| 143 |
+
failure_rate,
|
| 144 |
+
failure_budget=failure_budget,
|
| 145 |
+
valid_mask=valid_mask,
|
| 146 |
+
)
|
| 147 |
+
commit_lengths = torch.minimum(commit_lengths, remaining_lengths.clamp_min(0))
|
| 148 |
+
return first_committed_token_lengths(
|
| 149 |
+
committed_token_ids,
|
| 150 |
+
commit_lengths,
|
| 151 |
+
stop_token_id,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def select_commit_lengths(
|
| 156 |
+
sampled_token_ids: torch.LongTensor,
|
| 157 |
+
normal_failure_rate: torch.Tensor,
|
| 158 |
+
previous_failure_rate: torch.Tensor,
|
| 159 |
+
greedy_token_ids: torch.LongTensor,
|
| 160 |
+
jump_failure_rate: torch.Tensor,
|
| 161 |
+
*,
|
| 162 |
+
ponder_steps: torch.Tensor,
|
| 163 |
+
stagnation_steps: torch.Tensor,
|
| 164 |
+
active_rows: torch.BoolTensor,
|
| 165 |
+
remaining_lengths: torch.LongTensor,
|
| 166 |
+
failure_budget: float,
|
| 167 |
+
jump_failure_budget: float,
|
| 168 |
+
stop_token_id: int | Sequence[int],
|
| 169 |
+
max_ponder_steps: int,
|
| 170 |
+
stagnation_threshold: int,
|
| 171 |
+
min_progress: float,
|
| 172 |
+
valid_mask: torch.BoolTensor | None = None,
|
| 173 |
+
) -> CommitPolicyDecision:
|
| 174 |
+
"""Use normal sampled commits and a fixed-budget greedy JUMP.
|
| 175 |
+
|
| 176 |
+
Progress is measured from the signed change in fused failure rate over the
|
| 177 |
+
frontier region (the union of the previous and current commit prefixes plus
|
| 178 |
+
one blocking position), not from raw confidence/entropy deltas.
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
if not (
|
| 182 |
+
sampled_token_ids.shape
|
| 183 |
+
== normal_failure_rate.shape
|
| 184 |
+
== previous_failure_rate.shape
|
| 185 |
+
== greedy_token_ids.shape
|
| 186 |
+
== jump_failure_rate.shape
|
| 187 |
+
):
|
| 188 |
+
raise ValueError("Sampled and greedy statistics must share [batch, canvas].")
|
| 189 |
+
|
| 190 |
+
normal = bounded_prefix_failure_commit_lengths(
|
| 191 |
+
sampled_token_ids,
|
| 192 |
+
normal_failure_rate,
|
| 193 |
+
failure_budget=failure_budget,
|
| 194 |
+
remaining_lengths=remaining_lengths,
|
| 195 |
+
stop_token_id=stop_token_id,
|
| 196 |
+
valid_mask=valid_mask,
|
| 197 |
+
)
|
| 198 |
+
canvas_length = normal_failure_rate.shape[1]
|
| 199 |
+
previous_prefix_length = prefix_failure_commit_lengths(
|
| 200 |
+
previous_failure_rate,
|
| 201 |
+
failure_budget=failure_budget,
|
| 202 |
+
valid_mask=valid_mask,
|
| 203 |
+
)
|
| 204 |
+
frontier_length = torch.maximum(previous_prefix_length, normal) + 1
|
| 205 |
+
valid_lengths = (
|
| 206 |
+
valid_mask.long().sum(dim=-1)
|
| 207 |
+
if valid_mask is not None
|
| 208 |
+
else torch.full_like(frontier_length, canvas_length)
|
| 209 |
+
)
|
| 210 |
+
frontier_length = torch.minimum(frontier_length, valid_lengths)
|
| 211 |
+
positions = torch.arange(canvas_length, device=normal_failure_rate.device)[None, :]
|
| 212 |
+
progress_mask = positions < frontier_length[:, None]
|
| 213 |
+
if valid_mask is not None:
|
| 214 |
+
progress_mask &= valid_mask
|
| 215 |
+
progress_mask &= active_rows[:, None]
|
| 216 |
+
signed_improvement = (
|
| 217 |
+
previous_failure_rate.float() - normal_failure_rate.float()
|
| 218 |
+
)
|
| 219 |
+
weights = progress_mask.float()
|
| 220 |
+
progress = (
|
| 221 |
+
signed_improvement * weights
|
| 222 |
+
).sum(dim=-1) / weights.sum(dim=-1).clamp_min(1.0)
|
| 223 |
+
next_ponder, next_stagnation = advance_trajectory_clocks(
|
| 224 |
+
ponder_steps,
|
| 225 |
+
stagnation_steps,
|
| 226 |
+
commit_lengths=normal,
|
| 227 |
+
active_rows=active_rows,
|
| 228 |
+
progress_scores=progress,
|
| 229 |
+
min_progress=min_progress,
|
| 230 |
+
)
|
| 231 |
+
jump_rows = normal.eq(0) & active_rows & should_force_trajectory_jump(
|
| 232 |
+
next_ponder,
|
| 233 |
+
next_stagnation,
|
| 234 |
+
max_ponder_steps=max_ponder_steps,
|
| 235 |
+
stagnation_threshold=stagnation_threshold,
|
| 236 |
+
)
|
| 237 |
+
jump_commit = bounded_prefix_failure_commit_lengths(
|
| 238 |
+
greedy_token_ids,
|
| 239 |
+
jump_failure_rate,
|
| 240 |
+
failure_budget=jump_failure_budget,
|
| 241 |
+
remaining_lengths=remaining_lengths,
|
| 242 |
+
stop_token_id=stop_token_id,
|
| 243 |
+
valid_mask=valid_mask,
|
| 244 |
+
)
|
| 245 |
+
committed = torch.where(jump_rows, jump_commit, normal)
|
| 246 |
+
commit_token_ids = torch.where(
|
| 247 |
+
jump_rows[:, None],
|
| 248 |
+
greedy_token_ids,
|
| 249 |
+
sampled_token_ids,
|
| 250 |
+
)
|
| 251 |
+
committed = first_committed_token_lengths(
|
| 252 |
+
commit_token_ids,
|
| 253 |
+
committed,
|
| 254 |
+
stop_token_id,
|
| 255 |
+
)
|
| 256 |
+
committed = torch.where(active_rows, committed, 0)
|
| 257 |
+
jump_rows &= committed.gt(0)
|
| 258 |
+
next_ponder = torch.where(
|
| 259 |
+
committed.gt(0),
|
| 260 |
+
0,
|
| 261 |
+
next_ponder,
|
| 262 |
+
).to(torch.int32)
|
| 263 |
+
next_stagnation = torch.where(
|
| 264 |
+
committed.gt(0),
|
| 265 |
+
0,
|
| 266 |
+
next_stagnation,
|
| 267 |
+
).to(torch.int32)
|
| 268 |
+
return CommitPolicyDecision(
|
| 269 |
+
normal_lengths=normal,
|
| 270 |
+
commit_lengths=committed,
|
| 271 |
+
commit_token_ids=commit_token_ids,
|
| 272 |
+
jump_rows=jump_rows,
|
| 273 |
+
ponder_steps=next_ponder,
|
| 274 |
+
stagnation_steps=next_stagnation,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
__all__ = [
|
| 279 |
+
"CommitPolicyDecision",
|
| 280 |
+
"FUSED_ENTROPY_WEIGHT",
|
| 281 |
+
"bounded_prefix_failure_commit_lengths",
|
| 282 |
+
"first_committed_token_lengths",
|
| 283 |
+
"fused_commit_confidence",
|
| 284 |
+
"fused_commit_failure_rate",
|
| 285 |
+
"prefix_failure_commit_lengths",
|
| 286 |
+
"select_commit_lengths",
|
| 287 |
+
]
|
modilify_mk1/configuration_modilify_mk1.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Configuration classes for Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from transformers.models.diffusion_gemma import (
|
| 11 |
+
DiffusionGemmaConfig,
|
| 12 |
+
DiffusionGemmaTextConfig,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ModilifyMk1TextConfig(DiffusionGemmaTextConfig):
|
| 17 |
+
"""Text configuration for the Modilify Mk1 decoder.
|
| 18 |
+
|
| 19 |
+
This class preserves the standard DiffusionGemma text schema while giving
|
| 20 |
+
the exported model an independent, stable model type.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
model_type = "modilify_mk1_text"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ModilifyMk1Config(DiffusionGemmaConfig):
|
| 27 |
+
"""Serializable multimodal inference configuration for Modilify Mk1.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
text_config: DiffusionGemma text configuration or its serialized form.
|
| 31 |
+
vision_config: Gemma 4 vision configuration or its serialized form.
|
| 32 |
+
denoise_temperature: Sampling temperature used at every denoising step.
|
| 33 |
+
commit_failure_budget: Maximum cumulative failure risk for normal commits.
|
| 34 |
+
fused_entropy_weight: Multiplicative entropy penalty coefficient.
|
| 35 |
+
jump_failure_budget: Maximum cumulative failure risk for forced jumps.
|
| 36 |
+
vocab_chunk_size: Vocabulary projection planning size recorded with the
|
| 37 |
+
model. Inference uses standard PyTorch tensor operations.
|
| 38 |
+
latent_dim: Width of the recurrent latent state.
|
| 39 |
+
latent_memory_slots: Number of persistent latent memory slots.
|
| 40 |
+
latent_num_layers: Number of latent Transformer blocks.
|
| 41 |
+
latent_num_heads: Number of latent attention heads.
|
| 42 |
+
latent_local_attention_window: Local token-attention radius.
|
| 43 |
+
latent_dropout: Latent Transformer dropout probability.
|
| 44 |
+
jump_on_no_progress_after: Stagnation steps before a forced jump.
|
| 45 |
+
max_ponder_steps: Maximum denoising iterations per requested token.
|
| 46 |
+
min_trajectory_progress: Minimum fused-risk improvement counted as progress.
|
| 47 |
+
turn_end_token_id: Native Gemma turn terminator.
|
| 48 |
+
kwargs: Standard DiffusionGemma configuration values.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
model_type = "modilify_mk1"
|
| 52 |
+
sub_configs = {
|
| 53 |
+
"text_config": ModilifyMk1TextConfig,
|
| 54 |
+
**{
|
| 55 |
+
key: value
|
| 56 |
+
for key, value in DiffusionGemmaConfig.sub_configs.items()
|
| 57 |
+
if key != "text_config"
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
text_config: (
|
| 64 |
+
ModilifyMk1TextConfig
|
| 65 |
+
| DiffusionGemmaTextConfig
|
| 66 |
+
| dict[str, Any]
|
| 67 |
+
| None
|
| 68 |
+
) = None,
|
| 69 |
+
vision_config: Any | dict[str, Any] | None = None,
|
| 70 |
+
*,
|
| 71 |
+
denoise_temperature: float = 0.8,
|
| 72 |
+
commit_failure_budget: float = 0.2,
|
| 73 |
+
fused_entropy_weight: float = 0.5,
|
| 74 |
+
jump_failure_budget: float = 2.0,
|
| 75 |
+
vocab_chunk_size: int = 65_536,
|
| 76 |
+
latent_dim: int = 1536,
|
| 77 |
+
latent_memory_slots: int = 64,
|
| 78 |
+
latent_num_layers: int = 4,
|
| 79 |
+
latent_num_heads: int = 16,
|
| 80 |
+
latent_local_attention_window: int = 128,
|
| 81 |
+
latent_dropout: float = 0.0,
|
| 82 |
+
jump_on_no_progress_after: int = 12,
|
| 83 |
+
max_ponder_steps: int = 64,
|
| 84 |
+
min_trajectory_progress: float = 0.005,
|
| 85 |
+
turn_end_token_id: int = 106,
|
| 86 |
+
**kwargs: Any,
|
| 87 |
+
) -> None:
|
| 88 |
+
kwargs.pop("model_type", None)
|
| 89 |
+
if isinstance(text_config, DiffusionGemmaTextConfig):
|
| 90 |
+
text_payload = text_config.to_dict()
|
| 91 |
+
text_payload.pop("model_type", None)
|
| 92 |
+
text_config = ModilifyMk1TextConfig(**text_payload)
|
| 93 |
+
elif isinstance(text_config, dict):
|
| 94 |
+
text_payload = dict(text_config)
|
| 95 |
+
text_payload.pop("model_type", None)
|
| 96 |
+
text_config = ModilifyMk1TextConfig(**text_payload)
|
| 97 |
+
elif text_config is None:
|
| 98 |
+
text_config = ModilifyMk1TextConfig()
|
| 99 |
+
|
| 100 |
+
self.denoise_temperature = float(denoise_temperature)
|
| 101 |
+
self.commit_failure_budget = float(commit_failure_budget)
|
| 102 |
+
self.fused_entropy_weight = float(fused_entropy_weight)
|
| 103 |
+
self.jump_failure_budget = float(jump_failure_budget)
|
| 104 |
+
self.vocab_chunk_size = int(vocab_chunk_size)
|
| 105 |
+
self.latent_dim = int(latent_dim)
|
| 106 |
+
self.latent_memory_slots = int(latent_memory_slots)
|
| 107 |
+
self.latent_num_layers = int(latent_num_layers)
|
| 108 |
+
self.latent_num_heads = int(latent_num_heads)
|
| 109 |
+
self.latent_local_attention_window = int(latent_local_attention_window)
|
| 110 |
+
self.latent_dropout = float(latent_dropout)
|
| 111 |
+
self.jump_on_no_progress_after = int(jump_on_no_progress_after)
|
| 112 |
+
self.max_ponder_steps = int(max_ponder_steps)
|
| 113 |
+
self.min_trajectory_progress = float(min_trajectory_progress)
|
| 114 |
+
self.turn_end_token_id = int(turn_end_token_id)
|
| 115 |
+
super().__init__(
|
| 116 |
+
text_config=text_config,
|
| 117 |
+
vision_config=vision_config,
|
| 118 |
+
**kwargs,
|
| 119 |
+
)
|
| 120 |
+
self.model_type = type(self).model_type
|
| 121 |
+
if not hasattr(self, "eos_token_id"):
|
| 122 |
+
self.eos_token_id = self.text_config.eos_token_id
|
| 123 |
+
if not hasattr(self, "pad_token_id"):
|
| 124 |
+
self.pad_token_id = self.text_config.pad_token_id
|
| 125 |
+
if not hasattr(self, "bos_token_id"):
|
| 126 |
+
self.bos_token_id = self.text_config.bos_token_id
|
| 127 |
+
self._validate_modilify()
|
| 128 |
+
|
| 129 |
+
def _validate_modilify(self) -> None:
|
| 130 |
+
"""Validate inference-only extension values."""
|
| 131 |
+
|
| 132 |
+
policy_values = (
|
| 133 |
+
self.denoise_temperature,
|
| 134 |
+
self.commit_failure_budget,
|
| 135 |
+
self.fused_entropy_weight,
|
| 136 |
+
self.jump_failure_budget,
|
| 137 |
+
self.min_trajectory_progress,
|
| 138 |
+
)
|
| 139 |
+
if any(not math.isfinite(value) for value in policy_values):
|
| 140 |
+
raise ValueError("Modilify Mk1 policy values must be finite.")
|
| 141 |
+
positive = (
|
| 142 |
+
self.denoise_temperature,
|
| 143 |
+
self.commit_failure_budget,
|
| 144 |
+
self.jump_failure_budget,
|
| 145 |
+
self.vocab_chunk_size,
|
| 146 |
+
self.latent_dim,
|
| 147 |
+
self.latent_memory_slots,
|
| 148 |
+
self.latent_num_layers,
|
| 149 |
+
self.latent_num_heads,
|
| 150 |
+
self.latent_local_attention_window,
|
| 151 |
+
self.jump_on_no_progress_after,
|
| 152 |
+
self.max_ponder_steps,
|
| 153 |
+
)
|
| 154 |
+
if any(value <= 0 for value in positive):
|
| 155 |
+
raise ValueError(
|
| 156 |
+
"Modilify Mk1 dimensions, budgets, and intervals must be positive."
|
| 157 |
+
)
|
| 158 |
+
if self.fused_entropy_weight < 0:
|
| 159 |
+
raise ValueError("`fused_entropy_weight` must be non-negative.")
|
| 160 |
+
if self.latent_dim % self.latent_num_heads:
|
| 161 |
+
raise ValueError("`latent_dim` must be divisible by `latent_num_heads`.")
|
| 162 |
+
if not 0.0 <= self.latent_dropout < 1.0:
|
| 163 |
+
raise ValueError("`latent_dropout` must be in [0, 1).")
|
| 164 |
+
if self.min_trajectory_progress < 0:
|
| 165 |
+
raise ValueError("`min_trajectory_progress` must be non-negative.")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
__all__ = ["ModilifyMk1Config", "ModilifyMk1TextConfig"]
|
modilify_mk1/generation_modilify_mk1.py
ADDED
|
@@ -0,0 +1,782 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
"""Rolling generation for latent-memory Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
+
import math
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from transformers.cache_utils import Cache
|
| 13 |
+
from transformers.generation import LogitsProcessorList
|
| 14 |
+
from transformers.generation.streamers import BaseStreamer
|
| 15 |
+
from transformers.modeling_outputs import ModelOutput
|
| 16 |
+
|
| 17 |
+
from transformers.models.diffusion_gemma import (
|
| 18 |
+
DiffusionGemmaGenerationConfig,
|
| 19 |
+
DiffusionGemmaGenerationMixin,
|
| 20 |
+
)
|
| 21 |
+
from .commit_policy import fused_commit_failure_rate, select_commit_lengths
|
| 22 |
+
from .latent_deliberation import LatentDeliberationState
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ModilifyMk1GenerationConfig(DiffusionGemmaGenerationConfig):
|
| 26 |
+
"""Generation controls for the Modilify Mk1 commit policy.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
turn_end_token_id: Token that closes a native Gemma turn.
|
| 30 |
+
denoise_temperature: Sampling temperature used for every canvas step.
|
| 31 |
+
kwargs: Standard DiffusionGemma generation arguments.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
*,
|
| 37 |
+
turn_end_token_id: int | None = None,
|
| 38 |
+
denoise_temperature: float = 0.8,
|
| 39 |
+
**kwargs: Any,
|
| 40 |
+
) -> None:
|
| 41 |
+
self.turn_end_token_id = turn_end_token_id
|
| 42 |
+
self.denoise_temperature = float(denoise_temperature)
|
| 43 |
+
kwargs.pop("one_token_per_denoise_step", None)
|
| 44 |
+
kwargs["t_min"] = self.denoise_temperature
|
| 45 |
+
kwargs["t_max"] = self.denoise_temperature
|
| 46 |
+
super().__init__(**kwargs)
|
| 47 |
+
self.one_token_per_denoise_step = False
|
| 48 |
+
|
| 49 |
+
def update(self, **kwargs: Any) -> dict[str, Any]:
|
| 50 |
+
"""Apply standard generation overrides and one temperature override."""
|
| 51 |
+
|
| 52 |
+
if "denoise_temperature" in kwargs:
|
| 53 |
+
self.denoise_temperature = float(kwargs.pop("denoise_temperature"))
|
| 54 |
+
kwargs["t_min"] = self.denoise_temperature
|
| 55 |
+
kwargs["t_max"] = self.denoise_temperature
|
| 56 |
+
unused = super().update(**kwargs)
|
| 57 |
+
self.one_token_per_denoise_step = False
|
| 58 |
+
self.t_min = self.denoise_temperature
|
| 59 |
+
self.t_max = self.denoise_temperature
|
| 60 |
+
return unused
|
| 61 |
+
|
| 62 |
+
def validate(self, **kwargs: Any) -> None:
|
| 63 |
+
"""Validate fixed-temperature generation values.
|
| 64 |
+
|
| 65 |
+
DiffusionGemma's parent validator requires a non-empty temperature
|
| 66 |
+
interval. Modilify Mk1 intentionally uses one fixed temperature, so the
|
| 67 |
+
equivalent ``t_min == t_max`` configuration is validated here.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
del kwargs
|
| 71 |
+
if (
|
| 72 |
+
not math.isfinite(self.denoise_temperature)
|
| 73 |
+
or self.denoise_temperature <= 0
|
| 74 |
+
):
|
| 75 |
+
raise ValueError("`denoise_temperature` must be positive.")
|
| 76 |
+
if self.max_denoising_steps is not None and (
|
| 77 |
+
not isinstance(self.max_denoising_steps, int)
|
| 78 |
+
or self.max_denoising_steps <= 0
|
| 79 |
+
):
|
| 80 |
+
raise ValueError("`max_denoising_steps` must be a positive integer.")
|
| 81 |
+
if self.turn_end_token_id is not None and (
|
| 82 |
+
not isinstance(self.turn_end_token_id, int) or self.turn_end_token_id < 0
|
| 83 |
+
):
|
| 84 |
+
raise ValueError("`turn_end_token_id` must be a non-negative integer.")
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def from_model_config(cls, model_config: Any) -> "ModilifyMk1GenerationConfig":
|
| 88 |
+
"""Build generation defaults from a model configuration."""
|
| 89 |
+
|
| 90 |
+
return cls(
|
| 91 |
+
turn_end_token_id=model_config.turn_end_token_id,
|
| 92 |
+
denoise_temperature=model_config.denoise_temperature,
|
| 93 |
+
eos_token_id=getattr(
|
| 94 |
+
model_config,
|
| 95 |
+
"eos_token_id",
|
| 96 |
+
model_config.text_config.eos_token_id,
|
| 97 |
+
),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def _get_default_generation_params() -> dict[str, object]:
|
| 102 |
+
"""Return defaults with no inherited entropy/readiness commit controls."""
|
| 103 |
+
|
| 104 |
+
return {
|
| 105 |
+
"max_new_tokens": 256,
|
| 106 |
+
"max_denoising_steps": 48,
|
| 107 |
+
"t_min": 0.8,
|
| 108 |
+
"t_max": 0.8,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@dataclass
|
| 113 |
+
class ModilifyMk1GenerationOutput(ModelOutput):
|
| 114 |
+
"""Structured result returned by rolling block-diffusion generation."""
|
| 115 |
+
|
| 116 |
+
sequences: torch.LongTensor
|
| 117 |
+
generated_lengths: torch.LongTensor | None = None
|
| 118 |
+
tokens_per_forward: torch.FloatTensor | None = None
|
| 119 |
+
past_key_values: Cache | None = None
|
| 120 |
+
stop_reason: str | tuple[str, ...] | None = None
|
| 121 |
+
committed_tokens: int | torch.LongTensor | None = None
|
| 122 |
+
denoise_steps: int | torch.LongTensor | None = None
|
| 123 |
+
no_progress_steps: int | torch.LongTensor | None = None
|
| 124 |
+
jump_count: int | torch.LongTensor | None = None
|
| 125 |
+
forced_jump_bad_count: int | torch.LongTensor | None = None
|
| 126 |
+
heavy_forward_count: int | torch.LongTensor | None = None
|
| 127 |
+
latent_context_update_count: int | torch.LongTensor | None = None
|
| 128 |
+
average_commit_len: float | torch.FloatTensor | None = None
|
| 129 |
+
state_shift_count: int | torch.LongTensor | None = None
|
| 130 |
+
latent_memory_norm: float | torch.FloatTensor | None = None
|
| 131 |
+
state_retention_score: float | torch.FloatTensor | None = None
|
| 132 |
+
logits: None = None
|
| 133 |
+
scores: None = None
|
| 134 |
+
hidden_states: None = None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@dataclass
|
| 138 |
+
class _RollingState:
|
| 139 |
+
"""All real iterative state; no vocabulary-sized tensor is retained."""
|
| 140 |
+
|
| 141 |
+
canvas: torch.LongTensor
|
| 142 |
+
confidence: torch.FloatTensor
|
| 143 |
+
entropy: torch.FloatTensor
|
| 144 |
+
age: torch.IntTensor
|
| 145 |
+
latent_state: LatentDeliberationState
|
| 146 |
+
history_hidden_state: torch.FloatTensor | None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _retain_denoise_proposals(proposal: torch.LongTensor) -> torch.LongTensor:
|
| 150 |
+
"""Keep every latest denoise token; confidence controls commit, not writeback."""
|
| 151 |
+
if proposal.ndim != 2:
|
| 152 |
+
raise ValueError("Denoise proposals must have shape [batch, canvas].")
|
| 153 |
+
return proposal.clone()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class _NoiseCanvasSampler:
|
| 157 |
+
"""Uniform diffusion noise source with no commit-policy responsibilities."""
|
| 158 |
+
|
| 159 |
+
def __init__(self, *, canvas_length: int, vocab_size: int) -> None:
|
| 160 |
+
self.canvas_length = int(canvas_length)
|
| 161 |
+
self.vocab_size = int(vocab_size)
|
| 162 |
+
self.initial_entropy = math.log(self.vocab_size)
|
| 163 |
+
|
| 164 |
+
def initialize_canvas(
|
| 165 |
+
self,
|
| 166 |
+
batch_size: int,
|
| 167 |
+
device: torch.device,
|
| 168 |
+
) -> torch.LongTensor:
|
| 169 |
+
"""Sample a uniformly random starting canvas.
|
| 170 |
+
|
| 171 |
+
Args:
|
| 172 |
+
batch_size: Number of canvases to create.
|
| 173 |
+
device: Device on which token IDs are allocated.
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
Random token IDs with shape ``[batch_size, canvas_length]``.
|
| 177 |
+
"""
|
| 178 |
+
|
| 179 |
+
return torch.randint(
|
| 180 |
+
self.vocab_size,
|
| 181 |
+
(batch_size, self.canvas_length),
|
| 182 |
+
device=device,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
class ModilifyMk1GenerationMixin(DiffusionGemmaGenerationMixin):
|
| 187 |
+
"""Transformers-compatible rolling latent-deliberation generator."""
|
| 188 |
+
|
| 189 |
+
def _prepare_sampler(
|
| 190 |
+
self,
|
| 191 |
+
generation_config: ModilifyMk1GenerationConfig,
|
| 192 |
+
canvas_length: int | None = None,
|
| 193 |
+
) -> _NoiseCanvasSampler:
|
| 194 |
+
del generation_config
|
| 195 |
+
return _NoiseCanvasSampler(
|
| 196 |
+
canvas_length=canvas_length or self.config.canvas_length,
|
| 197 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
@staticmethod
|
| 201 |
+
def _shift_state_rows(
|
| 202 |
+
state: _RollingState,
|
| 203 |
+
commit_lengths: torch.LongTensor,
|
| 204 |
+
sampler: _NoiseCanvasSampler,
|
| 205 |
+
) -> _RollingState:
|
| 206 |
+
"""Shift every rolling row by its own committed prefix length."""
|
| 207 |
+
|
| 208 |
+
batch_size, canvas_length = state.canvas.shape
|
| 209 |
+
if commit_lengths.shape != (batch_size,):
|
| 210 |
+
raise ValueError("Commit lengths must have shape [batch].")
|
| 211 |
+
if not bool(commit_lengths.gt(0).any()):
|
| 212 |
+
return state
|
| 213 |
+
positions = torch.arange(canvas_length, device=state.canvas.device)[None, :]
|
| 214 |
+
source = positions + commit_lengths[:, None]
|
| 215 |
+
retained = source.lt(canvas_length)
|
| 216 |
+
|
| 217 |
+
def shift(value: torch.Tensor, fill_value: float | int = 0) -> torch.Tensor:
|
| 218 |
+
index = source.clamp_max(canvas_length - 1)
|
| 219 |
+
index = index.view(
|
| 220 |
+
batch_size, canvas_length, *([1] * (value.ndim - 2))
|
| 221 |
+
).expand_as(value)
|
| 222 |
+
gathered = value.gather(1, index)
|
| 223 |
+
mask = retained.view(
|
| 224 |
+
batch_size, canvas_length, *([1] * (value.ndim - 2))
|
| 225 |
+
)
|
| 226 |
+
fill = torch.as_tensor(fill_value, device=value.device, dtype=value.dtype)
|
| 227 |
+
return torch.where(mask, gathered, fill)
|
| 228 |
+
|
| 229 |
+
tail = sampler.initialize_canvas(batch_size, state.canvas.device)
|
| 230 |
+
canvas = torch.cat((state.canvas, tail), dim=1).gather(1, source)
|
| 231 |
+
unknown_entropy = float(sampler.initial_entropy)
|
| 232 |
+
latent = state.latent_state
|
| 233 |
+
committed = commit_lengths.gt(0)
|
| 234 |
+
shifted_latent = LatentDeliberationState(
|
| 235 |
+
token_latents=shift(latent.token_latents),
|
| 236 |
+
memory_slots=latent.memory_slots.clone(),
|
| 237 |
+
confidence=shift(latent.confidence),
|
| 238 |
+
entropy=shift(latent.entropy, unknown_entropy),
|
| 239 |
+
age=shift(latent.age),
|
| 240 |
+
token_changed=shift(latent.token_changed),
|
| 241 |
+
confidence_delta=shift(latent.confidence_delta),
|
| 242 |
+
entropy_delta=shift(latent.entropy_delta),
|
| 243 |
+
ponder_steps=torch.where(
|
| 244 |
+
committed, torch.zeros_like(latent.ponder_steps), latent.ponder_steps
|
| 245 |
+
),
|
| 246 |
+
stagnation_steps=torch.where(
|
| 247 |
+
committed, torch.zeros_like(latent.stagnation_steps), latent.stagnation_steps
|
| 248 |
+
),
|
| 249 |
+
)
|
| 250 |
+
return _RollingState(
|
| 251 |
+
canvas=canvas,
|
| 252 |
+
confidence=shift(state.confidence),
|
| 253 |
+
entropy=shift(state.entropy, unknown_entropy),
|
| 254 |
+
age=shift(state.age),
|
| 255 |
+
latent_state=shifted_latent,
|
| 256 |
+
history_hidden_state=(
|
| 257 |
+
None
|
| 258 |
+
if state.history_hidden_state is None
|
| 259 |
+
else shift(state.history_hidden_state)
|
| 260 |
+
),
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def _merge_state_rows(
|
| 265 |
+
previous: _RollingState,
|
| 266 |
+
updated: _RollingState,
|
| 267 |
+
update_mask: torch.BoolTensor,
|
| 268 |
+
) -> _RollingState:
|
| 269 |
+
"""Advance active rows while leaving completed rows unchanged."""
|
| 270 |
+
|
| 271 |
+
def choose(old: torch.Tensor, new: torch.Tensor) -> torch.Tensor:
|
| 272 |
+
mask = update_mask.view(
|
| 273 |
+
update_mask.shape[0],
|
| 274 |
+
*([1] * (old.ndim - 1)),
|
| 275 |
+
)
|
| 276 |
+
return torch.where(mask, new, old)
|
| 277 |
+
|
| 278 |
+
old_latent = previous.latent_state
|
| 279 |
+
new_latent = updated.latent_state
|
| 280 |
+
latent = LatentDeliberationState(
|
| 281 |
+
token_latents=choose(
|
| 282 |
+
old_latent.token_latents,
|
| 283 |
+
new_latent.token_latents,
|
| 284 |
+
),
|
| 285 |
+
memory_slots=choose(old_latent.memory_slots, new_latent.memory_slots),
|
| 286 |
+
confidence=choose(old_latent.confidence, new_latent.confidence),
|
| 287 |
+
entropy=choose(old_latent.entropy, new_latent.entropy),
|
| 288 |
+
age=choose(old_latent.age, new_latent.age),
|
| 289 |
+
token_changed=choose(
|
| 290 |
+
old_latent.token_changed,
|
| 291 |
+
new_latent.token_changed,
|
| 292 |
+
),
|
| 293 |
+
confidence_delta=choose(
|
| 294 |
+
old_latent.confidence_delta,
|
| 295 |
+
new_latent.confidence_delta,
|
| 296 |
+
),
|
| 297 |
+
entropy_delta=choose(
|
| 298 |
+
old_latent.entropy_delta,
|
| 299 |
+
new_latent.entropy_delta,
|
| 300 |
+
),
|
| 301 |
+
ponder_steps=choose(
|
| 302 |
+
old_latent.ponder_steps,
|
| 303 |
+
new_latent.ponder_steps,
|
| 304 |
+
),
|
| 305 |
+
stagnation_steps=choose(
|
| 306 |
+
old_latent.stagnation_steps,
|
| 307 |
+
new_latent.stagnation_steps,
|
| 308 |
+
),
|
| 309 |
+
)
|
| 310 |
+
history = previous.history_hidden_state
|
| 311 |
+
if updated.history_hidden_state is not None:
|
| 312 |
+
history = (
|
| 313 |
+
updated.history_hidden_state
|
| 314 |
+
if history is None
|
| 315 |
+
else choose(history, updated.history_hidden_state)
|
| 316 |
+
)
|
| 317 |
+
return _RollingState(
|
| 318 |
+
canvas=choose(previous.canvas, updated.canvas),
|
| 319 |
+
confidence=choose(previous.confidence, updated.confidence),
|
| 320 |
+
entropy=choose(previous.entropy, updated.entropy),
|
| 321 |
+
age=choose(previous.age, updated.age),
|
| 322 |
+
latent_state=latent,
|
| 323 |
+
history_hidden_state=history,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
@torch.inference_mode()
|
| 327 |
+
def generate(
|
| 328 |
+
self,
|
| 329 |
+
input_ids: torch.LongTensor | None = None,
|
| 330 |
+
past_key_values: Cache | None = None,
|
| 331 |
+
streamer: BaseStreamer | None = None,
|
| 332 |
+
generation_config: ModilifyMk1GenerationConfig | None = None,
|
| 333 |
+
logits_processor: LogitsProcessorList | None = None,
|
| 334 |
+
**kwargs,
|
| 335 |
+
) -> ModilifyMk1GenerationOutput:
|
| 336 |
+
"""Generate one or more responses with rolling block diffusion.
|
| 337 |
+
|
| 338 |
+
Args:
|
| 339 |
+
input_ids: Tokenized prompts with shape ``[batch, sequence]``.
|
| 340 |
+
past_key_values: Optional existing encoder cache.
|
| 341 |
+
streamer: Optional standard Transformers token streamer.
|
| 342 |
+
generation_config: Generation limits and token IDs.
|
| 343 |
+
logits_processor: Unsupported custom logits processors.
|
| 344 |
+
**kwargs: Standard multimodal encoder inputs and generation values.
|
| 345 |
+
|
| 346 |
+
Returns:
|
| 347 |
+
Generated sequences and diffusion diagnostics.
|
| 348 |
+
|
| 349 |
+
Raises:
|
| 350 |
+
ValueError: If inputs are invalid or unsupported logits processing
|
| 351 |
+
is requested.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
generation_config, model_kwargs = self._prepare_generation_config(
|
| 355 |
+
generation_config,
|
| 356 |
+
**kwargs,
|
| 357 |
+
)
|
| 358 |
+
if input_ids is None or input_ids.ndim != 2 or input_ids.shape[0] < 1:
|
| 359 |
+
raise ValueError(
|
| 360 |
+
"Modilify Mk1 generation requires `input_ids` with shape "
|
| 361 |
+
"[batch, sequence]."
|
| 362 |
+
)
|
| 363 |
+
if logits_processor:
|
| 364 |
+
raise ValueError(
|
| 365 |
+
"Modilify Mk1 samples the configured fixed-temperature distribution "
|
| 366 |
+
"and does not accept custom logits processors."
|
| 367 |
+
)
|
| 368 |
+
batch_size, input_width = input_ids.shape
|
| 369 |
+
if batch_size > 1 and streamer is not None:
|
| 370 |
+
raise ValueError("Streamers currently support batch size 1 only.")
|
| 371 |
+
if batch_size > 1 and past_key_values is not None:
|
| 372 |
+
raise ValueError("Batched generation requires a fresh KV cache.")
|
| 373 |
+
device = input_ids.device
|
| 374 |
+
dtype = self.model.decoder.embed_tokens.weight.dtype
|
| 375 |
+
canvas_length = self.config.canvas_length
|
| 376 |
+
cached_length = (
|
| 377 |
+
past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 378 |
+
)
|
| 379 |
+
_, max_new_tokens = self._prepare_generated_length(
|
| 380 |
+
generation_config, cached_length + input_width
|
| 381 |
+
)
|
| 382 |
+
max_iterations = max(1, max_new_tokens * self.config.max_ponder_steps)
|
| 383 |
+
if past_key_values is None:
|
| 384 |
+
past_key_values = self._prepare_cache_for_generation(
|
| 385 |
+
generation_config,
|
| 386 |
+
batch_size=batch_size,
|
| 387 |
+
# Ragged rows append dense masked blocks. If different rows
|
| 388 |
+
# advance in different iterations, physical cache width can
|
| 389 |
+
# reach the sum of all per-row generation limits.
|
| 390 |
+
max_length=input_width + batch_size * max_new_tokens,
|
| 391 |
+
)
|
| 392 |
+
expected_mask_width = cached_length + input_width
|
| 393 |
+
cache_attention_mask = model_kwargs.pop(
|
| 394 |
+
"attention_mask",
|
| 395 |
+
torch.ones(
|
| 396 |
+
batch_size, expected_mask_width, dtype=torch.bool, device=device
|
| 397 |
+
),
|
| 398 |
+
).bool()
|
| 399 |
+
if cache_attention_mask.shape != (batch_size, expected_mask_width):
|
| 400 |
+
raise ValueError(
|
| 401 |
+
"`attention_mask` must have shape [batch, cached_length + sequence]."
|
| 402 |
+
)
|
| 403 |
+
provided_position_ids = model_kwargs.pop("position_ids", None)
|
| 404 |
+
if provided_position_ids is not None:
|
| 405 |
+
if provided_position_ids.shape != input_ids.shape:
|
| 406 |
+
raise ValueError("`position_ids` must have the same shape as `input_ids`.")
|
| 407 |
+
prompt_positions = provided_position_ids.to(device=device, dtype=torch.int32)
|
| 408 |
+
elif cached_length:
|
| 409 |
+
prompt_positions = torch.arange(
|
| 410 |
+
cached_length,
|
| 411 |
+
cached_length + input_width,
|
| 412 |
+
device=device,
|
| 413 |
+
dtype=torch.int32,
|
| 414 |
+
).unsqueeze(0)
|
| 415 |
+
else:
|
| 416 |
+
input_mask = cache_attention_mask[:, -input_width:]
|
| 417 |
+
prompt_positions = (
|
| 418 |
+
input_mask.long()
|
| 419 |
+
.cumsum(dim=-1)
|
| 420 |
+
.sub(1)
|
| 421 |
+
.clamp_min(0)
|
| 422 |
+
.to(torch.int32)
|
| 423 |
+
)
|
| 424 |
+
logical_lengths = cache_attention_mask.long().sum(dim=-1)
|
| 425 |
+
if input_width:
|
| 426 |
+
encoder_keys = ("pixel_values", "mm_token_type_ids", "image_position_ids")
|
| 427 |
+
encoder_kwargs = {
|
| 428 |
+
key: model_kwargs.pop(key)
|
| 429 |
+
for key in encoder_keys
|
| 430 |
+
if key in model_kwargs
|
| 431 |
+
}
|
| 432 |
+
past_key_values = self.model.encoder(
|
| 433 |
+
input_ids=input_ids,
|
| 434 |
+
attention_mask=cache_attention_mask,
|
| 435 |
+
past_key_values=past_key_values,
|
| 436 |
+
position_ids=prompt_positions,
|
| 437 |
+
**encoder_kwargs,
|
| 438 |
+
).past_key_values
|
| 439 |
+
|
| 440 |
+
sampler = self._prepare_sampler(generation_config, canvas_length)
|
| 441 |
+
latent = LatentDeliberationState.empty(
|
| 442 |
+
batch_size=batch_size,
|
| 443 |
+
canvas_length=canvas_length,
|
| 444 |
+
latent_dim=self.config.latent_dim,
|
| 445 |
+
memory_slots=self.config.latent_memory_slots,
|
| 446 |
+
device=device,
|
| 447 |
+
dtype=dtype,
|
| 448 |
+
)
|
| 449 |
+
state = _RollingState(
|
| 450 |
+
canvas=sampler.initialize_canvas(batch_size, device),
|
| 451 |
+
confidence=torch.zeros(
|
| 452 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 453 |
+
),
|
| 454 |
+
entropy=torch.full(
|
| 455 |
+
(batch_size, canvas_length),
|
| 456 |
+
math.log(self.config.text_config.vocab_size),
|
| 457 |
+
device=device,
|
| 458 |
+
dtype=torch.float32,
|
| 459 |
+
),
|
| 460 |
+
age=torch.zeros(
|
| 461 |
+
batch_size, canvas_length, device=device, dtype=torch.int32
|
| 462 |
+
),
|
| 463 |
+
latent_state=latent,
|
| 464 |
+
history_hidden_state=None,
|
| 465 |
+
)
|
| 466 |
+
turn_end = (
|
| 467 |
+
self.config.turn_end_token_id
|
| 468 |
+
if generation_config.turn_end_token_id is None
|
| 469 |
+
else generation_config.turn_end_token_id
|
| 470 |
+
)
|
| 471 |
+
configured_eos = generation_config.eos_token_id
|
| 472 |
+
if configured_eos is None:
|
| 473 |
+
configured_eos = self.config.eos_token_id
|
| 474 |
+
if isinstance(configured_eos, int):
|
| 475 |
+
configured_eos = [configured_eos]
|
| 476 |
+
stop_token_ids = tuple(
|
| 477 |
+
dict.fromkeys((int(turn_end), *(int(value) for value in configured_eos or ())))
|
| 478 |
+
)
|
| 479 |
+
pad_token_id = generation_config.pad_token_id
|
| 480 |
+
if pad_token_id is None:
|
| 481 |
+
pad_token_id = getattr(self.config, "pad_token_id", None)
|
| 482 |
+
if isinstance(pad_token_id, (list, tuple)):
|
| 483 |
+
pad_token_id = pad_token_id[0]
|
| 484 |
+
pad_token_id = int(0 if pad_token_id is None else pad_token_id)
|
| 485 |
+
generated = torch.full(
|
| 486 |
+
(batch_size, max_new_tokens),
|
| 487 |
+
pad_token_id,
|
| 488 |
+
dtype=input_ids.dtype,
|
| 489 |
+
device=device,
|
| 490 |
+
)
|
| 491 |
+
committed = torch.zeros(batch_size, dtype=torch.long, device=device)
|
| 492 |
+
denoise_steps = torch.zeros_like(committed)
|
| 493 |
+
jumps = torch.zeros_like(committed)
|
| 494 |
+
forced_jump_tokens = torch.zeros_like(committed)
|
| 495 |
+
shifts = torch.zeros_like(committed)
|
| 496 |
+
retention_scores = torch.zeros(batch_size, dtype=torch.float32, device=device)
|
| 497 |
+
stop_codes = torch.zeros_like(committed)
|
| 498 |
+
active_rows = torch.ones(batch_size, dtype=torch.bool, device=device)
|
| 499 |
+
canvas_positions = torch.arange(canvas_length, device=device)[None, :]
|
| 500 |
+
if streamer is not None:
|
| 501 |
+
streamer.put(input_ids.cpu())
|
| 502 |
+
|
| 503 |
+
while bool(active_rows.any()):
|
| 504 |
+
decoder_positions = (
|
| 505 |
+
logical_lengths[:, None]
|
| 506 |
+
+ canvas_positions
|
| 507 |
+
).to(torch.int32)
|
| 508 |
+
denoise_steps += active_rows.long()
|
| 509 |
+
decoder_attention_mask = torch.cat(
|
| 510 |
+
(
|
| 511 |
+
cache_attention_mask,
|
| 512 |
+
torch.ones(
|
| 513 |
+
batch_size,
|
| 514 |
+
canvas_length,
|
| 515 |
+
dtype=torch.bool,
|
| 516 |
+
device=device,
|
| 517 |
+
),
|
| 518 |
+
),
|
| 519 |
+
dim=-1,
|
| 520 |
+
)
|
| 521 |
+
output = self(
|
| 522 |
+
input_ids=None,
|
| 523 |
+
past_key_values=past_key_values,
|
| 524 |
+
decoder_input_ids=state.canvas,
|
| 525 |
+
previous_confidence=state.confidence,
|
| 526 |
+
previous_entropy=state.entropy,
|
| 527 |
+
token_age=state.age,
|
| 528 |
+
latent_state=state.latent_state,
|
| 529 |
+
history_hidden_state=state.history_hidden_state,
|
| 530 |
+
decoder_position_ids=decoder_positions,
|
| 531 |
+
decoder_read_cache=True,
|
| 532 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 533 |
+
return_proposal_statistics=True,
|
| 534 |
+
denoise_temperature=generation_config.denoise_temperature,
|
| 535 |
+
**model_kwargs,
|
| 536 |
+
)
|
| 537 |
+
if any(
|
| 538 |
+
value is None
|
| 539 |
+
for value in (
|
| 540 |
+
output.proposal,
|
| 541 |
+
output.proposal_confidence,
|
| 542 |
+
output.token_entropy,
|
| 543 |
+
output.greedy_proposal,
|
| 544 |
+
output.greedy_confidence,
|
| 545 |
+
)
|
| 546 |
+
):
|
| 547 |
+
raise RuntimeError("Model forward did not return proposal statistics.")
|
| 548 |
+
proposal = output.proposal
|
| 549 |
+
proposal_confidence = output.proposal_confidence
|
| 550 |
+
token_entropy = output.token_entropy
|
| 551 |
+
greedy_proposal = output.greedy_proposal
|
| 552 |
+
greedy_confidence = output.greedy_confidence
|
| 553 |
+
next_canvas = _retain_denoise_proposals(proposal)
|
| 554 |
+
next_confidence = proposal_confidence.float()
|
| 555 |
+
next_latent = replace(
|
| 556 |
+
output.next_latent_state,
|
| 557 |
+
confidence=next_confidence.detach().float(),
|
| 558 |
+
entropy=token_entropy.detach().float(),
|
| 559 |
+
age=state.age + 1,
|
| 560 |
+
token_changed=next_canvas.ne(state.canvas).detach().float(),
|
| 561 |
+
confidence_delta=next_confidence.detach().float() - state.confidence,
|
| 562 |
+
entropy_delta=token_entropy.detach().float() - state.entropy,
|
| 563 |
+
)
|
| 564 |
+
next_state = _RollingState(
|
| 565 |
+
canvas=next_canvas,
|
| 566 |
+
confidence=next_confidence,
|
| 567 |
+
entropy=token_entropy,
|
| 568 |
+
age=state.age + 1,
|
| 569 |
+
latent_state=next_latent,
|
| 570 |
+
history_hidden_state=output.heavy_hidden_state,
|
| 571 |
+
)
|
| 572 |
+
next_state = self._merge_state_rows(state, next_state, active_rows)
|
| 573 |
+
remaining = torch.tensor(
|
| 574 |
+
max_new_tokens, device=device, dtype=torch.long
|
| 575 |
+
).sub(committed)
|
| 576 |
+
normal_failure_rate = fused_commit_failure_rate(
|
| 577 |
+
proposal_confidence, token_entropy,
|
| 578 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 579 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 580 |
+
)
|
| 581 |
+
jump_failure_rate = fused_commit_failure_rate(
|
| 582 |
+
greedy_confidence, token_entropy,
|
| 583 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 584 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 585 |
+
)
|
| 586 |
+
previous_failure_rate = fused_commit_failure_rate(
|
| 587 |
+
state.confidence, state.entropy,
|
| 588 |
+
vocab_size=self.config.text_config.vocab_size,
|
| 589 |
+
entropy_weight=self.config.fused_entropy_weight,
|
| 590 |
+
)
|
| 591 |
+
policy_decision = select_commit_lengths(
|
| 592 |
+
sampled_token_ids=proposal,
|
| 593 |
+
normal_failure_rate=normal_failure_rate,
|
| 594 |
+
previous_failure_rate=previous_failure_rate,
|
| 595 |
+
greedy_token_ids=greedy_proposal,
|
| 596 |
+
jump_failure_rate=jump_failure_rate,
|
| 597 |
+
ponder_steps=state.latent_state.ponder_steps,
|
| 598 |
+
stagnation_steps=state.latent_state.stagnation_steps,
|
| 599 |
+
active_rows=active_rows,
|
| 600 |
+
remaining_lengths=remaining,
|
| 601 |
+
failure_budget=self.config.commit_failure_budget,
|
| 602 |
+
jump_failure_budget=self.config.jump_failure_budget,
|
| 603 |
+
stop_token_id=stop_token_ids,
|
| 604 |
+
max_ponder_steps=self.config.max_ponder_steps,
|
| 605 |
+
stagnation_threshold=self.config.jump_on_no_progress_after,
|
| 606 |
+
min_progress=self.config.min_trajectory_progress,
|
| 607 |
+
)
|
| 608 |
+
next_ponder = policy_decision.ponder_steps
|
| 609 |
+
next_stagnation = policy_decision.stagnation_steps
|
| 610 |
+
commit_lengths = policy_decision.commit_lengths
|
| 611 |
+
jump_rows = policy_decision.jump_rows
|
| 612 |
+
jumps += jump_rows.long()
|
| 613 |
+
forced_jump_tokens += torch.where(
|
| 614 |
+
jump_rows, commit_lengths, torch.zeros_like(commit_lengths)
|
| 615 |
+
)
|
| 616 |
+
commit_positions = canvas_positions.lt(commit_lengths[:, None])
|
| 617 |
+
if bool(jump_rows.any()):
|
| 618 |
+
next_state = replace(
|
| 619 |
+
next_state,
|
| 620 |
+
canvas=torch.where(
|
| 621 |
+
commit_positions & jump_rows[:, None],
|
| 622 |
+
policy_decision.commit_token_ids,
|
| 623 |
+
next_state.canvas,
|
| 624 |
+
),
|
| 625 |
+
)
|
| 626 |
+
next_state = replace(
|
| 627 |
+
next_state,
|
| 628 |
+
latent_state=replace(
|
| 629 |
+
next_state.latent_state,
|
| 630 |
+
ponder_steps=next_ponder,
|
| 631 |
+
stagnation_steps=next_stagnation,
|
| 632 |
+
),
|
| 633 |
+
)
|
| 634 |
+
commit_token_ids = policy_decision.commit_token_ids
|
| 635 |
+
before = committed.clone()
|
| 636 |
+
write_rows = torch.arange(batch_size, device=device)[:, None].expand_as(
|
| 637 |
+
commit_token_ids
|
| 638 |
+
)
|
| 639 |
+
write_positions = before[:, None] + canvas_positions
|
| 640 |
+
generated[
|
| 641 |
+
write_rows[commit_positions], write_positions[commit_positions]
|
| 642 |
+
] = commit_token_ids[commit_positions]
|
| 643 |
+
|
| 644 |
+
commit_width = int(commit_lengths.max())
|
| 645 |
+
if commit_width:
|
| 646 |
+
block_mask = torch.arange(commit_width, device=device)[None, :].lt(
|
| 647 |
+
commit_lengths[:, None]
|
| 648 |
+
)
|
| 649 |
+
committed_block = torch.where(
|
| 650 |
+
block_mask,
|
| 651 |
+
commit_token_ids[:, :commit_width],
|
| 652 |
+
torch.full(
|
| 653 |
+
(batch_size, commit_width),
|
| 654 |
+
pad_token_id,
|
| 655 |
+
device=device,
|
| 656 |
+
dtype=input_ids.dtype,
|
| 657 |
+
),
|
| 658 |
+
)
|
| 659 |
+
block_positions = (
|
| 660 |
+
logical_lengths[:, None]
|
| 661 |
+
+ canvas_positions[:, :commit_width]
|
| 662 |
+
).to(torch.int32)
|
| 663 |
+
block_positions = torch.where(
|
| 664 |
+
block_mask, block_positions, torch.zeros_like(block_positions)
|
| 665 |
+
)
|
| 666 |
+
cache_attention_mask = torch.cat(
|
| 667 |
+
(cache_attention_mask, block_mask), dim=-1
|
| 668 |
+
)
|
| 669 |
+
past_key_values = self.model.encoder(
|
| 670 |
+
input_ids=committed_block,
|
| 671 |
+
attention_mask=cache_attention_mask,
|
| 672 |
+
past_key_values=past_key_values,
|
| 673 |
+
position_ids=block_positions,
|
| 674 |
+
).past_key_values
|
| 675 |
+
if streamer is not None:
|
| 676 |
+
streamer.put(committed_block.cpu())
|
| 677 |
+
committed += commit_lengths
|
| 678 |
+
logical_lengths += commit_lengths
|
| 679 |
+
committed_rows = commit_lengths.gt(0)
|
| 680 |
+
shifts += committed_rows.long()
|
| 681 |
+
shifted = self._shift_state_rows(next_state, commit_lengths, sampler)
|
| 682 |
+
retention_scores += committed_rows.float()
|
| 683 |
+
state = shifted
|
| 684 |
+
|
| 685 |
+
turn_hits = (
|
| 686 |
+
commit_token_ids.eq(turn_end) & commit_positions
|
| 687 |
+
).any(dim=-1)
|
| 688 |
+
eos_hits = torch.zeros_like(turn_hits)
|
| 689 |
+
for token_id in stop_token_ids:
|
| 690 |
+
if token_id != turn_end:
|
| 691 |
+
eos_hits |= (
|
| 692 |
+
commit_token_ids.eq(token_id) & commit_positions
|
| 693 |
+
).any(dim=-1)
|
| 694 |
+
stop_codes = torch.where(
|
| 695 |
+
stop_codes.eq(0) & turn_hits,
|
| 696 |
+
torch.ones_like(stop_codes),
|
| 697 |
+
stop_codes,
|
| 698 |
+
)
|
| 699 |
+
stop_codes = torch.where(
|
| 700 |
+
stop_codes.eq(0) & eos_hits,
|
| 701 |
+
torch.full_like(stop_codes, 2),
|
| 702 |
+
stop_codes,
|
| 703 |
+
)
|
| 704 |
+
stop_codes = torch.where(
|
| 705 |
+
stop_codes.eq(0) & committed.ge(max_new_tokens),
|
| 706 |
+
torch.full_like(stop_codes, 3),
|
| 707 |
+
stop_codes,
|
| 708 |
+
)
|
| 709 |
+
if generation_config.max_denoising_steps is not None:
|
| 710 |
+
stop_codes = torch.where(
|
| 711 |
+
stop_codes.eq(0)
|
| 712 |
+
& denoise_steps.ge(generation_config.max_denoising_steps),
|
| 713 |
+
torch.full_like(stop_codes, 4),
|
| 714 |
+
stop_codes,
|
| 715 |
+
)
|
| 716 |
+
stop_codes = torch.where(
|
| 717 |
+
stop_codes.eq(0) & denoise_steps.ge(max_iterations),
|
| 718 |
+
torch.full_like(stop_codes, 5),
|
| 719 |
+
stop_codes,
|
| 720 |
+
)
|
| 721 |
+
active_rows = stop_codes.eq(0)
|
| 722 |
+
|
| 723 |
+
output_width = int(committed.max())
|
| 724 |
+
sequences = torch.cat((input_ids, generated[:, :output_width]), dim=-1)
|
| 725 |
+
if streamer is not None:
|
| 726 |
+
streamer.end()
|
| 727 |
+
reason_names = {
|
| 728 |
+
1: "turn_end",
|
| 729 |
+
2: "eos",
|
| 730 |
+
3: "max_new_tokens",
|
| 731 |
+
4: "max_denoising_steps",
|
| 732 |
+
5: "episode_watchdog",
|
| 733 |
+
}
|
| 734 |
+
stop_reasons = tuple(
|
| 735 |
+
reason_names.get(code, "unknown")
|
| 736 |
+
for code in stop_codes.detach().cpu().tolist()
|
| 737 |
+
)
|
| 738 |
+
tokens_per_forward = committed.float() / denoise_steps.clamp_min(1).float()
|
| 739 |
+
average_commit_len = committed.float() / shifts.clamp_min(1).float()
|
| 740 |
+
latent_memory_norm = (
|
| 741 |
+
state.latent_state.memory_slots.float().norm(dim=-1).mean(dim=-1)
|
| 742 |
+
)
|
| 743 |
+
state_retention_score = retention_scores / shifts.clamp_min(1).float()
|
| 744 |
+
|
| 745 |
+
def scalar_or_tensor(
|
| 746 |
+
value: torch.Tensor,
|
| 747 |
+
*,
|
| 748 |
+
floating: bool = False,
|
| 749 |
+
) -> int | float | torch.Tensor:
|
| 750 |
+
if batch_size > 1:
|
| 751 |
+
return value
|
| 752 |
+
item = value[0].item()
|
| 753 |
+
return float(item) if floating else int(item)
|
| 754 |
+
|
| 755 |
+
return ModilifyMk1GenerationOutput(
|
| 756 |
+
sequences=sequences,
|
| 757 |
+
generated_lengths=committed.clone(),
|
| 758 |
+
tokens_per_forward=tokens_per_forward,
|
| 759 |
+
past_key_values=past_key_values,
|
| 760 |
+
stop_reason=stop_reasons[0] if batch_size == 1 else stop_reasons,
|
| 761 |
+
committed_tokens=scalar_or_tensor(committed),
|
| 762 |
+
denoise_steps=scalar_or_tensor(denoise_steps),
|
| 763 |
+
no_progress_steps=scalar_or_tensor(state.latent_state.stagnation_steps),
|
| 764 |
+
jump_count=scalar_or_tensor(jumps),
|
| 765 |
+
forced_jump_bad_count=scalar_or_tensor(forced_jump_tokens),
|
| 766 |
+
heavy_forward_count=scalar_or_tensor(denoise_steps),
|
| 767 |
+
latent_context_update_count=scalar_or_tensor(denoise_steps),
|
| 768 |
+
average_commit_len=scalar_or_tensor(average_commit_len, floating=True),
|
| 769 |
+
state_shift_count=scalar_or_tensor(shifts),
|
| 770 |
+
latent_memory_norm=scalar_or_tensor(latent_memory_norm, floating=True),
|
| 771 |
+
state_retention_score=scalar_or_tensor(
|
| 772 |
+
state_retention_score,
|
| 773 |
+
floating=True,
|
| 774 |
+
),
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
__all__ = [
|
| 779 |
+
"ModilifyMk1GenerationConfig",
|
| 780 |
+
"ModilifyMk1GenerationMixin",
|
| 781 |
+
"ModilifyMk1GenerationOutput",
|
| 782 |
+
]
|
modilify_mk1/latent_deliberation.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Fixed-shape latent deliberation state for Modilify Mk1 decoding.
|
| 4 |
+
|
| 5 |
+
The state deliberately contains no vocabulary-sized tensors. Keeping the
|
| 6 |
+
per-canvas information in a small latent space prevents iterative diffusion
|
| 7 |
+
rollouts from retaining one logits/probability allocation per denoise pass.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch import nn
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class LatentDeliberationState:
|
| 20 |
+
"""Persistent, fixed-size state for one or more canvas episodes."""
|
| 21 |
+
|
| 22 |
+
token_latents: torch.Tensor
|
| 23 |
+
memory_slots: torch.Tensor
|
| 24 |
+
confidence: torch.Tensor
|
| 25 |
+
entropy: torch.Tensor
|
| 26 |
+
age: torch.Tensor
|
| 27 |
+
token_changed: torch.Tensor
|
| 28 |
+
confidence_delta: torch.Tensor
|
| 29 |
+
entropy_delta: torch.Tensor
|
| 30 |
+
ponder_steps: torch.Tensor
|
| 31 |
+
stagnation_steps: torch.Tensor
|
| 32 |
+
|
| 33 |
+
@classmethod
|
| 34 |
+
def empty(
|
| 35 |
+
cls,
|
| 36 |
+
*,
|
| 37 |
+
batch_size: int,
|
| 38 |
+
canvas_length: int,
|
| 39 |
+
latent_dim: int,
|
| 40 |
+
memory_slots: int,
|
| 41 |
+
device: torch.device,
|
| 42 |
+
dtype: torch.dtype,
|
| 43 |
+
) -> "LatentDeliberationState":
|
| 44 |
+
"""Create a zero-initialized recurrent state.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
batch_size: Number of independent sequences.
|
| 48 |
+
canvas_length: Number of rolling canvas positions.
|
| 49 |
+
latent_dim: Width of each latent token and memory slot.
|
| 50 |
+
memory_slots: Number of persistent memory slots.
|
| 51 |
+
device: Allocation device.
|
| 52 |
+
dtype: Floating-point dtype for latent tensors.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
A zero-initialized state with integer progress clocks.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
return cls(
|
| 59 |
+
token_latents=torch.zeros(
|
| 60 |
+
batch_size, canvas_length, latent_dim, device=device, dtype=dtype
|
| 61 |
+
),
|
| 62 |
+
memory_slots=torch.zeros(
|
| 63 |
+
batch_size, memory_slots, latent_dim, device=device, dtype=dtype
|
| 64 |
+
),
|
| 65 |
+
confidence=torch.zeros(
|
| 66 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 67 |
+
),
|
| 68 |
+
entropy=torch.zeros(
|
| 69 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 70 |
+
),
|
| 71 |
+
age=torch.zeros(
|
| 72 |
+
batch_size, canvas_length, device=device, dtype=torch.int32
|
| 73 |
+
),
|
| 74 |
+
token_changed=torch.zeros(
|
| 75 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 76 |
+
),
|
| 77 |
+
confidence_delta=torch.zeros(
|
| 78 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 79 |
+
),
|
| 80 |
+
entropy_delta=torch.zeros(
|
| 81 |
+
batch_size, canvas_length, device=device, dtype=torch.float32
|
| 82 |
+
),
|
| 83 |
+
ponder_steps=torch.zeros(batch_size, device=device, dtype=torch.int32),
|
| 84 |
+
stagnation_steps=torch.zeros(batch_size, device=device, dtype=torch.int32),
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def advance_trajectory_clocks(
|
| 89 |
+
ponder_steps: torch.Tensor,
|
| 90 |
+
stagnation_steps: torch.Tensor,
|
| 91 |
+
*,
|
| 92 |
+
commit_lengths: torch.LongTensor,
|
| 93 |
+
active_rows: torch.BoolTensor,
|
| 94 |
+
progress_scores: torch.Tensor,
|
| 95 |
+
min_progress: float,
|
| 96 |
+
) -> tuple[torch.IntTensor, torch.IntTensor]:
|
| 97 |
+
"""Advance useful-ponder and true-stagnation clocks for each row.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
ponder_steps: Total waiting steps for each row.
|
| 101 |
+
stagnation_steps: Consecutive non-improving steps for each row.
|
| 102 |
+
commit_lengths: Number of committed tokens for each row.
|
| 103 |
+
active_rows: Rows that are still generating.
|
| 104 |
+
progress_scores: Signed fused-risk improvements.
|
| 105 |
+
min_progress: Smallest improvement that resets stagnation.
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
Updated ponder and stagnation counters.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
if min_progress < 0:
|
| 112 |
+
raise ValueError("`min_progress` must be non-negative.")
|
| 113 |
+
if not (
|
| 114 |
+
ponder_steps.shape == stagnation_steps.shape == commit_lengths.shape
|
| 115 |
+
== active_rows.shape == progress_scores.shape
|
| 116 |
+
):
|
| 117 |
+
raise ValueError("Trajectory clock inputs must share shape [batch].")
|
| 118 |
+
committed = commit_lengths.gt(0)
|
| 119 |
+
waiting = active_rows & ~committed
|
| 120 |
+
improving = progress_scores.ge(min_progress)
|
| 121 |
+
next_ponder = torch.where(
|
| 122 |
+
committed, torch.zeros_like(ponder_steps), ponder_steps + waiting.to(torch.int32)
|
| 123 |
+
)
|
| 124 |
+
next_stagnation = torch.where(
|
| 125 |
+
committed,
|
| 126 |
+
torch.zeros_like(stagnation_steps),
|
| 127 |
+
torch.where(
|
| 128 |
+
waiting & improving,
|
| 129 |
+
torch.zeros_like(stagnation_steps),
|
| 130 |
+
stagnation_steps + waiting.to(torch.int32),
|
| 131 |
+
),
|
| 132 |
+
)
|
| 133 |
+
return next_ponder.to(torch.int32), next_stagnation.to(torch.int32)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def should_force_trajectory_jump(
|
| 137 |
+
ponder_steps: torch.Tensor,
|
| 138 |
+
stagnation_steps: torch.Tensor,
|
| 139 |
+
*,
|
| 140 |
+
max_ponder_steps: int,
|
| 141 |
+
stagnation_threshold: int,
|
| 142 |
+
) -> torch.BoolTensor:
|
| 143 |
+
"""Return rows that exhausted either inference progress clock.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
ponder_steps: Total waiting steps for each row.
|
| 147 |
+
stagnation_steps: Consecutive non-improving steps for each row.
|
| 148 |
+
max_ponder_steps: Maximum allowed waiting steps.
|
| 149 |
+
stagnation_threshold: Maximum consecutive stagnation steps.
|
| 150 |
+
|
| 151 |
+
Returns:
|
| 152 |
+
Boolean mask selecting rows that must use a forced jump.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
if max_ponder_steps <= 0 or stagnation_threshold <= 0:
|
| 156 |
+
raise ValueError("Trajectory jump limits must be positive.")
|
| 157 |
+
return ponder_steps.ge(max_ponder_steps) | stagnation_steps.ge(stagnation_threshold)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class _TemporalTransformerCell(nn.Module):
|
| 161 |
+
"""One-step recurrent token update with fixed-slot memory attention."""
|
| 162 |
+
|
| 163 |
+
def __init__(
|
| 164 |
+
self, latent_dim: int, num_heads: int, dropout: float,
|
| 165 |
+
local_attention_window: int,
|
| 166 |
+
) -> None:
|
| 167 |
+
super().__init__()
|
| 168 |
+
self.state_norm = nn.LayerNorm(latent_dim)
|
| 169 |
+
self.observation_norm = nn.LayerNorm(latent_dim)
|
| 170 |
+
# A slot's learned identity is only used for attention addressing. The
|
| 171 |
+
# recurrent state itself remains pure memory content so commit shifts
|
| 172 |
+
# cannot accidentally write positional identity into persistent state.
|
| 173 |
+
self.memory_address_norm = nn.LayerNorm(latent_dim)
|
| 174 |
+
self.memory_value_norm = nn.LayerNorm(latent_dim)
|
| 175 |
+
self.temporal_update = nn.Linear(2 * latent_dim, 2 * latent_dim)
|
| 176 |
+
self.local_attention = nn.MultiheadAttention(
|
| 177 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 178 |
+
)
|
| 179 |
+
self.local_attention_window = local_attention_window
|
| 180 |
+
self.register_buffer("_local_attention_mask", torch.empty(0), persistent=False)
|
| 181 |
+
self.token_memory_attention = nn.MultiheadAttention(
|
| 182 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 183 |
+
)
|
| 184 |
+
self.memory_token_attention = nn.MultiheadAttention(
|
| 185 |
+
latent_dim, num_heads, dropout=dropout, batch_first=True
|
| 186 |
+
)
|
| 187 |
+
self.token_ff_norm = nn.LayerNorm(latent_dim)
|
| 188 |
+
self.memory_ff_norm = nn.LayerNorm(latent_dim)
|
| 189 |
+
self.stored_token_norm = nn.LayerNorm(latent_dim)
|
| 190 |
+
self.stored_memory_norm = nn.LayerNorm(latent_dim)
|
| 191 |
+
expansion = latent_dim * 4
|
| 192 |
+
self.token_ff = nn.Sequential(
|
| 193 |
+
nn.Linear(latent_dim, expansion),
|
| 194 |
+
nn.SiLU(),
|
| 195 |
+
nn.Linear(expansion, latent_dim),
|
| 196 |
+
)
|
| 197 |
+
self.memory_ff = nn.Sequential(
|
| 198 |
+
nn.Linear(latent_dim, expansion),
|
| 199 |
+
nn.SiLU(),
|
| 200 |
+
nn.Linear(expansion, latent_dim),
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
def forward(
|
| 204 |
+
self,
|
| 205 |
+
previous_tokens: torch.Tensor,
|
| 206 |
+
observation: torch.Tensor,
|
| 207 |
+
memory: torch.Tensor,
|
| 208 |
+
memory_slot_identity: torch.Tensor,
|
| 209 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 210 |
+
gate_logits, candidate = self.temporal_update(
|
| 211 |
+
torch.cat(
|
| 212 |
+
(self.state_norm(previous_tokens), self.observation_norm(observation)),
|
| 213 |
+
dim=-1,
|
| 214 |
+
)
|
| 215 |
+
).chunk(2, dim=-1)
|
| 216 |
+
gate = torch.sigmoid(gate_logits)
|
| 217 |
+
tokens = gate * previous_tokens + (1.0 - gate) * torch.nn.functional.silu(candidate)
|
| 218 |
+
if (
|
| 219 |
+
self._local_attention_mask.shape != (tokens.shape[1], tokens.shape[1])
|
| 220 |
+
or self._local_attention_mask.device != tokens.device
|
| 221 |
+
or self._local_attention_mask.dtype != tokens.dtype
|
| 222 |
+
):
|
| 223 |
+
positions = torch.arange(tokens.shape[1], device=tokens.device)
|
| 224 |
+
allowed = (
|
| 225 |
+
positions[:, None] - positions[None, :]
|
| 226 |
+
).abs() < self.local_attention_window
|
| 227 |
+
self._local_attention_mask = torch.zeros(
|
| 228 |
+
tokens.shape[1], tokens.shape[1], device=tokens.device, dtype=tokens.dtype
|
| 229 |
+
).masked_fill(~allowed, torch.finfo(tokens.dtype).min)
|
| 230 |
+
local_update, _ = self.local_attention(
|
| 231 |
+
self.state_norm(tokens), self.state_norm(tokens), self.state_norm(tokens),
|
| 232 |
+
attn_mask=self._local_attention_mask, need_weights=False,
|
| 233 |
+
)
|
| 234 |
+
tokens = tokens + local_update
|
| 235 |
+
|
| 236 |
+
addressed_memory = self.memory_address_norm(memory + memory_slot_identity)
|
| 237 |
+
memory_values = self.memory_value_norm(memory)
|
| 238 |
+
token_memory_update, _ = self.token_memory_attention(
|
| 239 |
+
self.state_norm(tokens), addressed_memory, memory_values, need_weights=False
|
| 240 |
+
)
|
| 241 |
+
tokens = tokens + token_memory_update
|
| 242 |
+
tokens = tokens + self.token_ff(self.token_ff_norm(tokens))
|
| 243 |
+
|
| 244 |
+
memory_token_update, _ = self.memory_token_attention(
|
| 245 |
+
addressed_memory,
|
| 246 |
+
self.state_norm(tokens),
|
| 247 |
+
self.state_norm(tokens),
|
| 248 |
+
need_weights=False,
|
| 249 |
+
)
|
| 250 |
+
memory = memory + memory_token_update
|
| 251 |
+
memory = memory + self.memory_ff(self.memory_ff_norm(memory))
|
| 252 |
+
# This module is a recurrent cell, not a depth-only Transformer block.
|
| 253 |
+
# Persist normalized state so repeated denoise updates cannot accumulate
|
| 254 |
+
# an unbounded residual magnitude across time.
|
| 255 |
+
return self.stored_token_norm(tokens), self.stored_memory_norm(memory)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class LatentDeliberationTransformer(nn.Module):
|
| 259 |
+
"""Small recurrent Transformer that compresses repeated denoise context."""
|
| 260 |
+
|
| 261 |
+
def __init__(
|
| 262 |
+
self,
|
| 263 |
+
*,
|
| 264 |
+
hidden_size: int,
|
| 265 |
+
latent_dim: int = 512,
|
| 266 |
+
memory_slots: int = 16,
|
| 267 |
+
num_layers: int = 2,
|
| 268 |
+
num_heads: int = 8,
|
| 269 |
+
local_attention_window: int = 32,
|
| 270 |
+
dropout: float = 0.0,
|
| 271 |
+
) -> None:
|
| 272 |
+
super().__init__()
|
| 273 |
+
if latent_dim % num_heads:
|
| 274 |
+
raise ValueError("`latent_dim` must be divisible by `num_heads`.")
|
| 275 |
+
if local_attention_window <= 0:
|
| 276 |
+
raise ValueError("`local_attention_window` must be positive.")
|
| 277 |
+
self.hidden_size = hidden_size
|
| 278 |
+
self.latent_dim = latent_dim
|
| 279 |
+
self.memory_slots = memory_slots
|
| 280 |
+
self.heavy_projection = nn.Linear(hidden_size, latent_dim, bias=False)
|
| 281 |
+
self.embedding_projection = nn.Linear(hidden_size, latent_dim, bias=False)
|
| 282 |
+
self.scalar_projection = nn.Linear(11, latent_dim, bias=False)
|
| 283 |
+
self.blocks = nn.ModuleList(
|
| 284 |
+
[
|
| 285 |
+
_TemporalTransformerCell(
|
| 286 |
+
latent_dim, num_heads, dropout, local_attention_window
|
| 287 |
+
)
|
| 288 |
+
for _ in range(num_layers)
|
| 289 |
+
]
|
| 290 |
+
)
|
| 291 |
+
self.output_norm = nn.LayerNorm(latent_dim)
|
| 292 |
+
self.output_projection = nn.Linear(latent_dim, hidden_size, bias=False)
|
| 293 |
+
self.memory_slot_identity = nn.Parameter(torch.empty(memory_slots, latent_dim))
|
| 294 |
+
self.reset_memory_slot_identity()
|
| 295 |
+
|
| 296 |
+
@torch.no_grad()
|
| 297 |
+
def reset_memory_slot_identity(self) -> None:
|
| 298 |
+
"""Restore learned memory addresses after generic initialization."""
|
| 299 |
+
|
| 300 |
+
nn.init.normal_(self.memory_slot_identity, mean=0.0, std=0.02)
|
| 301 |
+
|
| 302 |
+
def project_context(self, token_latents: torch.Tensor) -> torch.Tensor:
|
| 303 |
+
"""Translate latent state into a self-conditioning embedding."""
|
| 304 |
+
|
| 305 |
+
normalized_tokens = self.output_norm(token_latents)
|
| 306 |
+
return self.output_projection(normalized_tokens)
|
| 307 |
+
|
| 308 |
+
def forward(
|
| 309 |
+
self,
|
| 310 |
+
*,
|
| 311 |
+
heavy_hidden: torch.Tensor,
|
| 312 |
+
token_embeddings: torch.Tensor,
|
| 313 |
+
confidence: torch.Tensor,
|
| 314 |
+
entropy: torch.Tensor,
|
| 315 |
+
state: LatentDeliberationState,
|
| 316 |
+
) -> tuple[torch.Tensor, LatentDeliberationState]:
|
| 317 |
+
"""Advance latent memory and produce decoder self-conditioning.
|
| 318 |
+
|
| 319 |
+
Args:
|
| 320 |
+
heavy_hidden: Hidden states from the previous decoder pass.
|
| 321 |
+
token_embeddings: Embeddings of current noisy canvas tokens.
|
| 322 |
+
confidence: Proposal confidence for each canvas position.
|
| 323 |
+
entropy: Proposal entropy for each canvas position.
|
| 324 |
+
state: Persistent latent state from the preceding pass.
|
| 325 |
+
|
| 326 |
+
Returns:
|
| 327 |
+
Self-conditioning embeddings and the next compact latent state.
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
if heavy_hidden.ndim != 3:
|
| 331 |
+
raise ValueError("`heavy_hidden` must have shape [batch, canvas, hidden].")
|
| 332 |
+
if heavy_hidden.shape != token_embeddings.shape:
|
| 333 |
+
raise ValueError("`heavy_hidden` and `token_embeddings` must have the same shape.")
|
| 334 |
+
batch_size, canvas_length, hidden_size = heavy_hidden.shape
|
| 335 |
+
if hidden_size != self.hidden_size:
|
| 336 |
+
raise ValueError("Unexpected hidden size for latent deliberation.")
|
| 337 |
+
expected_state = (batch_size, canvas_length, self.latent_dim)
|
| 338 |
+
if state.token_latents.shape != expected_state:
|
| 339 |
+
raise ValueError("State token latents do not match the current canvas.")
|
| 340 |
+
if state.memory_slots.shape != (batch_size, self.memory_slots, self.latent_dim):
|
| 341 |
+
raise ValueError("State memory slots do not match this module.")
|
| 342 |
+
if state.age.dtype is not torch.int32:
|
| 343 |
+
raise TypeError("Latent deliberation ages must use int32.")
|
| 344 |
+
|
| 345 |
+
scalars = torch.stack(
|
| 346 |
+
(
|
| 347 |
+
confidence.to(dtype=heavy_hidden.dtype),
|
| 348 |
+
entropy.to(dtype=heavy_hidden.dtype).log1p(),
|
| 349 |
+
state.age.to(dtype=heavy_hidden.dtype).clamp_max(32767).log1p(),
|
| 350 |
+
torch.linspace(
|
| 351 |
+
-1.0, 1.0, canvas_length, device=heavy_hidden.device,
|
| 352 |
+
dtype=heavy_hidden.dtype,
|
| 353 |
+
).unsqueeze(0).expand(batch_size, -1),
|
| 354 |
+
state.token_changed.to(dtype=heavy_hidden.dtype),
|
| 355 |
+
state.confidence_delta.to(dtype=heavy_hidden.dtype),
|
| 356 |
+
state.entropy_delta.to(dtype=heavy_hidden.dtype).sign()
|
| 357 |
+
* state.entropy_delta.to(dtype=heavy_hidden.dtype).abs().log1p(),
|
| 358 |
+
state.ponder_steps.to(dtype=heavy_hidden.dtype).log1p()[:, None]
|
| 359 |
+
.expand(-1, canvas_length),
|
| 360 |
+
state.stagnation_steps.to(dtype=heavy_hidden.dtype).log1p()[:, None]
|
| 361 |
+
.expand(-1, canvas_length),
|
| 362 |
+
confidence.to(dtype=heavy_hidden.dtype)
|
| 363 |
+
* torch.exp(-entropy.to(dtype=heavy_hidden.dtype).clamp_min(0.0)),
|
| 364 |
+
state.confidence_delta.to(dtype=heavy_hidden.dtype).clamp_min(0.0)
|
| 365 |
+
+ (-state.entropy_delta.to(dtype=heavy_hidden.dtype)).clamp_min(0.0).log1p(),
|
| 366 |
+
),
|
| 367 |
+
dim=-1,
|
| 368 |
+
)
|
| 369 |
+
observation = (
|
| 370 |
+
self.heavy_projection(heavy_hidden)
|
| 371 |
+
+ self.embedding_projection(token_embeddings)
|
| 372 |
+
+ self.scalar_projection(scalars)
|
| 373 |
+
)
|
| 374 |
+
tokens = state.token_latents
|
| 375 |
+
memory = state.memory_slots
|
| 376 |
+
slot_identity = self.memory_slot_identity.to(device=memory.device, dtype=memory.dtype)
|
| 377 |
+
slot_identity = slot_identity.unsqueeze(0).expand(batch_size, -1, -1)
|
| 378 |
+
for block in self.blocks:
|
| 379 |
+
tokens, memory = block(tokens, observation, memory, slot_identity)
|
| 380 |
+
observation = tokens
|
| 381 |
+
|
| 382 |
+
context = self.project_context(tokens)
|
| 383 |
+
next_state = LatentDeliberationState(
|
| 384 |
+
token_latents=tokens,
|
| 385 |
+
memory_slots=memory,
|
| 386 |
+
confidence=confidence.to(dtype=torch.float32),
|
| 387 |
+
entropy=entropy.to(dtype=torch.float32),
|
| 388 |
+
age=state.age,
|
| 389 |
+
token_changed=state.token_changed,
|
| 390 |
+
confidence_delta=state.confidence_delta,
|
| 391 |
+
entropy_delta=state.entropy_delta,
|
| 392 |
+
ponder_steps=state.ponder_steps,
|
| 393 |
+
stagnation_steps=state.stagnation_steps,
|
| 394 |
+
)
|
| 395 |
+
return context, next_state
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
__all__ = [
|
| 399 |
+
"LatentDeliberationState", "LatentDeliberationTransformer",
|
| 400 |
+
"advance_trajectory_clocks", "should_force_trajectory_jump",
|
| 401 |
+
]
|
modilify_mk1/modeling_modilify_mk1.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026 Modilify
|
| 2 |
+
# SPDX-License-Identifier: LicenseRef-Modilify-Open-Model-1.0
|
| 3 |
+
"""Standard PyTorch multimodal model implementation for Modilify Mk1."""
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, replace
|
| 8 |
+
import math
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch import nn
|
| 13 |
+
from transformers.cache_utils import Cache
|
| 14 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast
|
| 15 |
+
from transformers.utils import ModelOutput
|
| 16 |
+
from transformers.models.diffusion_gemma import (
|
| 17 |
+
DiffusionGemmaDecoderModel,
|
| 18 |
+
DiffusionGemmaEncoderModel,
|
| 19 |
+
DiffusionGemmaPreTrainedModel,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from .configuration_modilify_mk1 import ModilifyMk1Config
|
| 23 |
+
from .generation_modilify_mk1 import (
|
| 24 |
+
ModilifyMk1GenerationConfig,
|
| 25 |
+
ModilifyMk1GenerationMixin,
|
| 26 |
+
)
|
| 27 |
+
from .latent_deliberation import (
|
| 28 |
+
LatentDeliberationState,
|
| 29 |
+
LatentDeliberationTransformer,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class ModilifyMk1DecoderOutput(BaseModelOutputWithPast):
|
| 35 |
+
"""Decoder hidden states and latent-context diagnostics."""
|
| 36 |
+
|
| 37 |
+
token_embeddings: torch.FloatTensor | None = None
|
| 38 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class ModilifyMk1ModelOutput(BaseModelOutputWithPast):
|
| 43 |
+
"""Combined multimodal encoder and diffusion decoder output."""
|
| 44 |
+
|
| 45 |
+
token_embeddings: torch.FloatTensor | None = None
|
| 46 |
+
encoder_last_hidden_state: torch.FloatTensor | None = None
|
| 47 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
@dataclass
|
| 51 |
+
class ModilifyMk1BlockDiffusionOutput(ModelOutput):
|
| 52 |
+
"""Inference output used by the rolling diffusion generator."""
|
| 53 |
+
|
| 54 |
+
logits: torch.FloatTensor | None = None
|
| 55 |
+
heavy_hidden_state: torch.FloatTensor | None = None
|
| 56 |
+
next_latent_state: LatentDeliberationState | None = None
|
| 57 |
+
past_key_values: Cache | None = None
|
| 58 |
+
encoder_last_hidden_state: torch.FloatTensor | None = None
|
| 59 |
+
temporal_context: torch.FloatTensor | None = None
|
| 60 |
+
latent_residual_diagnostics: dict[str, torch.Tensor] | None = None
|
| 61 |
+
proposal: torch.LongTensor | None = None
|
| 62 |
+
proposal_confidence: torch.FloatTensor | None = None
|
| 63 |
+
token_entropy: torch.FloatTensor | None = None
|
| 64 |
+
greedy_proposal: torch.LongTensor | None = None
|
| 65 |
+
greedy_confidence: torch.FloatTensor | None = None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class ModilifyMk1EncoderModel(DiffusionGemmaEncoderModel):
|
| 69 |
+
"""Unmodified Transformers DiffusionGemma multimodal encoder."""
|
| 70 |
+
|
| 71 |
+
config_class = ModilifyMk1Config
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ModilifyMk1DecoderModel(DiffusionGemmaDecoderModel):
|
| 75 |
+
"""DiffusionGemma decoder conditioned by recurrent latent embeddings."""
|
| 76 |
+
|
| 77 |
+
config_class = ModilifyMk1Config
|
| 78 |
+
latent_residual_rms_ratio_cap = 0.5
|
| 79 |
+
|
| 80 |
+
def merge_latent_context(
|
| 81 |
+
self,
|
| 82 |
+
token_embeddings: torch.Tensor,
|
| 83 |
+
latent_context: torch.Tensor | None,
|
| 84 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 85 |
+
"""Apply the native self-conditioning bridge to latent context.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
token_embeddings: Embedded noisy canvas tokens.
|
| 89 |
+
latent_context: Context emitted by the latent Transformer.
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
Merged embeddings and scalar diagnostic tensors.
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
context = (
|
| 96 |
+
torch.zeros_like(token_embeddings)
|
| 97 |
+
if latent_context is None
|
| 98 |
+
else latent_context.to(token_embeddings)
|
| 99 |
+
)
|
| 100 |
+
if context.shape != token_embeddings.shape:
|
| 101 |
+
raise ValueError("Latent context must match the canvas embedding shape.")
|
| 102 |
+
mapper = self.self_conditioning
|
| 103 |
+
normalized = mapper.pre_norm(context)
|
| 104 |
+
mapped = mapper.down_proj(
|
| 105 |
+
mapper.act_fn(mapper.gate_proj(normalized)) * mapper.up_proj(normalized)
|
| 106 |
+
)
|
| 107 |
+
mapped_rms_per_token = mapped.float().square().mean(dim=-1, keepdim=True).sqrt()
|
| 108 |
+
token_rms_per_token = token_embeddings.float().square().mean(dim=-1, keepdim=True).sqrt()
|
| 109 |
+
cap = self.latent_residual_rms_ratio_cap * token_rms_per_token
|
| 110 |
+
scale = cap / torch.sqrt(mapped_rms_per_token.square() + cap.square() + 1.0e-12)
|
| 111 |
+
mapped = mapped * scale.to(mapped)
|
| 112 |
+
combined = mapper.post_norm(token_embeddings + mapped)
|
| 113 |
+
token_rms = token_embeddings.detach().float().square().mean().sqrt()
|
| 114 |
+
mapped_rms = mapped.detach().float().square().mean().sqrt()
|
| 115 |
+
diagnostics = {
|
| 116 |
+
"token_embedding_rms": token_rms,
|
| 117 |
+
"latent_context_rms": context.detach().float().square().mean().sqrt(),
|
| 118 |
+
"mapped_context_rms": mapped_rms,
|
| 119 |
+
"latent_to_embedding_rms_ratio": mapped_rms / token_rms.clamp_min(1.0e-12),
|
| 120 |
+
}
|
| 121 |
+
return combined, diagnostics
|
| 122 |
+
|
| 123 |
+
def forward(
|
| 124 |
+
self,
|
| 125 |
+
decoder_input_ids: torch.LongTensor,
|
| 126 |
+
past_key_values: Cache | None = None,
|
| 127 |
+
temporal_context_embeddings: torch.FloatTensor | None = None,
|
| 128 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 129 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 130 |
+
**kwargs: Any,
|
| 131 |
+
) -> ModilifyMk1DecoderOutput:
|
| 132 |
+
"""Decode one noisy canvas using only Transformers and PyTorch operations."""
|
| 133 |
+
|
| 134 |
+
token_embeddings = self.embed_tokens(decoder_input_ids)
|
| 135 |
+
inputs_embeds, diagnostics = self.merge_latent_context(
|
| 136 |
+
token_embeddings,
|
| 137 |
+
temporal_context_embeddings,
|
| 138 |
+
)
|
| 139 |
+
if decoder_position_ids is None:
|
| 140 |
+
prefix = past_key_values.get_seq_length(0) if past_key_values is not None else 0
|
| 141 |
+
decoder_position_ids = torch.arange(
|
| 142 |
+
prefix,
|
| 143 |
+
prefix + inputs_embeds.shape[1],
|
| 144 |
+
device=inputs_embeds.device,
|
| 145 |
+
).unsqueeze(0)
|
| 146 |
+
if not isinstance(mask_mapping := decoder_attention_mask, dict):
|
| 147 |
+
mask_mapping = self.create_diffusion_decoder_attention_mask(
|
| 148 |
+
config=self.text_config,
|
| 149 |
+
inputs_embeds=inputs_embeds,
|
| 150 |
+
past_key_values=past_key_values,
|
| 151 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 152 |
+
)
|
| 153 |
+
position_embeddings = {
|
| 154 |
+
layer_type: self.rotary_emb(inputs_embeds, decoder_position_ids, layer_type)
|
| 155 |
+
for layer_type in self.unique_layer_types
|
| 156 |
+
}
|
| 157 |
+
hidden_states = inputs_embeds
|
| 158 |
+
for index, layer in enumerate(self.layers[: self.text_config.num_hidden_layers]):
|
| 159 |
+
layer_type = self.text_config.layer_types[index]
|
| 160 |
+
hidden_states = layer(
|
| 161 |
+
hidden_states,
|
| 162 |
+
position_embeddings=position_embeddings[layer_type],
|
| 163 |
+
attention_mask=mask_mapping[layer_type],
|
| 164 |
+
position_ids=decoder_position_ids,
|
| 165 |
+
past_key_values=past_key_values,
|
| 166 |
+
**kwargs,
|
| 167 |
+
)
|
| 168 |
+
return ModilifyMk1DecoderOutput(
|
| 169 |
+
last_hidden_state=self.norm(hidden_states),
|
| 170 |
+
past_key_values=past_key_values,
|
| 171 |
+
token_embeddings=token_embeddings,
|
| 172 |
+
latent_residual_diagnostics=diagnostics,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class ModilifyMk1Model(DiffusionGemmaPreTrainedModel):
|
| 177 |
+
"""Multimodal encoder plus latent-conditioned block diffusion decoder."""
|
| 178 |
+
|
| 179 |
+
config_class = ModilifyMk1Config
|
| 180 |
+
_tied_weights_keys = {
|
| 181 |
+
"encoder.language_model.norm.weight": "decoder.norm.weight",
|
| 182 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*weight": r"decoder.layers\.(?:[^.]+\.)*weight",
|
| 183 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*scale": r"decoder.layers\.(?:[^.]+\.)*scale",
|
| 184 |
+
(
|
| 185 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*per_expert_scale"
|
| 186 |
+
): r"decoder.layers\.(?:[^.]+\.)*per_expert_scale",
|
| 187 |
+
(
|
| 188 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*gate_up_proj"
|
| 189 |
+
): r"decoder.layers\.(?:[^.]+\.)*gate_up_proj",
|
| 190 |
+
(
|
| 191 |
+
r"encoder.language_model.layers\.(?:[^.]+\.)*down_proj"
|
| 192 |
+
): r"decoder.layers\.(?:[^.]+\.)*down_proj",
|
| 193 |
+
"encoder.language_model.embed_tokens.weight": "decoder.embed_tokens.weight",
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
def __init__(self, config: ModilifyMk1Config) -> None:
|
| 197 |
+
super().__init__(config)
|
| 198 |
+
self.encoder = ModilifyMk1EncoderModel(config)
|
| 199 |
+
self.decoder = ModilifyMk1DecoderModel(config)
|
| 200 |
+
self.post_init()
|
| 201 |
+
|
| 202 |
+
def get_encoder(self) -> ModilifyMk1EncoderModel:
|
| 203 |
+
"""Return the standard multimodal encoder."""
|
| 204 |
+
|
| 205 |
+
return self.encoder
|
| 206 |
+
|
| 207 |
+
def get_decoder(self) -> ModilifyMk1DecoderModel:
|
| 208 |
+
"""Return the diffusion decoder."""
|
| 209 |
+
|
| 210 |
+
return self.decoder
|
| 211 |
+
|
| 212 |
+
def get_input_embeddings(self) -> nn.Module:
|
| 213 |
+
"""Return the shared text embedding module."""
|
| 214 |
+
|
| 215 |
+
return self.encoder.get_input_embeddings()
|
| 216 |
+
|
| 217 |
+
def set_input_embeddings(self, value: nn.Module) -> None:
|
| 218 |
+
"""Set the shared text embedding module."""
|
| 219 |
+
|
| 220 |
+
self.encoder.set_input_embeddings(value)
|
| 221 |
+
self.decoder.embed_tokens = value
|
| 222 |
+
|
| 223 |
+
def forward(
|
| 224 |
+
self,
|
| 225 |
+
*,
|
| 226 |
+
input_ids: torch.LongTensor | None = None,
|
| 227 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 228 |
+
past_key_values: Cache | None = None,
|
| 229 |
+
position_ids: torch.LongTensor | None = None,
|
| 230 |
+
decoder_input_ids: torch.LongTensor,
|
| 231 |
+
temporal_context_embeddings: torch.FloatTensor | None = None,
|
| 232 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 233 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 234 |
+
**kwargs: Any,
|
| 235 |
+
) -> ModilifyMk1ModelOutput:
|
| 236 |
+
"""Encode multimodal context and decode one canvas."""
|
| 237 |
+
|
| 238 |
+
encoder_hidden_state = None
|
| 239 |
+
encoder_keys = ("pixel_values", "mm_token_type_ids", "image_position_ids", "inputs_embeds")
|
| 240 |
+
encoder_kwargs = {key: kwargs.pop(key) for key in encoder_keys if key in kwargs}
|
| 241 |
+
if input_ids is not None:
|
| 242 |
+
encoded = self.encoder(
|
| 243 |
+
input_ids=input_ids,
|
| 244 |
+
attention_mask=attention_mask,
|
| 245 |
+
past_key_values=past_key_values,
|
| 246 |
+
position_ids=position_ids,
|
| 247 |
+
**encoder_kwargs,
|
| 248 |
+
)
|
| 249 |
+
past_key_values = encoded.past_key_values
|
| 250 |
+
encoder_hidden_state = encoded.last_hidden_state
|
| 251 |
+
elif past_key_values is None:
|
| 252 |
+
raise ValueError("Either `input_ids` or `past_key_values` is required.")
|
| 253 |
+
decoded = self.decoder(
|
| 254 |
+
decoder_input_ids=decoder_input_ids,
|
| 255 |
+
past_key_values=past_key_values,
|
| 256 |
+
temporal_context_embeddings=temporal_context_embeddings,
|
| 257 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 258 |
+
decoder_position_ids=decoder_position_ids,
|
| 259 |
+
**kwargs,
|
| 260 |
+
)
|
| 261 |
+
return ModilifyMk1ModelOutput(
|
| 262 |
+
last_hidden_state=decoded.last_hidden_state,
|
| 263 |
+
past_key_values=past_key_values,
|
| 264 |
+
token_embeddings=decoded.token_embeddings,
|
| 265 |
+
encoder_last_hidden_state=encoder_hidden_state,
|
| 266 |
+
latent_residual_diagnostics=decoded.latent_residual_diagnostics,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class ModilifyMk1ForBlockDiffusion(
|
| 271 |
+
DiffusionGemmaPreTrainedModel,
|
| 272 |
+
ModilifyMk1GenerationMixin,
|
| 273 |
+
):
|
| 274 |
+
"""Inference-only multimodal Modilify Mk1 model."""
|
| 275 |
+
|
| 276 |
+
config_class = ModilifyMk1Config
|
| 277 |
+
_tied_weights_keys = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
|
| 278 |
+
generation_config_class = ModilifyMk1GenerationConfig
|
| 279 |
+
|
| 280 |
+
@torch.no_grad()
|
| 281 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 282 |
+
super()._init_weights(module)
|
| 283 |
+
if isinstance(module, LatentDeliberationTransformer):
|
| 284 |
+
module.reset_memory_slot_identity()
|
| 285 |
+
|
| 286 |
+
def __init__(self, config: ModilifyMk1Config) -> None:
|
| 287 |
+
super().__init__(config)
|
| 288 |
+
self.model = ModilifyMk1Model(config)
|
| 289 |
+
self.latent_deliberation = LatentDeliberationTransformer(
|
| 290 |
+
hidden_size=config.text_config.hidden_size,
|
| 291 |
+
latent_dim=config.latent_dim,
|
| 292 |
+
memory_slots=config.latent_memory_slots,
|
| 293 |
+
num_layers=config.latent_num_layers,
|
| 294 |
+
num_heads=config.latent_num_heads,
|
| 295 |
+
local_attention_window=config.latent_local_attention_window,
|
| 296 |
+
dropout=config.latent_dropout,
|
| 297 |
+
)
|
| 298 |
+
self.lm_head = nn.Linear(
|
| 299 |
+
config.text_config.hidden_size,
|
| 300 |
+
config.text_config.vocab_size,
|
| 301 |
+
bias=False,
|
| 302 |
+
)
|
| 303 |
+
self.final_logit_softcapping = config.text_config.final_logit_softcapping
|
| 304 |
+
self.post_init()
|
| 305 |
+
|
| 306 |
+
def _prepare_latent_context(
|
| 307 |
+
self,
|
| 308 |
+
decoder_input_ids: torch.LongTensor,
|
| 309 |
+
*,
|
| 310 |
+
history_hidden_state: torch.Tensor | None,
|
| 311 |
+
confidence: torch.Tensor | None,
|
| 312 |
+
entropy: torch.Tensor | None,
|
| 313 |
+
age: torch.Tensor | None,
|
| 314 |
+
latent_state: LatentDeliberationState | None,
|
| 315 |
+
) -> tuple[torch.Tensor, LatentDeliberationState]:
|
| 316 |
+
"""Advance recurrent latent state for the current canvas."""
|
| 317 |
+
|
| 318 |
+
batch_size, canvas_length = decoder_input_ids.shape
|
| 319 |
+
dtype = self.model.decoder.embed_tokens.weight.dtype
|
| 320 |
+
if latent_state is None:
|
| 321 |
+
latent_state = LatentDeliberationState.empty(
|
| 322 |
+
batch_size=batch_size,
|
| 323 |
+
canvas_length=canvas_length,
|
| 324 |
+
latent_dim=self.config.latent_dim,
|
| 325 |
+
memory_slots=self.config.latent_memory_slots,
|
| 326 |
+
device=decoder_input_ids.device,
|
| 327 |
+
dtype=dtype,
|
| 328 |
+
)
|
| 329 |
+
confidence = (
|
| 330 |
+
latent_state.confidence
|
| 331 |
+
if confidence is None
|
| 332 |
+
else confidence.squeeze(-1).float()
|
| 333 |
+
)
|
| 334 |
+
entropy = latent_state.entropy if entropy is None else entropy.squeeze(-1).float()
|
| 335 |
+
if age is not None:
|
| 336 |
+
latent_state = replace(
|
| 337 |
+
latent_state,
|
| 338 |
+
age=age.to(device=decoder_input_ids.device, dtype=torch.int32),
|
| 339 |
+
)
|
| 340 |
+
token_embeddings = self.model.decoder.embed_tokens(decoder_input_ids)
|
| 341 |
+
history = (
|
| 342 |
+
torch.zeros_like(token_embeddings)
|
| 343 |
+
if history_hidden_state is None
|
| 344 |
+
else history_hidden_state
|
| 345 |
+
)
|
| 346 |
+
return self.latent_deliberation(
|
| 347 |
+
heavy_hidden=history,
|
| 348 |
+
token_embeddings=token_embeddings,
|
| 349 |
+
confidence=confidence,
|
| 350 |
+
entropy=entropy,
|
| 351 |
+
state=latent_state,
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
def _proposal_statistics(
|
| 355 |
+
self,
|
| 356 |
+
logits: torch.Tensor,
|
| 357 |
+
*,
|
| 358 |
+
denoise_temperature: float | None = None,
|
| 359 |
+
) -> tuple[
|
| 360 |
+
torch.LongTensor,
|
| 361 |
+
torch.Tensor,
|
| 362 |
+
torch.Tensor,
|
| 363 |
+
torch.LongTensor,
|
| 364 |
+
torch.Tensor,
|
| 365 |
+
]:
|
| 366 |
+
"""Compute exact proposal statistics with standard PyTorch operations."""
|
| 367 |
+
|
| 368 |
+
temperature = (
|
| 369 |
+
self.config.denoise_temperature
|
| 370 |
+
if denoise_temperature is None
|
| 371 |
+
else float(denoise_temperature)
|
| 372 |
+
)
|
| 373 |
+
if not math.isfinite(temperature) or temperature <= 0.0:
|
| 374 |
+
raise ValueError("`denoise_temperature` must be positive.")
|
| 375 |
+
scores = logits.float() / temperature
|
| 376 |
+
probabilities = torch.softmax(scores, dim=-1)
|
| 377 |
+
flat = probabilities.reshape(-1, probabilities.shape[-1])
|
| 378 |
+
proposal = torch.multinomial(flat, num_samples=1).view(logits.shape[:-1])
|
| 379 |
+
proposal_confidence = probabilities.gather(
|
| 380 |
+
-1,
|
| 381 |
+
proposal.unsqueeze(-1),
|
| 382 |
+
).squeeze(-1)
|
| 383 |
+
greedy_proposal = probabilities.argmax(dim=-1)
|
| 384 |
+
greedy_confidence = probabilities.gather(
|
| 385 |
+
-1,
|
| 386 |
+
greedy_proposal.unsqueeze(-1),
|
| 387 |
+
).squeeze(-1)
|
| 388 |
+
token_entropy = -(
|
| 389 |
+
probabilities * probabilities.clamp_min(1.0e-30).log()
|
| 390 |
+
).sum(dim=-1)
|
| 391 |
+
return (
|
| 392 |
+
proposal,
|
| 393 |
+
proposal_confidence,
|
| 394 |
+
token_entropy,
|
| 395 |
+
greedy_proposal,
|
| 396 |
+
greedy_confidence,
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def forward(
|
| 400 |
+
self,
|
| 401 |
+
*,
|
| 402 |
+
input_ids: torch.LongTensor | None = None,
|
| 403 |
+
attention_mask: torch.Tensor | dict | None = None,
|
| 404 |
+
past_key_values: Cache | None = None,
|
| 405 |
+
position_ids: torch.LongTensor | None = None,
|
| 406 |
+
decoder_input_ids: torch.LongTensor,
|
| 407 |
+
previous_confidence: torch.FloatTensor | None = None,
|
| 408 |
+
previous_entropy: torch.FloatTensor | None = None,
|
| 409 |
+
token_age: torch.Tensor | None = None,
|
| 410 |
+
latent_state: LatentDeliberationState | None = None,
|
| 411 |
+
history_hidden_state: torch.FloatTensor | None = None,
|
| 412 |
+
decoder_attention_mask: torch.Tensor | dict | None = None,
|
| 413 |
+
decoder_position_ids: torch.LongTensor | None = None,
|
| 414 |
+
return_proposal_statistics: bool = False,
|
| 415 |
+
denoise_temperature: float | None = None,
|
| 416 |
+
**kwargs: Any,
|
| 417 |
+
) -> ModilifyMk1BlockDiffusionOutput:
|
| 418 |
+
"""Run one inference step over a noisy diffusion canvas."""
|
| 419 |
+
|
| 420 |
+
latent_context, next_state = self._prepare_latent_context(
|
| 421 |
+
decoder_input_ids,
|
| 422 |
+
history_hidden_state=history_hidden_state,
|
| 423 |
+
confidence=previous_confidence,
|
| 424 |
+
entropy=previous_entropy,
|
| 425 |
+
age=token_age,
|
| 426 |
+
latent_state=latent_state,
|
| 427 |
+
)
|
| 428 |
+
outputs = self.model(
|
| 429 |
+
input_ids=input_ids,
|
| 430 |
+
attention_mask=attention_mask,
|
| 431 |
+
past_key_values=past_key_values,
|
| 432 |
+
position_ids=position_ids,
|
| 433 |
+
decoder_input_ids=decoder_input_ids,
|
| 434 |
+
temporal_context_embeddings=latent_context,
|
| 435 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 436 |
+
decoder_position_ids=decoder_position_ids,
|
| 437 |
+
**kwargs,
|
| 438 |
+
)
|
| 439 |
+
logits = self.lm_head(outputs.last_hidden_state)
|
| 440 |
+
logits = (
|
| 441 |
+
torch.tanh(logits / self.final_logit_softcapping)
|
| 442 |
+
* self.final_logit_softcapping
|
| 443 |
+
)
|
| 444 |
+
statistics = (None, None, None, None, None)
|
| 445 |
+
if return_proposal_statistics:
|
| 446 |
+
statistics = self._proposal_statistics(
|
| 447 |
+
logits,
|
| 448 |
+
denoise_temperature=denoise_temperature,
|
| 449 |
+
)
|
| 450 |
+
return ModilifyMk1BlockDiffusionOutput(
|
| 451 |
+
logits=None if return_proposal_statistics else logits,
|
| 452 |
+
heavy_hidden_state=outputs.last_hidden_state,
|
| 453 |
+
next_latent_state=next_state,
|
| 454 |
+
past_key_values=outputs.past_key_values,
|
| 455 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 456 |
+
temporal_context=latent_context,
|
| 457 |
+
latent_residual_diagnostics=outputs.latent_residual_diagnostics,
|
| 458 |
+
proposal=statistics[0],
|
| 459 |
+
proposal_confidence=statistics[1],
|
| 460 |
+
token_entropy=statistics[2],
|
| 461 |
+
greedy_proposal=statistics[3],
|
| 462 |
+
greedy_confidence=statistics[4],
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
__all__ = [
|
| 467 |
+
"ModilifyMk1BlockDiffusionOutput",
|
| 468 |
+
"ModilifyMk1Config",
|
| 469 |
+
"ModilifyMk1DecoderModel",
|
| 470 |
+
"ModilifyMk1EncoderModel",
|
| 471 |
+
"ModilifyMk1ForBlockDiffusion",
|
| 472 |
+
"ModilifyMk1Model",
|
| 473 |
+
]
|
processor_config.json
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"audio_ms_per_token": 40,
|
| 3 |
+
"audio_seq_length": 750,
|
| 4 |
+
"feature_extractor": {
|
| 5 |
+
"dither": 0.0,
|
| 6 |
+
"feature_extractor_type": "Gemma4AudioFeatureExtractor",
|
| 7 |
+
"feature_size": 128,
|
| 8 |
+
"fft_length": 512,
|
| 9 |
+
"fft_overdrive": false,
|
| 10 |
+
"frame_length": 320,
|
| 11 |
+
"hop_length": 160,
|
| 12 |
+
"input_scale_factor": 1.0,
|
| 13 |
+
"max_frequency": 8000.0,
|
| 14 |
+
"mel_floor": 0.001,
|
| 15 |
+
"min_frequency": 0.0,
|
| 16 |
+
"padding_side": "right",
|
| 17 |
+
"padding_value": 0.0,
|
| 18 |
+
"per_bin_mean": null,
|
| 19 |
+
"per_bin_stddev": null,
|
| 20 |
+
"preemphasis": 0.0,
|
| 21 |
+
"preemphasis_htk_flavor": true,
|
| 22 |
+
"return_attention_mask": true,
|
| 23 |
+
"sampling_rate": 16000
|
| 24 |
+
},
|
| 25 |
+
"image_processor": {
|
| 26 |
+
"do_convert_rgb": true,
|
| 27 |
+
"do_normalize": false,
|
| 28 |
+
"do_rescale": true,
|
| 29 |
+
"do_resize": true,
|
| 30 |
+
"image_mean": [
|
| 31 |
+
0.0,
|
| 32 |
+
0.0,
|
| 33 |
+
0.0
|
| 34 |
+
],
|
| 35 |
+
"image_processor_type": "Gemma4ImageProcessor",
|
| 36 |
+
"image_seq_length": 280,
|
| 37 |
+
"image_std": [
|
| 38 |
+
1.0,
|
| 39 |
+
1.0,
|
| 40 |
+
1.0
|
| 41 |
+
],
|
| 42 |
+
"max_soft_tokens": 280,
|
| 43 |
+
"patch_size": 16,
|
| 44 |
+
"pooling_kernel_size": 3,
|
| 45 |
+
"resample": 3,
|
| 46 |
+
"rescale_factor": 0.00392156862745098
|
| 47 |
+
},
|
| 48 |
+
"image_seq_length": 280,
|
| 49 |
+
"processor_class": "Gemma4Processor",
|
| 50 |
+
"video_processor": {
|
| 51 |
+
"do_convert_rgb": true,
|
| 52 |
+
"do_normalize": true,
|
| 53 |
+
"do_rescale": true,
|
| 54 |
+
"do_resize": true,
|
| 55 |
+
"do_sample_frames": true,
|
| 56 |
+
"image_mean": [
|
| 57 |
+
0.0,
|
| 58 |
+
0.0,
|
| 59 |
+
0.0
|
| 60 |
+
],
|
| 61 |
+
"image_std": [
|
| 62 |
+
1.0,
|
| 63 |
+
1.0,
|
| 64 |
+
1.0
|
| 65 |
+
],
|
| 66 |
+
"max_soft_tokens": 70,
|
| 67 |
+
"num_frames": 32,
|
| 68 |
+
"patch_size": 16,
|
| 69 |
+
"pooling_kernel_size": 3,
|
| 70 |
+
"resample": 3,
|
| 71 |
+
"rescale_factor": 0.00392156862745098,
|
| 72 |
+
"return_metadata": false,
|
| 73 |
+
"video_processor_type": "Gemma4VideoProcessor"
|
| 74 |
+
}
|
| 75 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc8d3a0ce36466ccc1278bf987df5f71db1719b9ca6b4118264f45cb627bfe0f
|
| 3 |
+
size 32169626
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"audio_token": "<|audio|>",
|
| 3 |
+
"backend": "tokenizers",
|
| 4 |
+
"boa_token": "<|audio>",
|
| 5 |
+
"boi_token": "<|image>",
|
| 6 |
+
"bos_token": "<bos>",
|
| 7 |
+
"eoa_token": "<audio|>",
|
| 8 |
+
"eoc_token": "<channel|>",
|
| 9 |
+
"eoi_token": "<image|>",
|
| 10 |
+
"eos_token": "<eos>",
|
| 11 |
+
"eot_token": "<turn|>",
|
| 12 |
+
"escape_token": "<|\"|>",
|
| 13 |
+
"etc_token": "<tool_call|>",
|
| 14 |
+
"etd_token": "<tool|>",
|
| 15 |
+
"etr_token": "<tool_response|>",
|
| 16 |
+
"extra_special_tokens": [
|
| 17 |
+
"<|video|>"
|
| 18 |
+
],
|
| 19 |
+
"image_token": "<|image|>",
|
| 20 |
+
"is_local": true,
|
| 21 |
+
"local_files_only": false,
|
| 22 |
+
"mask_token": "<mask>",
|
| 23 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 24 |
+
"model_specific_special_tokens": {
|
| 25 |
+
"audio_token": "<|audio|>",
|
| 26 |
+
"boa_token": "<|audio>",
|
| 27 |
+
"boi_token": "<|image>",
|
| 28 |
+
"eoa_token": "<audio|>",
|
| 29 |
+
"eoc_token": "<channel|>",
|
| 30 |
+
"eoi_token": "<image|>",
|
| 31 |
+
"eot_token": "<turn|>",
|
| 32 |
+
"escape_token": "<|\"|>",
|
| 33 |
+
"etc_token": "<tool_call|>",
|
| 34 |
+
"etd_token": "<tool|>",
|
| 35 |
+
"etr_token": "<tool_response|>",
|
| 36 |
+
"image_token": "<|image|>",
|
| 37 |
+
"soc_token": "<|channel>",
|
| 38 |
+
"sot_token": "<|turn>",
|
| 39 |
+
"stc_token": "<|tool_call>",
|
| 40 |
+
"std_token": "<|tool>",
|
| 41 |
+
"str_token": "<|tool_response>",
|
| 42 |
+
"think_token": "<|think|>"
|
| 43 |
+
},
|
| 44 |
+
"pad_token": "<pad>",
|
| 45 |
+
"padding_side": "left",
|
| 46 |
+
"processor_class": "Gemma4Processor",
|
| 47 |
+
"response_schema": {
|
| 48 |
+
"properties": {
|
| 49 |
+
"content": {
|
| 50 |
+
"type": "string"
|
| 51 |
+
},
|
| 52 |
+
"role": {
|
| 53 |
+
"const": "assistant"
|
| 54 |
+
},
|
| 55 |
+
"thinking": {
|
| 56 |
+
"type": "string"
|
| 57 |
+
},
|
| 58 |
+
"tool_calls": {
|
| 59 |
+
"items": {
|
| 60 |
+
"properties": {
|
| 61 |
+
"function": {
|
| 62 |
+
"properties": {
|
| 63 |
+
"arguments": {
|
| 64 |
+
"additionalProperties": {},
|
| 65 |
+
"type": "object",
|
| 66 |
+
"x-parser": "gemma4-tool-call"
|
| 67 |
+
},
|
| 68 |
+
"name": {
|
| 69 |
+
"type": "string"
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
"type": "object",
|
| 73 |
+
"x-regex": "call\\:(?P<name>\\w+)(?P<arguments>\\{.*\\})"
|
| 74 |
+
},
|
| 75 |
+
"type": {
|
| 76 |
+
"const": "function"
|
| 77 |
+
}
|
| 78 |
+
},
|
| 79 |
+
"type": "object"
|
| 80 |
+
},
|
| 81 |
+
"type": "array",
|
| 82 |
+
"x-regex-iterator": "<\\|tool_call>(.*?)<tool_call\\|>"
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
"type": "object",
|
| 86 |
+
"x-regex": "(\\<\\|channel\\>thought\\n(?P<thinking>.*?)\\<channel\\|\\>)?(?P<tool_calls>\\<\\|tool_call\\>.*\\<tool_call\\|\\>)?(?P<content>(?:(?!\\<turn\\|\\>)(?!\\<\\|tool_response\\>).)+)?(?:\\<turn\\|\\>|\\<\\|tool_response\\>)?"
|
| 87 |
+
},
|
| 88 |
+
"soc_token": "<|channel>",
|
| 89 |
+
"sot_token": "<|turn>",
|
| 90 |
+
"stc_token": "<|tool_call>",
|
| 91 |
+
"std_token": "<|tool>",
|
| 92 |
+
"str_token": "<|tool_response>",
|
| 93 |
+
"think_token": "<|think|>",
|
| 94 |
+
"tokenizer_class": "GemmaTokenizer",
|
| 95 |
+
"unk_token": "<unk>"
|
| 96 |
+
}
|