Release merged diffusion checkpoint and bilingual model card
Browse filesFiles changed (28)
- .gitattributes+1
- LICENSEAdded+202
- NOTICEAdded+14
- README.mdAdded+44
- block_diffusion.pyAdded+278
- chat_template.jinjaAdded+137
- config.jsonAdded+169
- generation_config.jsonAdded+7
- generation_limits.pyAdded+2
- model-00001-of-00013.safetensorsAdded+3
- model-00002-of-00013.safetensorsAdded+3
- model-00003-of-00013.safetensorsAdded+3
- model-00004-of-00013.safetensorsAdded+3
- model-00005-of-00013.safetensorsAdded+3
- model-00006-of-00013.safetensorsAdded+3
- model-00007-of-00013.safetensorsAdded+3
- model-00008-of-00013.safetensorsAdded+3
- model-00009-of-00013.safetensorsAdded+3
- model-00010-of-00013.safetensorsAdded+3
- model-00011-of-00013.safetensorsAdded+3
- model-00012-of-00013.safetensorsAdded+3
- model-00013-of-00013.safetensorsAdded+3
- model.safetensors.index.jsonAdded
- processor_config.jsonAdded+25
- requirements.txtAdded+7
- run_diffusion.pyAdded+69
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded+85
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.1234567891011121314Diffusion-Inkling-2-mini
Based on Inkling 2 Mini, made available by Thinking Machines Lab, Inc.Upstream source: https://huggingface.co/thinkingmachines/Inkling-2-MiniUpstream revision: fcd43a4241eb71e9f56f5f4d4bb125438cc613d9Upstream license: Apache License, Version 2.0
Modified by the Diffusion-Inkling-2-mini project: trained and merged thequery-projection LoRA, added future-convolution weights and maskedblock-diffusion decoding, and exported full native-format Safetensors.Tokenizer and processor assets originate from the upstream model.
Research reference: DiCALM, https://arxiv.org/abs/2611.33919.Nothing in this notice implies endorsement by Thinking Machines Lab.1234567891011121314151617181920212223242526272829303132333435363738394041424344---license: apache-2.0base_model: thinkingmachines/Inkling-2-Minibase_model_relation: finetunepipeline_tag: text-generationlanguage:- en- jatags:- block-diffusion- masked-denoising- safetensors---
# Diffusion-Inkling-2-mini
**▮▮▮ → text.** A merged block-diffusion checkpoint for English and Japanese. **▮▮▮ → 文章。** 英語・日本語に対応したブロック拡散モデル。
## English
An independent research adaptation of Thinking Machines Lab’s **Inkling 2 Mini**. The query-projection LoRA is merged into the full checkpoint, alongside the learned forward-looking convolution weights. The included runner generates text by filling masks within each block.
**Format:** BF16 Safetensors (with some FP32 tensors), tokenizer included. Use a CUDA GPU with room for about 52 GB of weights plus runtime buffers. The runner defaults to 128-token blocks and accepts sizes from 1 to 512. Larger blocks and lower confidence thresholds can degrade output quality.
## 日本語
Thinking Machines Lab の **Inkling 2 Mini** をベースにした独立の研究モデルです。クエリ射影のLoRAを本体の重みに統合し、ブロック内の未来位置を参照する畳み込みを追加しました。同梱ランナーは、ブロック内のマスクを段階的に埋めて文章を生成します。
**形式:** BF16主体(一部FP32)のSafetensors。トークナイザー同梱。重み約52 GBと実行用バッファが収まるCUDA GPUが必要です。既定のブロック幅は128、指定範囲は1〜512です。ブロックを大きくしたり、しきい値を下げたりすると、回答品質が落ちる場合があります。
## Quick start / 実行
```bashhf download summerAIO/Diffusion-Inkling-2-mini --local-dir diffusion-inklingpip install -r diffusion-inkling/requirements.txtpython diffusion-inkling/run_diffusion.py "空はなぜ青く見えるの?"```
## License / ライセンス
Apache 2.0: [LICENSE](./blob/main/LICENSE) · [NOTICE](./blob/main/NOTICE) Base / ベース: [Thinking Machines Lab — Inkling 2 Mini](https://huggingface.co/thinkingmachines/Inkling-2-Mini) · [Model Acceptable Use Policy](https://thinkingmachines.ai/model-acceptable-use-policy/) Method reference / 手法の参考: [DiCALM](https://arxiv.org/abs/2611.33919)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278import mathfrom copy import copyfrom contextvars import ContextVar
import torchfrom torch import nnfrom torch.nn import functional as F
from generation_limits import MAX_BLOCK_SIZE
BLOCK_SIZE = 128ACTIVE = ContextVar('diffusion_block_start', default=None)
def masks(length, start, subblock, window, device, dtype): return attention_masks(length, start, subblock, window, device, dtype)
def attention_masks(length, start, subblock, window, device, dtype, query_start=0, sliding_start=0): q = torch.arange(query_start, length, device=device)[:, None] k = torch.arange(length, device=device)[None, :] allow = (k <= q) | ((q >= start) & ((q-start)//subblock == (k-start)//subblock)) def additive(visible): return torch.zeros_like(visible, dtype=dtype)[None, None].masked_fill(~visible, float('-inf')) return {'full_attention': additive(allow), 'sliding_attention': additive((allow & ((q-k).abs() < window))[:, sliding_start:]), 'linear_attention': None}
def future_residual(x, taps, start): positions = torch.arange(x.shape[1], device=x.device) result = torch.zeros_like(x, dtype=torch.float32) for offset, tap in enumerate(taps, 1): valid = (positions >= start) & (positions + offset < x.shape[1]) index = (positions + offset).clamp(max=x.shape[1]-1) result = result + x[:, index].float() * tap * valid[None, :, None] return result
def install_future_convolutions(model): from transformers.models.inkling2_loop.modeling_inkling2_loop import ( Inkling2LoopDynamicShortConvolution, Inkling2LoopShortConvolution, )
for module in list(model.modules()): if isinstance(module, Inkling2LoopShortConvolution): weight = module.conv1d.weight width, device = weight.shape[0], weight.device scale = math.sqrt(module.conv_kernel_size + 1) elif isinstance(module, Inkling2LoopDynamicShortConvolution): width, device = module.static_weight.shape[1], module.static_weight.device scale = math.sqrt(2 * module.conv_kernel_size + 1) else: continue module.register_parameter('future_taps', nn.Parameter(torch.zeros(2, width, device=device)))
def extend(mod, args, out, scale=scale): start = ACTIVE.get() if start is None: return out return out + (future_residual(args[0], mod.future_taps, start) / scale).to(out.dtype)
module.register_forward_hook(extend)
def logits(model, ids, positions, start=None, subblock=BLOCK_SIZE): attention = None if start is not None: config = model.config.text_config attention = masks(ids.shape[1], start, subblock, config.sliding_window_size, ids.device, model.get_input_embeddings().weight.dtype) context = ACTIVE.set(start) try: return model(input_ids=ids, attention_mask=attention, use_cache=False, logits_to_keep=positions).logits[0] finally: ACTIVE.reset(context)
def guarded_candidates(scores, ids, positions, mask_id, stop_ids, suppressed): scores[:, mask_id] = -torch.inf if suppressed: scores[:, suppressed] = -torch.inf if stop_ids: scores[1:, list(stop_ids)] = -torch.inf # Prevent a third identical token after an already-established run. previous = ids[0, (positions - 1).clamp_min(0)] earlier = ids[0, (positions - 2).clamp_min(0)] repeated = (positions >= 2) & (previous == earlier) & (previous != mask_id) if stop_ids: repeated &= ~torch.isin(previous, positions.new_tensor(list(stop_ids))) scores[repeated.nonzero().flatten(), previous[repeated]] = -torch.inf confidence, tokens = scores.softmax(-1).max(-1) eligible = positions <= positions[0] + 11 # Adjacent identical guesses deep inside one masked run are often the same # marginal repeated, not independent evidence for multiple occurrences. eligible[1:] &= ((positions[1:] != positions[:-1] + 1) | (tokens[1:] != tokens[:-1])) return confidence.masked_fill(~eligible, -torch.inf), tokens
@torch.no_grad()def generate(model, ids, mask_id, stop_ids, max_new_tokens=128, threshold=0.9, stats=None, prefix_cache=False, block_steps=0, confidence_order=False, guarded=False, suppressed=(), scorer=None, block_size=BLOCK_SIZE): tokens = [] for _, _, _, _, tokens, _ in denoise_steps( model, ids, mask_id, stop_ids, max_new_tokens, threshold, stats, prefix_cache, block_steps, confidence_order, guarded=guarded, suppressed=suppressed, scorer=scorer, block_size=block_size, ): pass return tokens
def fork_prefix_cache(cache): """Fork dynamic Inkling cache metadata and writable short-convolution state.
Dynamic attention updates replace K/V tensor references (torch.cat), so the immutable prefix K/V storage itself can be shared with every trial. """ fork = copy(cache) fork.layers = [] for original in cache.layers: layer = copy(original) for name in ('conv_kernel_size', 'has_previous_state', 'is_conv_states_initialized'): setattr(layer, name, copy(getattr(original, name))) layer.conv_states = {i: state.clone() if state is not None else None for i, state in original.conv_states.items()} layer.cumulative_length_linear = original.cumulative_length_linear.clone() fork.layers.append(layer) return fork
class BlockPrefix: def __init__(self, model): self.model = model self.cache = None self.length = 0 self.last_logits = None
def attention(self, ids, diffusion_start): window = self.model.config.text_config.sliding_window_size active_width = max(1, ids.shape[1] - diffusion_start) return attention_masks(ids.shape[1], diffusion_start, active_width, window, ids.device, self.model.get_input_embeddings().weight.dtype, query_start=self.length, sliding_start=max(0, self.length - window + 1))
@torch.no_grad() def commit(self, ids): if self.length == ids.shape[1]: return False out = self.model(input_ids=ids[:, self.length:], attention_mask=self.attention(ids, ids.shape[1]), cache=self.cache, use_cache=True, logits_to_keep=1) self.cache = out.cache self.last_logits = out.logits[0] self.length = ids.shape[1] return True
@torch.no_grad() def scores(self, ids, positions, attention): # Token shift: the first query's prediction comes from the causal prefix. first = positions[0].item() == self.length local = positions[int(first):] - self.length - 1 if not local.numel(): return self.last_logits.clone() context = ACTIVE.set(0) try: out = self.model(input_ids=ids[:, self.length:], attention_mask=attention, cache=fork_prefix_cache(self.cache), use_cache=True, logits_to_keep=local).logits[0] finally: ACTIVE.reset(context) return torch.cat((self.last_logits, out), dim=0) if first else out
def denoise_steps(model, ids, mask_id, stop_ids, max_new_tokens=128, threshold=0.9, stats=None, prefix_cache=False, block_steps=0, confidence_order=False, one_at_a_time=False, guarded=False, suppressed=(), scorer=None, block_size=BLOCK_SIZE, observe_draft=None): if not 1 <= block_size <= MAX_BLOCK_SIZE: raise ValueError(f'block_size must be between 1 and {MAX_BLOCK_SIZE}') generated = [] block = 0 prefix = BlockPrefix(model) if prefix_cache else None if scorer is not None and prefix is not None and not hasattr(scorer, 'begin_block'): raise ValueError('A custom scorer cannot be combined with prefix caching')
def evaluate(positions): if scorer is not None: return scorer(ids, positions, start) if prefix is not None: return prefix.scores(ids, positions, attention) return logits(model, ids, positions-1, start, subblock=ids.shape[1]-start) while len(generated) < max_new_tokens: block += 1 start = ids.shape[1] width = min(block_size, max_new_tokens-len(generated)) yield block, 0, width, 0, list(generated), [mask_id] * width if prefix is not None: commit = getattr(scorer, 'commit_prefix', None) committed = prefix.commit(ids) if commit is None else commit(prefix, ids) if committed and stats is not None: stats['cache_commits'] = stats.get('cache_commits', 0) + 1 ids = torch.cat([ids, ids.new_full((1, width), mask_id)], dim=1) attention = prefix.attention(ids, start) if prefix is not None else None if prefix is not None and scorer is not None: scorer.begin_block(prefix, ids, attention) cursor = start step = 0 block_start = len(generated) if confidence_order: while True: positions = (ids[0, start:] == mask_id).nonzero().flatten() + start if not positions.numel(): break with torch.no_grad(): scores = evaluate(positions) if guarded: confidence, tokens = guarded_candidates(scores, ids, positions, mask_id, stop_ids, suppressed) else: scores[:, mask_id] = -torch.inf confidence, tokens = scores.softmax(-1).max(-1) step += 1 if stats is not None: stats['forwards'] += 1 count = max(1, int((confidence >= threshold).sum().item())) if block_steps: count = max(count, math.ceil(len(positions) / max(1, block_steps-step+1))) if one_at_a_time: count = 1 elif guarded: count = min(count, int(confidence.isfinite().sum().item())) if one_at_a_time and confidence.max().item() < threshold: chosen = positions.new_zeros(1) else: chosen = confidence.topk(count).indices ids[0, positions[chosen]] = tokens[chosen] if observe_draft is not None: observe_draft(torch.stack((positions - start, tokens)).tolist()) cells = ids[0, start:].tolist() visible = [] stopped = False for token in cells: if token == mask_id: break if token in stop_ids: stopped = True break visible.append(token) yield block, step, width, width-cells.count(mask_id), generated + visible, cells if stopped: return generated.extend(cells) continue while cursor < start + width: positions = torch.arange(cursor, start+width, device=ids.device) with torch.no_grad(): scores = evaluate(positions) step += 1 if stats is not None: stats['forwards'] += 1 scores[:, mask_id] = -torch.inf confidence, tokens = scores.softmax(-1).max(-1) low = (confidence < threshold).nonzero() count = max(1, int(low[0, 0])) if low.numel() else len(positions) if block_steps: count = max(count, math.ceil(len(positions) / max(1, block_steps-step+1))) ids[0, cursor:cursor+count] = tokens[:count] cursor += count for token in tokens[:count].tolist(): if token in stop_ids: yield block, step, width, len(generated)-block_start, list(generated), ids[0, start:].tolist() return generated.append(token) yield block, step, width, len(generated)-block_start, list(generated), ids[0, start:].tolist()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137{%- set effort_map = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99} -%}{%- set role_token = {"user": "<|message_user|>", "assistant": "<|message_model|>", "system": "<|message_system|>", "tool": "<|message_tool|>"} -%}
{%- macro emit_thinking_effort() -%} {%- set eff = reasoning_effort if reasoning_effort is defined and reasoning_effort is not none else 0.9 -%} {%- if eff is string -%} {%- set key = eff | trim -%} {%- if key not in effort_map -%} {{- raise_exception("Unknown reasoning_effort: " ~ eff) -}} {%- endif -%} {%- set num = effort_map[key] -%} {%- else -%} {%- set num = eff | float -%} {%- endif -%} {%- if num < 0.0 or num > 0.99 -%} {{- raise_exception("reasoning_effort must be in [0.0, 0.99]") -}} {%- endif -%} {{- "<|message_system|><|content_text|>Thinking effort level: " -}} {%- if num == 0.0 -%}0{%- else -%}{{ num }}{%- endif -%} {{- "<|end_message|>" -}}{%- endmacro -%}
{%- if tools -%} {%- set tool_state = namespace(specs=[]) -%} {%- for tool in tools -%} {%- set fn = tool.function if tool.function is defined else tool -%} {%- set spec = { "description": (fn.description if fn.description is defined and fn.description else ""), "name": fn.name, "parameters": (fn.parameters if fn.parameters is defined and fn.parameters else {}), "type": (tool.type if tool.type is defined and tool.type else "function"), } -%} {%- set tool_state.specs = tool_state.specs + [spec] -%} {%- endfor -%} {{- "<|message_system|>tool_declare<|content_xml|>" -}} {{- tool_state.specs | tojson(sort_keys=true, separators=(",", ":")) -}} {{- "<|end_message|>" -}}{%- endif -%}
{%- set state = namespace(effort_emitted=false) -%}{%- for message in messages -%} {%- if message.role not in role_token -%} {{- raise_exception("Unknown message role: " ~ message.role) -}} {%- endif -%} {%- if not state.effort_emitted and message.role != "system" -%} {{- emit_thinking_effort() -}} {%- set state.effort_emitted = true -%} {%- endif -%}
{%- set header = namespace(text=role_token[message.role]) -%} {%- if message.role == "tool" -%} {%- if message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- elif message.tool_call_id is defined and message.tool_call_id -%} {%- for prev in messages -%} {%- if prev.role == "assistant" and prev.tool_calls -%} {%- for tc in prev.tool_calls -%} {%- if tc.id is defined and tc.id == message.tool_call_id and tc.function.name is defined -%} {%- set header.text = header.text ~ tc.function.name -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- endfor -%} {%- endif -%} {%- elif message.role == "assistant" and message.name is defined and message.name -%} {%- set header.text = header.text ~ message.name -%} {%- endif -%} {%- set rtok = header.text -%} {%- set rendered -%}
{%- if message.role == "assistant" and message.reasoning_content is defined and message.reasoning_content -%} {{- rtok ~ "<|content_thinking|>" ~ message.reasoning_content ~ "<|end_message|>" -}} {%- endif -%}
{%- if message.content is string and (message.content or not (message.role == "assistant" and (message.tool_calls or message.reasoning_content))) -%} {{- rtok ~ "<|content_text|>" ~ message.content ~ "<|end_message|>" -}} {%- elif message.content -%} {%- for part in message.content -%} {%- if part is string -%} {{- rtok ~ "<|content_text|>" ~ part ~ "<|end_message|>" -}} {%- elif part.type is not defined or part.type in ("text", "input_text") -%} {%- set text_part = (part.text if part.text is defined and part.text is string else "") -%} {{- rtok ~ "<|content_text|>" ~ text_part ~ "<|end_message|>" -}} {%- elif part.type in ("image", "input_image", "image_url") -%} {%- if message.role not in ("user", "tool") -%} {{- raise_exception("Image content is only supported for user and tool messages") -}} {%- endif -%} {{- rtok ~ "<|content_image|><|unused_200054|><|end_message|>" -}} {%- elif part.type in ("audio", "input_audio", "audio_url") -%} {{- raise_exception("Inkling 2 does not accept audio input") -}} {%- else -%} {{- raise_exception("Unsupported content part type: " ~ part.type) -}} {%- endif -%} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" and message.tool_calls -%} {%- for tc in message.tool_calls -%} {%- set fn = tc.function -%} {%- if fn.name is not defined or fn.name is not string -%} {{- raise_exception("tool call function name must be a string") -}} {%- endif -%} {%- if message.name is defined and message.name and message.name != fn.name -%} {{- raise_exception("assistant name " ~ message.name ~ " does not match its tool call " ~ fn.name) -}} {%- endif -%} {%- set args = fn.arguments if fn.arguments is defined and fn.arguments else {} -%} {%- if args is string -%} {{- raise_exception("tool call arguments must be a parsed object, not a JSON string; canonicalize upstream") -}} {%- endif -%} {%- if args is not mapping -%} {{- raise_exception("tool call arguments must be an object") -}} {%- endif -%} {{- "<|message_model|>" ~ fn.name ~ "<|content_invoke_tool_json|>" -}} {{- '{"name":' ~ (fn.name | tojson(sort_keys=true, separators=(",", ":"))) ~ ',"args":' -}} {{- "{" -}} {%- for key, value in args | dictsort(case_sensitive=true) -%} {{- (key | tojson) ~ ":" ~ (value | tojson(separators=(",", ":"))) -}} {%- if not loop.last -%},{%- endif -%} {%- endfor -%} {{- "}}<|end_message|>" -}} {%- endfor -%} {%- endif -%}
{%- if message.role == "assistant" -%} {{- "<|content_model_end_sampling|>" -}} {%- endif -%} {%- endset -%} {%- if message.role == "assistant" -%} {%- generation -%}{{- rendered -}}{%- endgeneration -%} {%- else -%} {{- rendered -}} {%- endif -%}{%- endfor -%}
{%- if not state.effort_emitted -%} {{- emit_thinking_effort() -}}{%- endif -%}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169{ "architectures": [ "Inkling2LoopForConditionalGeneration" ], "dtype": "bfloat16", "eos_token_id": 200006, "image_token_id": 200054, "model_type": "inkling2_loop", "mtp_config": { "block_size": 8, "head_dim": 128, "hidden_size": 2304, "intermediate_size": 9216, "local_layer_ids": [ 0, 2 ], "markov_head_type": "rnn_hidden", "markov_rank": 256, "max_position_embeddings": 1048576, "num_attention_heads": 24, "num_hidden_layers": 3, "num_key_value_heads": 8, "o_bias": false, "q_bias": false, "rms_norm_eps": 1e-06, "rope_theta": 1000000.0, "sliding_window_size": 1024, "target_layer_ids": [ 5, 23, 41, 48 ], "torch_dtype": "bfloat16" }, "text_config": { "attention_dropout": 0.0, "attn_res_normalize_values": true, "bos_token_id": null, "conv_kernel_size": 4, "d_rel": 16, "dtype": "bfloat16", "eos_token_id": 200006, "final_logit_softcapping": 30.0, "head_dim": 128, "hidden_act": "silu", "hidden_size": 2304, "initializer_range": 0.02, "layer_types": [ "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid_sliding", "hybrid" ], "local_layer_ids": [ 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22 ], "log_scaling_alpha": 0.1, "log_scaling_n_floor": 8192, "loop_config": { "core_end": 18, "core_start": 6, "gate_rank": 64, "is_varloop": false, "num_passes": 3 }, "loop_gate_rank": 64, "loop_layer_index_end": 18, "loop_layer_index_start": 6, "loop_num_passes": 3, "max_position_embeddings": 1048576, "mlp_gate_softcap": 4.0, "mlp_up_softcap": 25.0, "model_type": "inkling2_loop_text", "moe_intermediate_size": 1152, "n_layers_per_attn_res_block": 6, "n_routed_experts": 128, "n_shared_experts": 0, "num_attention_heads": 24, "num_experts_per_tok": 8, "num_hidden_layers": 24, "num_key_value_heads": 8, "o_bias": false, "pad_token_id": null, "q_bias": false, "qk_l2_clip_threshold": 22.627416997969522, "rel_extent": 1024, "rel_l2_clip_threshold": 8.0, "rms_norm_eps": 1e-06, "route_scale": 8.0, "scoring_func": "sigmoid", "sliding_window_size": 1024, "swa_head_dim": 128, "swa_num_attention_heads": 24, "swa_num_key_value_heads": 8, "unpadded_vocab_size": 200058, "use_cache": true, "use_gate_bias": true, "use_value_norm_no_gamma": true, "vocab_size": 201024 }, "transformers_version": "5.26.0.dev0", "vision_config": { "attention_dropout": 0.0, "dtype": "bfloat16", "hidden_act": "gelu", "hidden_size": 1024, "initializer_range": 0.02, "intermediate_size": 4096, "layer_norm_eps": 1e-05, "layer_scale_init_value": 0.1, "mlp_ratio": 4.0, "model_type": "inkling2_vision", "num_attention_heads": 16, "num_channels": 3, "num_hidden_layers": 23, "patch_size": 20, "posemb_grid_size": 32, "projection_hidden_dim": 4096, "projector_bias": false, "rope_parameters": { "rope_theta": 10000.0, "rope_type": "axial" }, "spatial_merge_size": 2, "temporal_patch_size": 2, "text_hidden_size": 2304 }}1234567{ "do_sample": true, "eos_token_id": 200006, "pad_token_id": 199999, "temperature": 1.0, "transformers_version": "5.26.0.dev0"}12MAX_BLOCK_SIZE = 512MAX_DIFFUSION_CONTEXT = 1024123version https://git-lfs.github.com/spec/v1oid sha256:969875792f73ed878858428e56d532bc463fddf7c59a1f58afe6fa75d9910f9csize 4432789832123version https://git-lfs.github.com/spec/v1oid sha256:c44903b1b03445dee6cbf8da99bea8312888e33c971130d1f82ef77aa9082a43size 4921926536123version https://git-lfs.github.com/spec/v1oid sha256:ff9c2d9bee0ca77a4548ce9ab39aff81f1b66abb17680510b82a7788c7c1ece1size 4187560864123version https://git-lfs.github.com/spec/v1oid sha256:2546199878a0b77adfd3224b787205995aec0f3d4bd06023078e4ede9ae76896size 4201413264123version https://git-lfs.github.com/spec/v1oid sha256:1d2d9ae3084b578f38ccfc94e2a26534cb8f683ebc99c93cfda8807de971c96dsize 4201413200123version https://git-lfs.github.com/spec/v1oid sha256:8f8aafffa4bd6729712e26b87ba839c8c40857df162b3f9ec739c32a3e696373size 4201720080123version https://git-lfs.github.com/spec/v1oid sha256:1b2e6549590793f72685f30264aa877d69ed7223b07842aa0ab0d31f7f1bdc46size 4201413336123version https://git-lfs.github.com/spec/v1oid sha256:621e3ddee8001ea316c633e9c7c2a9f7ad0e2e022dc12ede4476c42a9734a08esize 4201413336123version https://git-lfs.github.com/spec/v1oid sha256:68b96d826e650654800c155fbdb907984e77433d90f2464e39087e4049ca25b4size 4201720080123version https://git-lfs.github.com/spec/v1oid sha256:64af94f2bc0424a6b2350b2fb8d404f68fc9fd5e24e49b8126441645b5de4b60size 4187254176123version https://git-lfs.github.com/spec/v1oid sha256:b9225367c078e1e39449d429463f55a8dffa99c0dc6e07e0643e9e7c6142d3ebsize 4187254176123version https://git-lfs.github.com/spec/v1oid sha256:9f6b31c36c1d37a6f588b49d246ba7c60d08c725cc5a9827f2ec8dc624217418size 4770687456123version https://git-lfs.github.com/spec/v1oid sha256:c8da5b1f02a259061ae82bbff51e54e1be230435529b85ba1cfc9439561c8cf0size 92186739212345678910111213141516171819202122232425{ "image_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "Inkling2ImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "rescale_factor": 0.00392156862745098, "size": { "height": 40, "width": 40 } }, "image_token": "<|unused_200054|>", "processor_class": "Inkling2Processor"}1234567torch==2.14.1torchvision==0.29.2accelerate>=1.16tiktoken>=0.14safetensors>=0.8huggingface-hub>=2.4,<3transformers @ git+https://github.com/huggingface/transformers.git@626e62ef889c9b77c4d1425e076b17ee098ae925123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# SPDX-License-Identifier: Apache-2.0"""Load the merged Diffusion-Inkling-2-mini checkpoint and run masked denoising."""import argparsefrom pathlib import Path
import torchfrom transformers import AutoProcessorfrom transformers.models.inkling2_loop.modeling_inkling2_loop import Inkling2LoopForConditionalGeneration
from block_diffusion import generate, install_future_convolutionsfrom generation_limits import MAX_BLOCK_SIZE, MAX_DIFFUSION_CONTEXT
class DiffusionInkling2Mini(Inkling2LoopForConditionalGeneration): _keep_in_fp32_modules_strict = [*(Inkling2LoopForConditionalGeneration._keep_in_fp32_modules_strict or []), 'future_taps']
def __init__(self, config): super().__init__(config) install_future_convolutions(self)
def load_merged(source): model, info = DiffusionInkling2Mini.from_pretrained( str(source), device_map={'': 'cuda:0'}, dtype=torch.bfloat16, attn_implementation='eager', experts_implementation='grouped_mm', use_kernels=False, output_loading_info=True, ) if any(info.get(key) for key in ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs')): raise RuntimeError(f'Incomplete merged checkpoint load: {info}') return model.eval(), AutoProcessor.from_pretrained(str(source))
def encode_prompt(processor, prompt): rendered = processor.apply_chat_template([{'role': 'user', 'content': prompt}], tokenize=False, add_generation_prompt=False, reasoning_effort='none') return processor.tokenizer(rendered + '<|message_model|><|content_text|>', add_special_tokens=False, return_tensors='pt')['input_ids']
def generate_reply(model, processor, prompt, block_size=128, max_new_tokens=128, threshold=0.7): tokenizer = processor.tokenizer mask = tokenizer.convert_tokens_to_ids('<|unused_200054|>') stop = {tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids('<|end_message|>')} suppressed = sorted(set(tokenizer.all_special_ids) - stop) ids = encode_prompt(processor, prompt).to(model.device) if ids.shape[1] + max_new_tokens > MAX_DIFFUSION_CONTEXT or (ids == mask).any(): raise ValueError(f'Input and output budget must fit in {MAX_DIFFUSION_CONTEXT} tokens without the reserved mask.') tokens = generate(model, ids, mask, stop, max_new_tokens=max_new_tokens, threshold=threshold, confidence_order=True, guarded=True, suppressed=suppressed, block_size=block_size) return tokenizer.decode(tokens, skip_special_tokens=True)
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('prompt') parser.add_argument('--model', default=str(Path(__file__).resolve().parent)) parser.add_argument('--block-size', type=int, default=128) parser.add_argument('--max-new-tokens', type=int, default=128) parser.add_argument('--threshold', type=float, default=0.7) args = parser.parse_args() if not 1 <= args.block_size <= MAX_BLOCK_SIZE or not 0 <= args.threshold <= 1 or args.max_new_tokens < 1: parser.error('Specify a valid block size, confidence threshold, and reply budget.') model, processor = load_merged(args.model) print(generate_reply(model, processor, args.prompt, args.block_size, args.max_new_tokens, args.threshold))
if __name__ == '__main__': main()123version https://git-lfs.github.com/spec/v1oid sha256:7f332727f9a3f093dd452a39cc978e6757627e5dad1b0673aa4e75174f236dd6size 2617867812345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485{ "backend": "tokenizers", "begin_of_text": "<|begin_of_text|>", "clean_up_tokenization_spaces": false, "content_image": "<|content_image|>", "content_invoke_tool_json": "<|content_invoke_tool_json|>", "content_invoke_tool_text": "<|content_invoke_tool_text|>", "content_model_end_sampling": "<|content_model_end_sampling|>", "content_text": "<|content_text|>", "content_thinking": "<|content_thinking|>", "content_tool_error": "<|content_tool_error|>", "content_xml": "<|content_xml|>", "end_message": "<|end_message|>", "endoftext": "<|endoftext|>", "eos_token": "<|content_model_end_sampling|>", "fix_mistral_regex": false, "is_local": false, "local_files_only": false, "message_model": "<|message_model|>", "message_system": "<|message_system|>", "message_tool": "<|message_tool|>", "message_user": "<|message_user|>", "model_max_length": 1048576, "model_specific_special_tokens": { "begin_of_text": "<|begin_of_text|>", "content_image": "<|content_image|>", "content_invoke_tool_json": "<|content_invoke_tool_json|>", "content_invoke_tool_text": "<|content_invoke_tool_text|>", "content_model_end_sampling": "<|content_model_end_sampling|>", "content_text": "<|content_text|>", "content_thinking": "<|content_thinking|>", "content_tool_error": "<|content_tool_error|>", "content_xml": "<|content_xml|>", "end_message": "<|end_message|>", "endoftext": "<|endoftext|>", "message_model": "<|message_model|>", "message_system": "<|message_system|>", "message_tool": "<|message_tool|>", "message_user": "<|message_user|>" }, "pad_token": "<|endoftext|>", "processor_class": "Inkling2Processor", "response_template": { "defaults": { "role": "assistant" }, "fields": { "content": { "close": "<|end_message|>", "content": "text", "content_args": { "strip": false }, "join": "", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_(?:text|tool_error|invoke_tool_text)\\|>", "repeats": true }, "reasoning_content": { "close": "<|end_message|>", "content": "text", "content_args": { "strip": false }, "join": "", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_thinking\\|>", "repeats": true }, "tool_calls": { "close": "<|end_message|>", "content": "json", "open_pattern": "(?:<\\|message_model\\|>[^<]*)?<\\|content_invoke_tool_json\\|>", "repeats": true, "transform": { "function": { "arguments": "{content.args}", "name": "{content.name}" }, "type": "function" } } }, "start_anchor_pattern": "<\\|end_message\\|>|<\\|content_model_end_sampling\\|>" }, "tokenizer_class": "TokenizersBackend"}.gitattributes+1
LICENSEAdded+202
NOTICEAdded+14
README.mdAdded+44
block_diffusion.pyAdded+278
chat_template.jinjaAdded+137
config.jsonAdded+169
generation_config.jsonAdded+7
generation_limits.pyAdded+2
model-00001-of-00013.safetensorsAdded+3
model-00002-of-00013.safetensorsAdded+3
model-00003-of-00013.safetensorsAdded+3
model-00004-of-00013.safetensorsAdded+3
model-00005-of-00013.safetensorsAdded+3
model-00006-of-00013.safetensorsAdded+3
model-00007-of-00013.safetensorsAdded+3
model-00008-of-00013.safetensorsAdded+3
model-00009-of-00013.safetensorsAdded+3
model-00010-of-00013.safetensorsAdded+3
model-00011-of-00013.safetensorsAdded+3
model-00012-of-00013.safetensorsAdded+3
model-00013-of-00013.safetensorsAdded+3
model.safetensors.index.jsonAdded
processor_config.jsonAdded+25
requirements.txtAdded+7
run_diffusion.pyAdded+69
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded+85