Instructions to use reaperdoesntknow/TameLM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use reaperdoesntknow/TameLM with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="reaperdoesntknow/TameLM", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("reaperdoesntknow/TameLM", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use reaperdoesntknow/TameLM with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "reaperdoesntknow/TameLM" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "reaperdoesntknow/TameLM", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/reaperdoesntknow/TameLM
- SGLang
How to use reaperdoesntknow/TameLM 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 "reaperdoesntknow/TameLM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "reaperdoesntknow/TameLM", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'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 "reaperdoesntknow/TameLM" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "reaperdoesntknow/TameLM", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use reaperdoesntknow/TameLM with Docker Model Runner:
docker model run hf.co/reaperdoesntknow/TameLM
Download modeling_tamelm.py from reaperdoesntknow/TameLM: direct link, hf CLI and curl.
- Browser
- Download file 113 kB
-
https://huggingface.co/reaperdoesntknow/TameLM/resolve/main/modeling_tamelm.py
- Command line
-
hf download hf://reaperdoesntknow/TameLM/modeling_tamelm.py
-
curl -L -o modeling_tamelm.py https://huggingface.co/reaperdoesntknow/TameLM/resolve/main/modeling_tamelm.py
113 kB
| """TAMELM model definitions: routed attention, depth attention, and dropless MoE. | |
| This module stays self-contained for notebook execution and portable Hugging Face | |
| exports. Definitions are ordered from configuration and low-level operations to | |
| model components, cache/output interfaces, and the complete language model. | |
| Routing uses shared GQA projections and original top-k softmax probabilities. | |
| Tile routing and graph selection are causal; cached decoding retains tile state. | |
| CUDA FlexAttention and Triton grouped GEMM are optional acceleration backends. | |
| """ | |
| from __future__ import annotations | |
| import ast as _ast | |
| import inspect as _inspect | |
| import linecache as _linecache | |
| import math | |
| from dataclasses import dataclass | |
| from typing import Dict, Optional, Tuple | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| from transformers import ( | |
| AutoConfig, | |
| AutoModelForCausalLM, | |
| GenerationMixin, | |
| PretrainedConfig, | |
| PreTrainedModel, | |
| ) | |
| from transformers.cache_utils import Cache | |
| from transformers.utils import ModelOutput | |
| try: | |
| from torch.nn.attention.flex_attention import ( | |
| BlockMask, | |
| create_block_mask, | |
| flex_attention, | |
| ) | |
| HAS_FLEX = True | |
| except ImportError: # pragma: no cover | |
| HAS_FLEX = False | |
| try: | |
| import triton # type: ignore | |
| import triton.language as tl # type: ignore | |
| HAS_TRITON = True | |
| except ImportError: | |
| HAS_TRITON = False | |
| THIRD_PARTY_NOTICES = """Position adapters informed by zetascale 2.8.8, https://github.com/kyegomez/zeta. | |
| Modified for causal rectangular reads, explicit offsets, portable initialization, | |
| and efficient unique-distance evaluation. These are local adaptations, not direct Zeta imports. | |
| RelativePositionBias source notice: Copyright (c) 2022 Agora. MIT License. | |
| Permission is hereby granted, free of charge, to any person obtaining a copy | |
| of this software and associated documentation files (the "Software"), to deal | |
| in the Software without restriction, including without limitation the rights | |
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| copies of the Software, and to permit persons to whom the Software is | |
| furnished to do so, subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in | |
| all copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
| THE SOFTWARE. | |
| 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 [2023] [KyeGomez] | |
| 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. | |
| """ | |
| # Notebook source capture and semantic fingerprints. | |
| # Capture source independently of execution counts, paths, and timestamps. | |
| _NOTEBOOK_SOURCES = globals().get("_NOTEBOOK_SOURCES", {}) | |
| # ============================================================================= | |
| # Source identity helpers | |
| # ============================================================================= | |
| def _capture_cell_source(component): | |
| caller = _inspect.currentframe().f_back | |
| source = "".join(_linecache.getlines(caller.f_code.co_filename)) | |
| if not source: | |
| try: | |
| source = get_ipython().history_manager.input_hist_raw[-1] | |
| except (NameError, AttributeError, IndexError): | |
| raise RuntimeError( | |
| "Cannot capture executed source. Run the model, tokenizer, and harness cells in Jupyter/Colab." | |
| ) | |
| if not source.strip(): | |
| raise RuntimeError( | |
| "Cannot capture model source; rerun the model definition cell." | |
| ) | |
| _NOTEBOOK_SOURCES[component] = source | |
| class _WithoutDocstrings(_ast.NodeTransformer): | |
| def _strip(self, node): | |
| self.generic_visit(node) | |
| if ( | |
| node.body | |
| and isinstance(node.body[0], _ast.Expr) | |
| and isinstance(node.body[0].value, _ast.Constant) | |
| and isinstance(node.body[0].value.value, str) | |
| ): | |
| node.body = node.body[1:] or [_ast.Pass()] | |
| return node | |
| visit_Module = _strip | |
| visit_ClassDef = _strip | |
| visit_FunctionDef = _strip | |
| visit_AsyncFunctionDef = _strip | |
| def _semantic_source(source): | |
| return _ast.dump( | |
| _WithoutDocstrings().visit(_ast.parse(source)), include_attributes=False | |
| ) | |
| # Routing mechanism IDs are part of the attention/cache contract. | |
| GLOBAL, LOCAL, STRIDED, GRAPH = 0, 1, 2, 3 | |
| MECH_NAMES = ("global", "local", "strided", "graph") | |
| # ============================================================================= | |
| # Configuration | |
| # ============================================================================= | |
| class RoutedAttentionConfig: | |
| d_model: int | |
| n_q_heads: int = 16 | |
| n_kv_heads: int = 4 | |
| head_dim: Optional[int] = None | |
| top_k: int = 2 | |
| tile: int = 128 # routing granularity == FlexAttention block size | |
| local_window: int = 256 # tokens | |
| strided_recent: int = 128 # tokens of dense recent context for 'strided' | |
| strided_every: int = 4 # plus every S-th tile back (tile-relative) | |
| graph_top_r: int = 0 # past tiles picked by 'graph'; 0 = legacy 3-way router | |
| graph_recent: int = 128 # tokens of dense recent context for 'graph' | |
| max_seq_len: int = 2048 | |
| router_init_std: float = 1e-2 | |
| balance_coef: float = 1e-2 | |
| backend: str = "flex" # "flex" | "dense"; decode/cached paths always dense | |
| class TAMEConfig(PretrainedConfig): | |
| """Architecture settings grouped by backbone, attention, depth, and refinement. | |
| Head widths must divide the model width; rotary widths must be even. | |
| Defaults describe a fresh model. from_dict fills legacy checkpoint defaults. | |
| Backend choices change execution; bank/head/refinement choices are experiments. | |
| """ | |
| model_type = "tamelm_two_axis" | |
| attribute_map = { | |
| "hidden_size": "embed_dim", | |
| "num_hidden_layers": "num_layers", | |
| "num_attention_heads": "n_q_heads", | |
| "num_key_value_heads": "n_kv_heads", | |
| "max_position_embeddings": "max_seq_len", | |
| } | |
| # Keys introduced after the alpha checkpoint, with the value that reproduces | |
| # the older architecture when a saved config predates them. | |
| _LEGACY_DEFAULTS = { | |
| "graph_top_r": 0, | |
| "init_scheme": "pilot", | |
| "reasoning_mode": "none", | |
| "reasoning_revisit_mode": "full", | |
| "expert_banks": 1, | |
| "expert_bank_top_k": 1, | |
| "reasoning_position_bias": "none", | |
| "add_sinusoidal_embeddings": False, | |
| } | |
| def __init__( | |
| self, | |
| # Backbone and expert capacity (see MODEL_CONFIGURATION.md). | |
| vocab_size=44469, | |
| embed_dim=768, | |
| num_layers=12, | |
| num_experts=8, | |
| expert_top_k=2, | |
| expert_hidden_dim=3072, | |
| # Sequence attention and execution backends (see MODEL_CONFIGURATION.md). | |
| n_q_heads=32, | |
| n_kv_heads=4, | |
| attention_top_k=2, | |
| tile=128, | |
| local_window=256, | |
| strided_recent=128, | |
| strided_every=4, | |
| graph_top_r=2, | |
| graph_recent=128, | |
| attention_backend="flex", | |
| expert_backend="grouped", | |
| max_seq_len=2048, | |
| # Same-token depth memory (see MODEL_CONFIGURATION.md). | |
| depth_mode="attention", | |
| depth_slots=4, | |
| depth_dim=256, | |
| depth_heads=4, | |
| depth_gate_init=0.01, | |
| # Loss, positions, and initialization (see MODEL_CONFIGURATION.md). | |
| balance_coef=0.01, | |
| router_z_loss_coef=0.0, | |
| rope_type="warped", | |
| router_init_std=0.01, | |
| init_scheme="v1", | |
| loss_chunk_size=256, | |
| # Tokenizer and generation (see MODEL_CONFIGURATION.md). | |
| pad_token_id=0, | |
| bos_token_id=1, | |
| eos_token_id=2, | |
| use_cache=True, | |
| # Refinement and bank capacity (see MODEL_CONFIGURATION.md). | |
| reasoning_mode="fold_unfold", # "fold_unfold" | "none" | |
| reasoning_slots=4, | |
| reasoning_steps=3, | |
| reasoning_heads=4, | |
| reasoning_chunk_size=32, | |
| reasoning_gate_init=0.1, | |
| reasoning_initial_fold=True, | |
| reasoning_direct_read=True, | |
| reasoning_revisit_mode="full", # "full" | "local_only" | |
| expert_banks=4, | |
| expert_bank_top_k=2, | |
| # Memory and optional position mechanisms (see MODEL_CONFIGURATION.md). | |
| checkpoint_backbone=False, | |
| reasoning_position_bias="none", # "none" | "relative" | "continuous" | |
| add_sinusoidal_embeddings=False, | |
| **kwargs, | |
| ): | |
| kwargs.setdefault("tie_word_embeddings", True) | |
| super().__init__( | |
| pad_token_id=pad_token_id, | |
| bos_token_id=bos_token_id, | |
| eos_token_id=eos_token_id, | |
| **kwargs, | |
| ) | |
| values = locals().copy() | |
| for key, value in values.items(): | |
| if key not in {"self", "kwargs", "__class__", "values"}: | |
| setattr(self, key, value) | |
| if embed_dim % n_q_heads or (embed_dim // n_q_heads) % 2: | |
| raise ValueError( | |
| "Width must divide query heads with even rotary head dimension" | |
| ) | |
| if depth_dim % depth_heads or depth_mode not in {"attention", "baseline"}: | |
| raise ValueError("Invalid depth dimensions/mode") | |
| if ( | |
| not 1 <= expert_top_k <= num_experts | |
| or min(num_layers, depth_slots, loss_chunk_size) < 1 | |
| ): | |
| raise ValueError("Invalid expert/depth/loss dimensions") | |
| if expert_backend not in {"reference", "grouped"} or rope_type not in { | |
| "blackhole", | |
| "standard", | |
| "warped", | |
| }: | |
| raise ValueError("Unknown expert backend or position transform") | |
| if not math.isfinite(router_z_loss_coef) or router_z_loss_coef < 0: | |
| raise ValueError("router_z_loss_coef must be finite and nonnegative") | |
| if graph_top_r < 0 or init_scheme not in {"v1", "pilot"} or router_init_std < 0: | |
| raise ValueError("Invalid graph_top_r, init_scheme or router_init_std") | |
| if not isinstance(reasoning_initial_fold, bool) or not isinstance(reasoning_direct_read, bool): | |
| raise ValueError("Refinement branch switches must be booleans") | |
| if reasoning_mode not in {"none", "fold_unfold"}: | |
| raise ValueError("Unknown reasoning_mode") | |
| if reasoning_revisit_mode not in {"full", "local_only"}: | |
| raise ValueError("Unknown reasoning_revisit_mode") | |
| if reasoning_position_bias not in {"none", "relative", "continuous"}: | |
| raise ValueError("Unknown reasoning_position_bias") | |
| if reasoning_mode == "none" and reasoning_position_bias != "none": | |
| raise ValueError("reasoning_position_bias requires fold_unfold reasoning") | |
| if ( | |
| min(reasoning_slots, reasoning_steps, reasoning_heads, reasoning_chunk_size) | |
| < 1 | |
| or embed_dim % reasoning_heads | |
| ): | |
| raise ValueError("Invalid reasoning dimensions/steps/chunk size") | |
| if not 1 <= expert_bank_top_k <= expert_banks: | |
| raise ValueError("expert_bank_top_k must be between 1 and expert_banks") | |
| def from_dict(cls, config_dict, **kwargs): | |
| config_dict = dict(config_dict) | |
| for key, legacy in cls._LEGACY_DEFAULTS.items(): | |
| config_dict.setdefault(key, legacy) | |
| return super().from_dict(config_dict, **kwargs) | |
| # ============================================================================= | |
| # Shared routing precision | |
| # ============================================================================= | |
| def router_logits_fp32(router, x): | |
| """Keep routing decisions out of AMP; casting rounded BF16 logits is too late.""" | |
| with torch.autocast(device_type=x.device.type, enabled=False): | |
| return F.linear( | |
| x.float(), | |
| router.weight.float(), | |
| None if router.bias is None else router.bias.float(), | |
| ) | |
| # ============================================================================= | |
| # Position transforms | |
| # ============================================================================= | |
| class ScaledSinusoidalEmbedding(nn.Module): | |
| """Zeta-style learned sinusoidal scale, with correct explicit/cache positions. | |
| Adapted interface: frequencies are computed at use time for meta/HF loading; | |
| supplied positions are respected rather than replaced. See bundled notices. | |
| """ | |
| def __init__(self, dim, theta=10000): | |
| super().__init__() | |
| if dim < 2 or dim % 2: | |
| raise ValueError("Sinusoidal embedding width must be positive and even") | |
| self.dim, self.theta = dim, theta | |
| self.scale = nn.Parameter(torch.tensor(dim**-0.5)) | |
| def forward(self, x, pos=None, seq_start_pos=None, start_pos=0): | |
| if pos is None: | |
| pos = torch.arange(start_pos, start_pos + x.shape[1], device=x.device) | |
| else: | |
| pos = pos.to(x.device) | |
| if seq_start_pos is not None: | |
| pos = pos - seq_start_pos.to(x.device)[..., None] | |
| inv = self.theta ** ( | |
| -torch.arange(self.dim // 2, device=x.device).float() / (self.dim // 2) | |
| ) | |
| angles = pos.float()[..., None] * inv | |
| return (torch.cat((angles.sin(), angles.cos()), dim=-1) * self.scale).to( | |
| x.dtype | |
| ) | |
| class RelativePositionBias(nn.Module): | |
| """Causal logarithmic distance buckets; rectangular cached reads supported. | |
| Adapted from Zeta's RelativePositionBias (Copyright 2022 Agora, MIT). | |
| Here forward returns [1, heads, queries, keys], ready for SDPA masks. | |
| """ | |
| def __init__(self, heads, num_buckets=32, max_distance=128): | |
| super().__init__() | |
| if num_buckets < 4 or max_distance <= num_buckets // 2: | |
| raise ValueError("Invalid relative position buckets/distance") | |
| self.num_buckets, self.max_distance = num_buckets, max_distance | |
| self.relative_attention_bias = nn.Embedding(num_buckets, heads) | |
| nn.init.zeros_(self.relative_attention_bias.weight) | |
| def forward(self, qlen, klen, start_pos=0): | |
| device = self.relative_attention_bias.weight.device | |
| distance = ( | |
| torch.arange(start_pos, start_pos + qlen, device=device)[:, None] | |
| - torch.arange(klen, device=device)[None, :] | |
| ).clamp_min(0) | |
| exact = self.num_buckets // 2 | |
| large = ( | |
| exact | |
| + ( | |
| torch.log(distance.float().clamp_min(exact) / exact) | |
| / math.log(self.max_distance / exact) | |
| * (self.num_buckets - exact) | |
| ).long() | |
| ) | |
| bucket = torch.where( | |
| distance < exact, distance, large.clamp_max(self.num_buckets - 1) | |
| ) | |
| return self.relative_attention_bias(bucket).permute(2, 0, 1).unsqueeze(0) | |
| class ContinuousPositionBias(nn.Module): | |
| """Zeta-inspired 1-D relative-bias MLP evaluated once per unique distance. | |
| Uses signed log distances and rectangular query offsets. It does not allocate | |
| an MLP activation for every query/key pair or depend on future token content. | |
| """ | |
| def __init__(self, dim, heads): | |
| super().__init__() | |
| self.net = nn.Sequential( | |
| nn.Linear(1, dim, bias=False), nn.SiLU(), nn.Linear(dim, heads, bias=False) | |
| ) | |
| def forward(self, qlen, klen, start_pos=0): | |
| device = self.net[0].weight.device | |
| minimum = start_pos - klen + 1 | |
| offsets = torch.arange(minimum, start_pos + qlen, device=device) | |
| feature = offsets.float().sign() * offsets.float().abs().log1p() | |
| values = self.net(feature[:, None]) | |
| distance = ( | |
| torch.arange(start_pos, start_pos + qlen, device=device)[:, None] | |
| - torch.arange(klen, device=device)[None, :] | |
| ) | |
| return values[distance - minimum].permute(2, 0, 1).unsqueeze(0) | |
| class RotaryPos(nn.Module): | |
| """Standard RoPE with interleaved pairs (same pairing convention as BlackHoleRoPE).""" | |
| def __init__(self, head_dim: int, base: float = 10_000.0): | |
| super().__init__() | |
| half = head_dim // 2 | |
| self.register_buffer( | |
| "inv", 1.0 / base ** (torch.arange(half).float() / half), persistent=False | |
| ) | |
| def forward(self, x, start_pos: int = 0, **_): # x: [B, H, T, dh] | |
| T = x.shape[2] | |
| t = torch.arange(start_pos, start_pos + T, device=x.device, dtype=torch.float32) | |
| ang = t[:, None] * self.inv[None] | |
| cos, sin = ang.cos(), ang.sin() | |
| xf = x.float() | |
| x1, x2 = xf[..., 0::2], xf[..., 1::2] | |
| return ( | |
| torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1) | |
| .flatten(-2) | |
| .to(x.dtype) | |
| ) | |
| class WarpedRoPE(nn.Module): | |
| """RoPE on a content-defined clock, one clock per KV group. | |
| tau_t = softplus(w . x_t + b) > 0 clock rate of token t | |
| T_t = sum_{s<t} tau_s token time (exclusive prefix sum) | |
| angle = omega_f * T_t | |
| q_m . k_n then depends on T_m - T_n = sum_{n<=s<m} tau_s: only the tokens between | |
| them, so attention is relative in warped time and independent of where a document | |
| sits in a packed window. Causal, cumsum-parallel, O(1) decode state (the running | |
| time). At init (w = 0, softplus(b) = 1) it is exactly standard RoPE. | |
| """ | |
| def __init__( | |
| self, | |
| d_model: int, | |
| head_dim: int, | |
| n_q_heads: int, | |
| n_kv_heads: int, | |
| base: float = 10_000.0, | |
| ): | |
| super().__init__() | |
| if head_dim % 2 or n_q_heads % n_kv_heads: | |
| raise ValueError( | |
| "WarpedRoPE needs an even head_dim and grouped query heads" | |
| ) | |
| self.half, self.base = head_dim // 2, float(base) | |
| self.group = n_q_heads // n_kv_heads | |
| self.rate = nn.Linear(d_model, n_kv_heads) | |
| self.reset_parameters() | |
| def reset_parameters(self): | |
| nn.init.zeros_(self.rate.weight) | |
| nn.init.constant_(self.rate.bias, math.log(math.e - 1.0)) # softplus(b) = 1 | |
| def clock(self, x, t0=None): | |
| """x [B,T,d] (normed). t0 [B,Hkv] time already elapsed, or None. | |
| Returns token times [B,T,Hkv] and inclusive times [B,T,Hkv] (cache state).""" | |
| tau = F.softplus(router_logits_fp32(self.rate, x)) # fp32 | |
| inclusive = tau.cumsum(1) | |
| if t0 is not None: | |
| inclusive = inclusive + t0[:, None] | |
| return inclusive - tau, inclusive | |
| def rotate(self, x, times): # x [B,h,T,dh]; times [B,h,T] | |
| # Frequencies are recomputed rather than buffered: nothing here can be left | |
| # uninitialized by meta-device / no_init_weights loading. | |
| inv = 1.0 / self.base ** ( | |
| torch.arange(self.half, device=x.device, dtype=torch.float32) / self.half | |
| ) | |
| ang = times[..., None] * inv | |
| cos, sin = ang.cos(), ang.sin() | |
| xf = x.float() | |
| x1, x2 = xf[..., 0::2], xf[..., 1::2] | |
| return ( | |
| torch.stack([x1 * cos - x2 * sin, x1 * sin + x2 * cos], -1) | |
| .flatten(-2) | |
| .to(x.dtype) | |
| ) | |
| class BlackHoleRoPE(nn.Module): | |
| def __init__( | |
| self, | |
| dim, | |
| max_seq_len=2048, | |
| base_vortex_strength=1.0, | |
| energy_amplification=0.1, | |
| theta_base=10_000.0, | |
| adaptive_vortex=True, | |
| discrepancy_modulation=True, | |
| ): | |
| super().__init__() | |
| if dim <= 0 or dim % 2 or max_seq_len < 1: | |
| raise ValueError( | |
| "BlackHoleRoPE requires an even dimension and positive max_seq_len" | |
| ) | |
| self.dim = int(dim) | |
| self.half_dim = dim // 2 | |
| self.max_seq_len = int(max_seq_len) | |
| self.energy_amplification = float(energy_amplification) | |
| self.discrepancy_modulation = bool(discrepancy_modulation) | |
| freqs = 1.0 / ( | |
| theta_base | |
| ** (torch.arange(0, self.half_dim, dtype=torch.float32) / self.half_dim) | |
| ) | |
| self.register_buffer("base_freqs", freqs) | |
| self.vortex_strength = nn.Parameter( | |
| torch.full((max_seq_len,), base_vortex_strength), | |
| requires_grad=adaptive_vortex, | |
| ) | |
| self.phase_shift = nn.Parameter(torch.randn(max_seq_len, self.half_dim) * 0.01) | |
| self.radial_warp = nn.Parameter(torch.ones(max_seq_len, self.half_dim)) | |
| if discrepancy_modulation: | |
| self.discrepancy_projector = nn.Sequential( | |
| nn.Linear(dim, self.half_dim), | |
| nn.Tanh(), | |
| nn.Linear(self.half_dim, self.half_dim), | |
| ) | |
| self.register_buffer("energy_clamp_min", torch.tensor(0.1)) | |
| self.register_buffer("energy_clamp_max", torch.tensor(10.0)) | |
| def _compute_positional_vortex(self, seq_len, device, dtype, start_pos=0): | |
| positions = torch.arange( | |
| start_pos, start_pos + seq_len, dtype=torch.float32, device=device | |
| ) | |
| position_freqs = positions.unsqueeze(1) * self.base_freqs.unsqueeze(0) | |
| base_phase = position_freqs + self.phase_shift[start_pos : start_pos + seq_len] | |
| vortex_phase = self.vortex_strength[start_pos : start_pos + seq_len].unsqueeze( | |
| 1 | |
| ) * torch.sin(base_phase + position_freqs * 0.1) | |
| final_phase = base_phase + vortex_phase | |
| rotation = torch.complex(torch.cos(final_phase), torch.sin(final_phase)) | |
| radial_factor = torch.sqrt(position_freqs + 1e-8) | |
| energy = 1.0 + self.energy_amplification * torch.sin( | |
| self.radial_warp[start_pos : start_pos + seq_len] * radial_factor | |
| + vortex_phase.abs() | |
| ) | |
| energy = energy.clamp(self.energy_clamp_min, self.energy_clamp_max) | |
| return rotation, energy.to(dtype=dtype) | |
| def apply_discrepancy_modulation(self, x, symplectic_state): | |
| if not self.discrepancy_modulation or not symplectic_state: | |
| return None | |
| bsz, seq_len, _ = x.shape | |
| total = torch.zeros(bsz, seq_len, 1, device=x.device, dtype=x.dtype) | |
| count = 0 | |
| for theta, p in symplectic_state.values(): | |
| if theta is None or p is None: | |
| continue | |
| ev = theta.float().var(dim=-1, keepdim=True, correction=0) + p.float().var( | |
| dim=-1, keepdim=True, correction=0 | |
| ) | |
| ev = ( | |
| ev.unsqueeze(1).expand(-1, seq_len, -1) | |
| if theta.dim() == 2 | |
| else ev[:, :seq_len] | |
| ) | |
| total = total + ev.to(dtype=x.dtype) | |
| count += 1 | |
| if count == 0: | |
| return None | |
| lifted = F.pad(total / count, (0, self.dim - 1)) | |
| return self.discrepancy_projector(lifted) | |
| def forward(self, x, symplectic_state=None, start_pos=0): | |
| bsz, seq_len, dim = x.shape | |
| if dim != self.dim or start_pos < 0 or start_pos + seq_len > self.max_seq_len: | |
| raise ValueError( | |
| "BlackHoleRoPE dimension/position exceeds configured bounds" | |
| ) | |
| input_dtype = x.dtype | |
| xp = x.reshape(bsz, seq_len, self.half_dim, 2) | |
| xc = torch.complex(xp[..., 0].float(), xp[..., 1].float()) | |
| rotation, energy = self._compute_positional_vortex( | |
| seq_len, x.device, torch.float32, start_pos | |
| ) | |
| rotation = rotation.unsqueeze(0) | |
| energy = energy.unsqueeze(0) | |
| disc = self.apply_discrepancy_modulation(x, symplectic_state) | |
| if disc is not None: | |
| phase_scale = 1.0 + 0.1 * torch.tanh(disc.float()) | |
| base_phase = torch.angle(rotation) | |
| rotation = torch.polar( | |
| torch.ones_like(base_phase), base_phase * phase_scale | |
| ) | |
| amp = xc * rotation * energy.float() | |
| return ( | |
| torch.stack([amp.real, amp.imag], dim=-1) | |
| .reshape(bsz, seq_len, dim) | |
| .to(input_dtype) | |
| ) | |
| class BlackHolePos(nn.Module): | |
| """Adapter: folds heads into batch for BlackHoleRoPE and repeats the symplectic | |
| state per head so discrepancy modulation keeps the right batch alignment.""" | |
| def __init__(self, bh: nn.Module): | |
| super().__init__() | |
| self.bh = bh | |
| def forward(self, x, start_pos: int = 0, symplectic_state=None): | |
| B, H, T, dh = x.shape | |
| state = None | |
| if symplectic_state: | |
| state = { | |
| n: (th.repeat_interleave(H, 0), p.repeat_interleave(H, 0)) | |
| for n, (th, p) in symplectic_state.items() | |
| if th is not None and p is not None | |
| } | |
| y = self.bh( | |
| x.reshape(B * H, T, dh), symplectic_state=state, start_pos=start_pos | |
| ) | |
| return y.view(B, H, T, dh) | |
| # FlexAttention compilation is lazy and shared by CUDA attention calls. | |
| _COMPILED_FLEX = None | |
| # ============================================================================= | |
| # Attention backends and visibility geometry | |
| # ============================================================================= | |
| def _run_flex(q, k, v, block_mask): | |
| global _COMPILED_FLEX | |
| if q.is_cuda: | |
| if min(q.shape[-1], k.shape[-1], v.shape[-1]) < 16: | |
| raise ValueError( | |
| "CUDA FlexAttention requires head_dim >= 16; use a supported GPU model configuration" | |
| ) | |
| if _COMPILED_FLEX is None: | |
| _COMPILED_FLEX = torch.compile(flex_attention, dynamic=False) | |
| return _COMPILED_FLEX(q, k, v, block_mask=block_mask, enable_gqa=True) | |
| return flex_attention(q, k, v, block_mask=block_mask, enable_gqa=True) | |
| def geometry_allows(mech, q_idx, kv_idx, cfg: RoutedAttentionConfig, picked=None): | |
| """Boolean key-visibility for a given mechanism id. Pure tensor algebra so the | |
| same function serves FlexAttention's mask_mod and the dense reference mask. | |
| `picked` is True where kv_idx lies in a graph-selected tile of q_idx's tile.""" | |
| d = q_idx - kv_idx | |
| causal = d >= 0 | |
| local = d < cfg.local_window | |
| tile_gap = torch.div(q_idx, cfg.tile, rounding_mode="floor") - torch.div( | |
| kv_idx, cfg.tile, rounding_mode="floor" | |
| ) | |
| strided = (d < cfg.strided_recent) | ( | |
| torch.remainder(tile_gap, cfg.strided_every) == 0 | |
| ) | |
| allowed = ( | |
| (mech == GLOBAL) | ((mech == LOCAL) & local) | ((mech == STRIDED) & strided) | |
| ) | |
| if cfg.graph_top_r: | |
| graph = d < cfg.graph_recent | |
| if picked is not None: | |
| graph = graph | picked | |
| allowed = allowed | ((mech == GRAPH) & graph) | |
| return causal & allowed | |
| def geometry_block_mask(mech, length, cfg, mask_mod, picked=None): | |
| """Exact block classification in O(B * H * (T/tile)^2), never O(B*H*T^2). | |
| A partial block uses the original elementwise predicate. Fully allowed blocks | |
| skip that predicate. No attention probabilities or causal rules are approximated. | |
| `picked` is the tile-level graph selection [B, H, n, n] (query tile, kv tile). | |
| """ | |
| c = cfg.tile | |
| n = mech.shape[-1] | |
| starts = torch.arange(n, device=mech.device) * c | |
| ends = (starts + c - 1).clamp(max=length - 1) | |
| dmin = starts[:, None] - ends[None, :] | |
| dmax = ends[:, None] - starts[None, :] | |
| gap = ( | |
| torch.arange(n, device=mech.device)[:, None] | |
| - torch.arange(n, device=mech.device)[None, :] | |
| ) | |
| periodic = gap.remainder(cfg.strided_every) == 0 | |
| mechanism = mech[..., None] | |
| any_geometry = ( | |
| (mechanism == GLOBAL) | |
| | ((mechanism == LOCAL) & (dmin < cfg.local_window)) | |
| | ((mechanism == STRIDED) & ((dmin < cfg.strided_recent) | periodic)) | |
| ) | |
| full_geometry = ( | |
| (mechanism == GLOBAL) | |
| | ((mechanism == LOCAL) & (dmax < cfg.local_window)) | |
| | ((mechanism == STRIDED) & ((dmax < cfg.strided_recent) | periodic)) | |
| ) | |
| if cfg.graph_top_r: | |
| g_any, g_full = dmin < cfg.graph_recent, dmax < cfg.graph_recent | |
| if picked is not None: | |
| # A picked tile is a strictly earlier, complete tile: every pair in the | |
| # block is allowed, so it is safe for the full-block path. | |
| g_any, g_full = g_any | picked, g_full | picked | |
| any_geometry = any_geometry | ((mechanism == GRAPH) & g_any) | |
| full_geometry = full_geometry | ((mechanism == GRAPH) & g_full) | |
| any_block = (dmax >= 0) & any_geometry | |
| # Out-of-range positions in tail tiles are masked. Such blocks must not | |
| # enter the full-block path, which skips mask_mod in the CUDA kernel. | |
| complete_tiles = starts + c <= length | |
| full = ( | |
| (dmin >= 0) & full_geometry & complete_tiles[:, None] & complete_tiles[None, :] | |
| ) | |
| partial = any_block & ~full | |
| def encode(mask): | |
| counts = mask.sum(-1).to( | |
| dtype=torch.int32, memory_format=torch.contiguous_format | |
| ) | |
| # Router permutes tile/head axes; argsort preserves that nonstandard | |
| # layout. CUDA Flex flattens B/H using the H stride and requires | |
| # contiguous metadata (the CPU eager path does not enforce this). | |
| indices = ( | |
| mask.to(torch.int32) | |
| .argsort(dim=-1, descending=True, stable=True) | |
| .to(dtype=torch.int32, memory_format=torch.contiguous_format) | |
| ) | |
| return counts, indices | |
| pnum, pidx = encode(partial) | |
| fnum, fidx = encode(full) | |
| return BlockMask.from_kv_blocks( | |
| pnum, | |
| pidx, | |
| fnum, | |
| fidx, | |
| BLOCK_SIZE=c, | |
| mask_mod=mask_mod, | |
| seq_lengths=(length, length), | |
| ) | |
| # TAMELM routed sequence attention, v2. | |
| # | |
| # One shared GQA projection/cache; a tiny tile-level router picks, per (tile, q-head), | |
| # top-k attention geometries from {global, local, strided, graph}; all geometries run | |
| # through ONE attention call (FlexAttention block mask, or an equivalent dense mask). | |
| # | |
| # Invariants: | |
| # * K/V are projected, position-encoded and cached BEFORE routing. | |
| # * Tile routing is causal: tile c is routed, and its graph neighbours are chosen, | |
| # from its first token only, so training == chunked prefill == token-by-token decode. | |
| # * Top-k outputs are weighted by the ORIGINAL softmax probabilities (no | |
| # renormalization), so top-1 still trains the router. | |
| # * Graph geometry: a query tile sees its recent window plus the top-r COMPLETED | |
| # past tiles ranked by (first-token query) . (tile-mean key). Ranking uses | |
| # un-rotated q/k, so it is content similarity rather than position. The tile choice | |
| # is hard (no gradient); the router weight on 'graph' is what trains. This is the | |
| # causal, tile-level repair of the learned k-NN adjacency from the graph router. | |
| # | |
| # Positional transform is pluggable: RotaryPos (standard RoPE), WarpedRoPE (RoPE on a | |
| # content-defined clock; relative in warped time), or BlackHolePos (legacy adapter; | |
| # note it depends on absolute position through per-position phase/vortex/energy). | |
| # ============================================================================= | |
| # Routed sequence attention | |
| # ============================================================================= | |
| class RoutedSequenceAttention(nn.Module): | |
| def __init__(self, cfg: RoutedAttentionConfig, pos: Optional[nn.Module] = None): | |
| super().__init__() | |
| H, Hkv, K = cfg.n_q_heads, cfg.n_kv_heads, cfg.top_k | |
| dh = cfg.head_dim or cfg.d_model // H | |
| if cfg.graph_top_r < 0: | |
| raise ValueError("graph_top_r must be nonnegative") | |
| self.M = 4 if cfg.graph_top_r else 3 # number of mechanisms | |
| if ( | |
| min( | |
| H, | |
| Hkv, | |
| dh, | |
| cfg.tile, | |
| cfg.local_window, | |
| cfg.strided_recent, | |
| cfg.strided_every, | |
| cfg.graph_recent, | |
| cfg.max_seq_len, | |
| ) | |
| <= 0 | |
| ): | |
| raise ValueError("Attention dimensions/windows must be positive") | |
| if H % Hkv or dh % 2 or not 1 <= K <= self.M: | |
| raise ValueError("Invalid GQA heads, odd rotary dimension, or top_k") | |
| if cfg.backend not in {"flex", "dense"}: | |
| raise ValueError("backend must be flex or dense") | |
| self.cfg, self.H, self.Hkv, self.K, self.dh = cfg, H, Hkv, K, dh | |
| self.graph = bool(cfg.graph_top_r) | |
| self.n_max = -(-cfg.max_seq_len // cfg.tile) # tiles in a full window | |
| self._force_flex = False # test hook: Flex on CPU (eager) | |
| self.q_proj = nn.Linear(cfg.d_model, H * dh, bias=False) | |
| self.k_proj = nn.Linear(cfg.d_model, Hkv * dh, bias=False) | |
| self.v_proj = nn.Linear(cfg.d_model, Hkv * dh, bias=False) | |
| self.o_proj = nn.Linear(H * dh, cfg.d_model, bias=False) | |
| self.router = nn.Linear(cfg.d_model, H * self.M, bias=False) | |
| nn.init.normal_(self.router.weight, std=cfg.router_init_std) | |
| # [H, M] mask: this revision has no mandatory anchor heads. | |
| # The run contract records actual constraints; anchored variants are separate experiments. | |
| self.register_buffer("allowed", torch.ones(H, self.M, dtype=torch.bool)) | |
| self.pos = pos if pos is not None else RotaryPos(dh) | |
| # --------------------------------------------------------------------- routing | |
| def _route(self, x_starts): # [B, n, d] | |
| B, n, _ = x_starts.shape | |
| logits = router_logits_fp32(self.router, x_starts).view(B, n, self.H, self.M) | |
| logits = logits.masked_fill(~self.allowed, float("-inf")) | |
| P = logits.softmax(-1) | |
| w, idx = P.topk(self.K, dim=-1) # un-renormalized weights | |
| return P, w, idx | |
| def _balance(self, P, idx): | |
| M = self.M | |
| f = F.one_hot(idx, M).float().sum(-2).reshape(-1, M).mean(0) / self.K | |
| Pbar = P.reshape(-1, M).mean(0) | |
| loss = self.cfg.balance_coef * M * (f * Pbar).sum() | |
| ent = -(P.clamp_min(1e-9).log() * P).sum(-1).mean() | |
| return loss, f.detach(), ent.detach() | |
| def _select_tiles(self, q_first, k_raw, tiles): | |
| """q_first [B,H,n_new,dh]: un-rotated query of each new tile's first token. | |
| k_raw [B,Hkv,S,dh]: every un-rotated key known so far. tiles [n_new]. | |
| Returns [B, n_new, H, n_max] bool: past complete tiles picked per query tile.""" | |
| C, r = self.cfg.tile, self.cfg.graph_top_r | |
| B, H, n_new, dh = q_first.shape | |
| sel = torch.zeros( | |
| B, n_new, H, self.n_max, dtype=torch.bool, device=q_first.device | |
| ) | |
| n_full = min(k_raw.shape[2] // C, self.n_max) | |
| if n_full == 0 or n_new == 0: | |
| return sel | |
| with torch.autocast(device_type=q_first.device.type, enabled=False): | |
| kbar = k_raw[:, :, : n_full * C].float().unflatten(2, (n_full, C)).mean(3) | |
| kbar = kbar.repeat_interleave(H // self.Hkv, dim=1) # [B,H,n_full,dh] | |
| scores = torch.einsum("bhnd,bhtd->bnht", q_first.float(), kbar) | |
| # Tile t is a candidate for query tile c iff t < c (strictly earlier, hence | |
| # complete by the time tile c's first token exists). | |
| past = torch.arange(n_full, device=sel.device)[None, :] < tiles[:, None] | |
| scores = scores.masked_fill(~past[None, :, None, :], float("-inf")) | |
| vals, idx = scores.topk(min(r, n_full), dim=-1) | |
| part = torch.zeros(B, n_new, H, n_full, dtype=torch.bool, device=sel.device) | |
| part.scatter_(-1, idx, torch.isfinite(vals)) | |
| sel[..., :n_full] = part | |
| return sel | |
| # --------------------------------------------------------------------- forward | |
| def forward( | |
| self, x, cache: Optional[Dict] = None, start_pos: int = 0, symplectic_state=None | |
| ): | |
| """x: [B, T, d]. With `cache` (a dict, mutated in place) supports chunked | |
| prefill and decode; `start_pos` is the absolute position of x[:, 0].""" | |
| cfg, H, Hkv, K, dh, C = ( | |
| self.cfg, | |
| self.H, | |
| self.Hkv, | |
| self.K, | |
| self.dh, | |
| self.cfg.tile, | |
| ) | |
| B, T, _ = x.shape | |
| if T < 1 or start_pos < 0: | |
| raise ValueError("Nonempty input and nonnegative start_pos required") | |
| if cache is not None and torch.is_grad_enabled(): | |
| raise ValueError("KV caching is inference-only; use torch.no_grad()") | |
| if cache is None and start_pos != 0: | |
| raise ValueError("A nonzero start_pos requires the prior KV cache") | |
| if cache is not None and "k" not in cache and start_pos != 0: | |
| raise ValueError("An empty cache must begin at position zero") | |
| q_raw = self.q_proj(x).view(B, T, H, dh).transpose(1, 2) | |
| k_raw = self.k_proj(x).view(B, T, Hkv, dh).transpose(1, 2) | |
| v = self.v_proj(x).view(B, T, Hkv, dh).transpose(1, 2) | |
| clock_stats = {} | |
| if isinstance(self.pos, WarpedRoPE): | |
| t0 = ( | |
| cache["clock"][:, -1] | |
| if (cache is not None and "clock" in cache) | |
| else None | |
| ) | |
| times, clock = self.pos.clock(x, t0) # [B, T, Hkv] | |
| rates = (clock - times).detach() | |
| clock_stats = { | |
| "clock_rate_mean": rates.mean(), | |
| "clock_rate_min": rates.amin(), | |
| "clock_rate_max": rates.amax(), | |
| } | |
| if cache is not None: | |
| cache["clock"] = ( | |
| torch.cat([cache["clock"], clock], 1) if "clock" in cache else clock | |
| ) | |
| times = times.transpose(1, 2) # [B, Hkv, T] | |
| q = self.pos.rotate(q_raw, times.repeat_interleave(H // Hkv, dim=1)) | |
| k = self.pos.rotate(k_raw, times) | |
| else: | |
| # Compute the positional transform once for the shared Q/K position range. | |
| qk = self.pos( | |
| torch.cat((q_raw, k_raw), dim=1), | |
| start_pos=start_pos, | |
| symplectic_state=symplectic_state, | |
| ) | |
| q, k = qk.split((H, Hkv), dim=1) | |
| # 1) write sequence memory before any routing decision | |
| k_raw_all = k_raw | |
| if cache is not None: | |
| if "k" in cache: | |
| assert ( | |
| cache["k"].shape[2] == start_pos | |
| ), "cache length must equal start_pos" | |
| k = torch.cat([cache["k"], k], 2) | |
| v = torch.cat([cache["v"], v], 2) | |
| if self.graph: | |
| k_raw_all = torch.cat([cache["k_raw"], k_raw], 2) | |
| cache["k"], cache["v"] = k, v | |
| if self.graph: | |
| cache["k_raw"] = k_raw_all | |
| # 2) causal tile routing: route every tile whose FIRST token lies in this chunk | |
| first_tile, last_tile = start_pos // C, (start_pos + T - 1) // C | |
| n_known = cache["w"].shape[1] if (cache is not None and "w" in cache) else 0 | |
| new_tiles = torch.arange(n_known, last_tile + 1, device=x.device) | |
| offsets = new_tiles * C - start_pos | |
| if n_known <= last_tile and n_known * C < start_pos: | |
| raise ValueError("A tile first token was skipped; routes out of sync") | |
| aux = dict(clock_stats) | |
| sel_new = None | |
| if len(new_tiles): | |
| P_new, w_new, idx_new = self._route(x[:, offsets]) | |
| loss, f, ent = self._balance(P_new, idx_new) | |
| aux.update(balance_loss=loss, mech_freq=f, router_entropy=ent) | |
| with torch.no_grad(): | |
| selected = F.one_hot(idx_new, self.M).float() | |
| selected_weight = torch.zeros_like(P_new).scatter_add_( | |
| -1, idx_new, w_new | |
| ) | |
| aux.update( | |
| query_tile_indices=new_tiles.detach(), | |
| mech_frequency_by_query_tile=selected.mean(dim=(0, 2, 3)), | |
| mech_probability_by_query_tile=P_new.detach().mean(dim=(0, 2)), | |
| mech_selected_weight_by_query_tile=selected_weight.mean(dim=(0, 2)), | |
| ) | |
| if self.graph: | |
| sel_new = self._select_tiles(q_raw[:, :, offsets], k_raw_all, new_tiles) | |
| else: | |
| w_new = x.new_zeros(B, 0, H, K, dtype=torch.float32) | |
| idx_new = torch.zeros(B, 0, H, K, dtype=torch.long, device=x.device) | |
| if self.graph and sel_new is None: | |
| sel_new = torch.zeros( | |
| B, 0, H, self.n_max, dtype=torch.bool, device=x.device | |
| ) | |
| if cache is not None and n_known: | |
| w_all = torch.cat([cache["w"], w_new], 1) | |
| idx_all = torch.cat([cache["idx"], idx_new], 1) | |
| sel_all = torch.cat([cache["sel"], sel_new], 1) if self.graph else None | |
| else: | |
| w_all, idx_all, sel_all = w_new, idx_new, sel_new | |
| if cache is not None: | |
| cache["w"], cache["idx"] = w_all.detach(), idx_all | |
| if self.graph: | |
| cache["sel"] = sel_all | |
| # slot s = h*K + j (maps to kv head s // (H*K/Hkv) == h // (H/Hkv)) | |
| w_t = w_all[:, first_tile : last_tile + 1] # [B, n, H, K] | |
| i_t = idx_all[:, first_tile : last_tile + 1] | |
| n = w_t.shape[1] | |
| mech = i_t.permute(0, 2, 3, 1).reshape(B, H * K, n) # [B, HK, n] | |
| wslot = w_t.permute(0, 2, 3, 1).reshape(B, H * K, n) | |
| picked_slots = None | |
| if self.graph: # [B, HK, n, n_max] | |
| picked_slots = ( | |
| sel_all[:, first_tile : last_tile + 1] | |
| .permute(0, 2, 1, 3) | |
| .repeat_interleave(K, dim=1) | |
| ) | |
| q_slots = q.repeat_interleave(K, dim=1) # [B, HK, T, dh] | |
| q_pos = torch.arange(start_pos, start_pos + T, device=x.device) | |
| q_tile = q_pos // C - first_tile # [T] | |
| if cfg.backend == "flex" and not HAS_FLEX: | |
| raise RuntimeError( | |
| "FlexAttention unavailable; install compatible torch or explicitly select dense" | |
| ) | |
| use_flex = ( | |
| cfg.backend == "flex" | |
| and (x.is_cuda or self._force_flex) | |
| and cache is None | |
| and start_pos == 0 | |
| ) | |
| if use_flex: | |
| n_max = self.n_max | |
| if picked_slots is not None: | |
| def mask_mod(b, h, q_idx, kv_idx): | |
| qt = (q_idx // C).clamp(max=n - 1) | |
| picked = picked_slots[b, h, qt, (kv_idx // C).clamp(max=n_max - 1)] | |
| return ( | |
| (q_idx < T) | |
| & (kv_idx < T) | |
| & geometry_allows(mech[b, h, qt], q_idx, kv_idx, cfg, picked) | |
| ) | |
| else: | |
| def mask_mod(b, h, q_idx, kv_idx): | |
| return ( | |
| (q_idx < T) | |
| & (kv_idx < T) | |
| & geometry_allows( | |
| mech[b, h, (q_idx // C).clamp(max=n - 1)], | |
| q_idx, | |
| kv_idx, | |
| cfg, | |
| ) | |
| ) | |
| if C == 128: | |
| bm = geometry_block_mask( | |
| mech, | |
| T, | |
| cfg, | |
| mask_mod, | |
| None if picked_slots is None else picked_slots[..., :n], | |
| ) | |
| else: | |
| bm = create_block_mask( | |
| mask_mod, | |
| B, | |
| H * K, | |
| T, | |
| T, | |
| device=x.device, | |
| BLOCK_SIZE=C, | |
| _compile=x.is_cuda, | |
| ) | |
| out = _run_flex(q_slots, k, v, bm) | |
| else: | |
| S = k.shape[2] | |
| kv_pos = torch.arange(S, device=x.device) | |
| m = mech[:, :, q_tile] # [B, HK, T] | |
| picked = None | |
| if picked_slots is not None: | |
| picked = picked_slots[:, :, q_tile][..., kv_pos // C] # [B, HK, T, S] | |
| allow = geometry_allows( | |
| m[..., None], | |
| q_pos[None, None, :, None], | |
| kv_pos[None, None, None, :], | |
| cfg, | |
| picked, | |
| ) # [B, HK, T, S] | |
| out = F.scaled_dot_product_attention( | |
| q_slots, k, v, attn_mask=allow, enable_gqa=True | |
| ) | |
| # 3) merge: o_h = sum_j P_{h,m_j} * A_{m_j} | |
| out = out * wslot[:, :, q_tile, None].to(out.dtype) | |
| out = out.view(B, H, K, T, dh).sum(2).transpose(1, 2).reshape(B, T, H * dh) | |
| return self.o_proj(out), aux | |
| # ============================================================================= | |
| # Grouped GEMM acceleration | |
| # ============================================================================= | |
| # Ampere-compatible dropless grouped GEMM with explicit autograd. | |
| # | |
| # No Hopper TMA instructions, token dropping, padding capacity, or CPU count reads. | |
| # A is [sum(tokens), K], W is [experts,K,N], offsets are cumulative token counts. | |
| # Persistent forward/input-gradient kernels use tensor-core dot products; each | |
| # weight-gradient tile has a unique writer and accumulates in FP32. | |
| if HAS_TRITON: | |
| def _grouped_forward( | |
| A, | |
| W, | |
| O, | |
| Y, | |
| K: tl.constexpr, | |
| N: tl.constexpr, | |
| AS0: tl.constexpr, | |
| AS1: tl.constexpr, | |
| WS0: tl.constexpr, | |
| WS1: tl.constexpr, | |
| WS2: tl.constexpr, | |
| E: tl.constexpr, | |
| GRID: tl.constexpr, | |
| BM: tl.constexpr = 32, | |
| BN: tl.constexpr = 64, | |
| BK: tl.constexpr = 32, | |
| ): | |
| tile_id = tl.program_id(0) | |
| prior_tiles = 0 | |
| start = 0 | |
| for expert in range(E): | |
| end = tl.load(O + expert) | |
| count = end - start | |
| nt = tl.cdiv(N, BN) | |
| tiles = tl.cdiv(count, BM) * nt | |
| while tile_id >= prior_tiles and tile_id < prior_tiles + tiles: | |
| local = tile_id - prior_tiles | |
| mi = (local // nt) * BM + tl.arange(0, BM) | |
| ni = (local % nt) * BN + tl.arange(0, BN) | |
| ki = tl.arange(0, BK) | |
| acc = tl.zeros((BM, BN), tl.float32) | |
| for kk in range(tl.cdiv(K, BK)): | |
| kval = kk * BK + ki | |
| av = tl.load( | |
| A + (start + mi[:, None]) * AS0 + kval[None, :] * AS1, | |
| (mi[:, None] < count) & (kval[None, :] < K), | |
| other=0, | |
| ) | |
| wv = tl.load( | |
| W + expert * WS0 + kval[:, None] * WS1 + ni[None, :] * WS2, | |
| (kval[:, None] < K) & (ni[None, :] < N), | |
| other=0, | |
| ) | |
| acc += tl.dot(av, wv) | |
| tl.store( | |
| Y + (start + mi[:, None]) * N + ni[None, :], | |
| acc, | |
| (mi[:, None] < count) & (ni[None, :] < N), | |
| ) | |
| tile_id += GRID | |
| prior_tiles += tiles | |
| start = end | |
| def _grouped_weight_grad( | |
| A, | |
| DY, | |
| O, | |
| DW, | |
| K: tl.constexpr, | |
| N: tl.constexpr, | |
| AS0: tl.constexpr, | |
| AS1: tl.constexpr, | |
| DS0: tl.constexpr, | |
| DS1: tl.constexpr, | |
| BM: tl.constexpr = 32, | |
| BN: tl.constexpr = 64, | |
| BT: tl.constexpr = 32, | |
| ): | |
| expert = tl.program_id(0) | |
| ki = tl.program_id(1) * BM + tl.arange(0, BM) | |
| ni = tl.program_id(2) * BN + tl.arange(0, BN) | |
| end = tl.load(O + expert) | |
| start = 0 | |
| if expert > 0: | |
| start = tl.load(O + expert - 1) | |
| ti = tl.arange(0, BT) | |
| acc = tl.zeros((BM, BN), tl.float32) | |
| for block in range(tl.cdiv(end - start, BT)): | |
| token = start + block * BT + ti | |
| av = tl.load( | |
| A + token[None, :] * AS0 + ki[:, None] * AS1, | |
| (token[None, :] < end) & (ki[:, None] < K), | |
| other=0, | |
| ) | |
| dy = tl.load( | |
| DY + token[:, None] * DS0 + ni[None, :] * DS1, | |
| (token[:, None] < end) & (ni[None, :] < N), | |
| other=0, | |
| ) | |
| acc += tl.dot(av, dy) | |
| tl.store( | |
| DW + expert * K * N + ki[:, None] * N + ni[None, :], | |
| acc, | |
| (ki[:, None] < K) & (ni[None, :] < N), | |
| ) | |
| def _forward(a, w, offsets): | |
| if not HAS_TRITON or not a.is_cuda: | |
| raise RuntimeError("Ampere grouped GEMM requires CUDA and Triton") | |
| if a.dtype not in (torch.bfloat16, torch.float16) or w.dtype != a.dtype: | |
| raise ValueError("Grouped GEMM expects matching BF16/FP16 operands") | |
| if ( | |
| a.ndim != 2 | |
| or w.ndim != 3 | |
| or a.shape[1] != w.shape[1] | |
| or offsets.numel() != w.shape[0] | |
| ): | |
| raise ValueError("Grouped GEMM shape mismatch") | |
| out = torch.empty((a.shape[0], w.shape[2]), device=a.device, dtype=a.dtype) | |
| grid = torch.cuda.get_device_properties(a.device).multi_processor_count | |
| with torch.cuda.device(a.device): | |
| _grouped_forward[(grid,)]( | |
| a, | |
| w, | |
| offsets, | |
| out, | |
| a.shape[1], | |
| w.shape[2], | |
| *a.stride(), | |
| *w.stride(), | |
| w.shape[0], | |
| grid, | |
| num_warps=4, | |
| num_stages=3, | |
| ) | |
| return out | |
| class _GroupedGEMM(torch.autograd.Function): | |
| def forward(ctx, a, w, offsets): | |
| ctx.save_for_backward(a, w, offsets) | |
| return _forward(a, w, offsets) | |
| def backward(ctx, grad): | |
| a, w, offsets = ctx.saved_tensors | |
| da = ( | |
| _forward(grad, w.transpose(-1, -2), offsets) | |
| if ctx.needs_input_grad[0] | |
| else None | |
| ) | |
| dw = None | |
| if ctx.needs_input_grad[1]: | |
| dw = torch.empty(w.shape, device=w.device, dtype=w.dtype) | |
| grid = ( | |
| w.shape[0], | |
| triton.cdiv(w.shape[1], 32), | |
| triton.cdiv(w.shape[2], 64), | |
| ) | |
| with torch.cuda.device(a.device): | |
| _grouped_weight_grad[grid]( | |
| a, | |
| grad, | |
| offsets, | |
| dw, | |
| w.shape[1], | |
| w.shape[2], | |
| *a.stride(), | |
| *grad.stride(), | |
| num_warps=4, | |
| num_stages=3, | |
| ) | |
| return da, dw, None | |
| def ampere_grouped_mm(a, w, offsets): | |
| return _GroupedGEMM.apply(a, w, offsets) | |
| def grouped_mm(a, b, offsets): | |
| return ampere_grouped_mm(a, b, offsets) | |
| # ============================================================================= | |
| # Model building blocks | |
| # ============================================================================= | |
| class RMSNorm(nn.Module): | |
| def __init__(self, dim): | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(dim)) | |
| def forward(self, x): | |
| return ( | |
| x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6) | |
| ).to(x.dtype) * self.weight | |
| class DepthAttention(nn.Module): | |
| """Bank entries [B,T,H,d] preserve token index exactly; never reduce over T. | |
| Keep the input embedding plus the most recent layer states. Keys and values | |
| are projected once when written, with autograd retained through the bank. | |
| """ | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.heads = cfg.depth_heads | |
| self.dim = cfg.depth_dim | |
| self.q_proj = nn.Linear(cfg.embed_dim, cfg.depth_dim, bias=False) | |
| self.out_proj = nn.Linear(cfg.depth_dim, cfg.embed_dim, bias=False) | |
| self.gate = nn.Parameter(torch.tensor(cfg.depth_gate_init)) | |
| def forward(self, x, bank): | |
| b, t, _ = x.shape | |
| q = self.q_proj(x).view(b, t, self.heads, self.dim // self.heads) | |
| keys = torch.stack([kv[0] for kv in bank], dim=-2) | |
| vals = torch.stack([kv[1] for kv in bank], dim=-2) | |
| scores = (q.unsqueeze(-2).float() * keys.float()).sum(-1) / math.sqrt( | |
| q.shape[-1] | |
| ) | |
| weights = scores.softmax(-1).to(vals.dtype) | |
| y = (weights.unsqueeze(-1) * vals).sum(-2).reshape(b, t, self.dim) | |
| return self.gate.tanh() * self.out_proj(y) | |
| class FoldUnfoldReasoning(nn.Module): | |
| """Prefix-specific full-width slots, shared refinement, and residual readout. | |
| Each token owns its workspace; slots never mix across token positions. Fold | |
| and, by default, every refinement step read the full causal token bank. | |
| Experimental local_only refinement omits revisits but retains slot operations. | |
| A separate direct token read bypasses the slots. Query chunking bounds temporary activations, | |
| not context or information access. Only immutable prefix K/V are cached; | |
| slots are recomputed for new queries, so chunked decoding has the same graph | |
| as a full forward. No extra token positions are consumed by latent steps. | |
| """ | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.width, self.heads = cfg.embed_dim, cfg.reasoning_heads | |
| self.slots, self.steps = cfg.reasoning_slots, cfg.reasoning_steps | |
| self.chunk_size = cfg.reasoning_chunk_size | |
| self.initial_fold = cfg.reasoning_initial_fold | |
| self.direct_read = cfg.reasoning_direct_read | |
| self.revisit_mode = cfg.reasoning_revisit_mode | |
| self.position_bias = ( | |
| RelativePositionBias(self.heads) | |
| if cfg.reasoning_position_bias == "relative" | |
| else ( | |
| ContinuousPositionBias(32, self.heads) | |
| if cfg.reasoning_position_bias == "continuous" | |
| else None | |
| ) | |
| ) | |
| self.slot_seed = nn.Parameter(torch.randn(self.slots, self.width) * 0.02) | |
| self.context_norm = RMSNorm(self.width) | |
| self.slot_norm = RMSNorm(self.width) | |
| self.ff_norm = RMSNorm(self.width) | |
| self.context_kv = nn.Linear(self.width, 2 * self.width, bias=False) | |
| self.fold_q = nn.Linear(self.width, self.width, bias=False) | |
| self.fold_out = nn.Linear(self.width, self.width, bias=False) | |
| self.revisit_q = nn.Linear(self.width, self.width, bias=False) | |
| self.revisit_out = nn.Linear(self.width, self.width, bias=False) | |
| self.slot_qkv = nn.Linear(self.width, 3 * self.width, bias=False) | |
| self.slot_out = nn.Linear(self.width, self.width, bias=False) | |
| self.ff_up = nn.Linear(self.width, 4 * self.width, bias=False) | |
| self.ff_down = nn.Linear(2 * self.width, self.width, bias=False) | |
| self.unfold_q = nn.Linear(self.width, self.width, bias=False) | |
| self.unfold_kv = nn.Linear(self.width, 2 * self.width, bias=False) | |
| self.unfold_out = nn.Linear(self.width, self.width, bias=False) | |
| self.direct_q = nn.Linear(self.width, self.width, bias=False) | |
| self.direct_out = nn.Linear(self.width, self.width, bias=False) | |
| self.unfold_gate = nn.Parameter(torch.tensor(float(cfg.reasoning_gate_init))) | |
| self.direct_gate = nn.Parameter(torch.tensor(float(cfg.reasoning_gate_init))) | |
| def _heads(self, x): | |
| return x.unflatten(-1, (self.heads, self.width // self.heads)).transpose(-3, -2) | |
| def _merge(self, x): | |
| return x.transpose(-3, -2).flatten(-2) | |
| def _chunk(self, x, k, v, start_pos, steps): | |
| b, t, d = x.shape | |
| seed = self.context_norm(x) | |
| z = seed[:, :, None, :] + self.slot_seed[None, None] | |
| # A query's slots share exactly that query's causal prefix. | |
| allow = ( | |
| torch.arange(k.shape[2], device=x.device)[None, :] | |
| <= (start_pos + torch.arange(t, device=x.device))[:, None] | |
| ) | |
| direct_mask = allow[None, None] | |
| if self.position_bias is not None: | |
| # Explicit causality is retained after adding learned score biases. | |
| direct_mask = self.position_bias(t, k.shape[2], start_pos).to(k.dtype) | |
| direct_mask = direct_mask.masked_fill(~allow[None, None], float("-inf")) | |
| slot_mask = direct_mask.repeat_interleave(self.slots, dim=-2) | |
| def read_slots(query): | |
| q = self._heads(query.reshape(b, t * self.slots, d)) | |
| return self._merge( | |
| F.scaled_dot_product_attention(q, k, v, attn_mask=slot_mask) | |
| ).reshape(b, t, self.slots, d) | |
| if self.initial_fold: | |
| z = z + self.fold_out(read_slots(self.fold_q(self.slot_norm(z)))) | |
| initial = z | |
| for _ in range(steps): | |
| if self.revisit_mode == "full": | |
| z = z + self.revisit_out(read_slots(self.revisit_q(self.slot_norm(z)))) | |
| q, sk, sv = self.slot_qkv(self.slot_norm(z)).chunk(3, dim=-1) | |
| # [B,T,H,slots,head_dim]: no attention between different prefixes. | |
| z = z + self.slot_out( | |
| self._merge( | |
| F.scaled_dot_product_attention( | |
| self._heads(q), self._heads(sk), self._heads(sv) | |
| ) | |
| ) | |
| ) | |
| gate, value = self.ff_up(self.ff_norm(z)).chunk(2, dim=-1) | |
| z = z + self.ff_down(F.silu(gate) * value) | |
| uk, uv = self.unfold_kv(self.slot_norm(z)).chunk(2, dim=-1) | |
| uq = self._heads(self.unfold_q(seed)[:, :, None, :]) | |
| unfolded = self._merge( | |
| F.scaled_dot_product_attention(uq, self._heads(uk), self._heads(uv)) | |
| ).squeeze(-2) | |
| delta = self.unfold_gate.tanh() * self.unfold_out(unfolded) | |
| if self.direct_read: | |
| direct = self._merge( | |
| F.scaled_dot_product_attention( | |
| self._heads(self.direct_q(seed)), k, v, attn_mask=direct_mask | |
| ) | |
| ) | |
| delta = delta + self.direct_gate.tanh() * self.direct_out(direct) | |
| # Detached sums allow correct aggregation across execution chunks. | |
| stats = torch.stack( | |
| ( | |
| (z - initial).detach().float().square().sum(), | |
| delta.detach().float().square().sum(), | |
| x.detach().float().square().sum(), | |
| ) | |
| ) | |
| return x + delta, stats | |
| def forward(self, x, cache=None, start_pos=0, steps=None): | |
| steps = self.steps if steps is None else steps | |
| if not isinstance(steps, int) or isinstance(steps, bool) or steps < 1: | |
| raise ValueError("reasoning_steps must be a positive integer") | |
| k, v = self.context_kv(self.context_norm(x)).chunk(2, dim=-1) | |
| k, v = self._heads(k), self._heads(v) | |
| if cache is not None: | |
| if "reasoning_k" in cache: | |
| k = torch.cat((cache["reasoning_k"], k), dim=2) | |
| v = torch.cat((cache["reasoning_v"], v), dim=2) | |
| cache["reasoning_k"], cache["reasoning_v"] = k, v | |
| chunks, stats = [], [] | |
| for offset in range(0, x.shape[1], self.chunk_size): | |
| query = x[:, offset : offset + self.chunk_size] | |
| if torch.is_grad_enabled(): | |
| from torch.utils.checkpoint import checkpoint | |
| out, info = checkpoint( | |
| self._chunk, | |
| query, | |
| k, | |
| v, | |
| start_pos + offset, | |
| steps, | |
| use_reentrant=False, | |
| ) | |
| else: | |
| out, info = self._chunk(query, k, v, start_pos + offset, steps) | |
| chunks.append(out) | |
| stats.append(info) | |
| sums = torch.stack(stats).sum(0) | |
| return torch.cat(chunks, dim=1), { | |
| "steps": steps, | |
| "slots": self.slots, | |
| "refinement_delta_rms": (sums[0] / (x.numel() * self.slots)).sqrt(), | |
| "output_delta_rms": (sums[1] / x.numel()).sqrt(), | |
| "input_rms": (sums[2] / x.numel()).sqrt(), | |
| } | |
| class DroplessMoE(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.cfg = cfg | |
| self.router = nn.Linear(cfg.embed_dim, cfg.num_experts, bias=False) | |
| # Flat [expert * bank + bank_id] storage keeps grouped GEMM unchanged. | |
| self.bank_router = ( | |
| nn.Parameter(torch.empty(cfg.num_experts, cfg.embed_dim, cfg.expert_banks)) | |
| if cfg.expert_banks > 1 | |
| else None | |
| ) | |
| if self.bank_router is not None: | |
| nn.init.normal_(self.bank_router, std=0.02) | |
| self.up = nn.Parameter( | |
| torch.empty( | |
| cfg.num_experts * cfg.expert_banks, | |
| cfg.embed_dim, | |
| cfg.expert_hidden_dim * 2, | |
| ) | |
| ) | |
| self.down = nn.Parameter( | |
| torch.empty( | |
| cfg.num_experts * cfg.expert_banks, cfg.expert_hidden_dim, cfg.embed_dim | |
| ) | |
| ) | |
| nn.init.normal_(self.up, std=0.02) | |
| nn.init.normal_(self.down, std=0.02 / math.sqrt(2 * cfg.num_layers)) | |
| def forward(self, x): | |
| cfg = self.cfg | |
| if ( | |
| self.training | |
| and torch.is_grad_enabled() | |
| and cfg.expert_top_k == 1 | |
| and cfg.num_experts > 1 | |
| ): | |
| raise ValueError( | |
| "Training with expert_top_k=1 removes the task gradient through " | |
| "normalized expert weights. Use top-2 or more; top-1 inference remains supported." | |
| ) | |
| flat = x.reshape(-1, x.shape[-1]) | |
| expert_logits = router_logits_fp32(self.router, flat) | |
| prob = expert_logits.softmax(-1) | |
| z_loss = ( | |
| cfg.router_z_loss_coef * expert_logits.logsumexp(-1).square().mean() | |
| if cfg.router_z_loss_coef | |
| else expert_logits.new_zeros(()) | |
| ) | |
| weights, experts = prob.topk(cfg.expert_top_k, -1) | |
| weights = weights / weights.sum(-1, keepdim=True) | |
| if cfg.expert_banks > 1: | |
| mixed, balance, stats = self._bank_forward(x, flat, prob, weights, experts) | |
| z_loss = z_loss + stats["router_z_loss"] | |
| stats["router_z_loss"] = z_loss.detach() | |
| stats["expert_router_entropy"] = ( | |
| -(prob.detach() * prob.detach().clamp_min(1e-9).log()).sum(-1).mean() | |
| ) | |
| return mixed, balance + z_loss, stats | |
| order = experts.flatten().argsort(stable=True) | |
| token_ids = order // cfg.expert_top_k | |
| dispatched = flat[token_ids] | |
| counts = torch.zeros(cfg.num_experts, device=x.device, dtype=torch.int32) | |
| counts.scatter_add_( | |
| 0, experts.flatten(), torch.ones_like(experts.flatten(), dtype=torch.int32) | |
| ) | |
| if cfg.expert_backend == "grouped" and x.is_cuda: | |
| # Explicit casts are differentiable and avoid ambiguous autocast support. | |
| offsets = counts.cumsum(0, dtype=torch.int32) | |
| h = grouped_mm( | |
| dispatched.to(torch.bfloat16), self.up.to(torch.bfloat16), offsets | |
| ) | |
| gate, value = h.chunk(2, -1) | |
| h = (F.silu(gate) * value).contiguous() | |
| result = grouped_mm(h, self.down.to(torch.bfloat16), offsets) | |
| else: | |
| # One synchronization for all counts, instead of nonzero()+sync per expert. | |
| sizes = counts.cpu().tolist() | |
| chunks = dispatched.split(sizes, 0) | |
| # Empty assignments do not execute an FFN; indexed parameter grads | |
| # still scatter zeros to unselected expert slices. | |
| result = torch.cat( | |
| [ | |
| self._expert(chunk, i) | |
| for i, chunk in enumerate(chunks) | |
| if chunk.shape[0] | |
| ], | |
| 0, | |
| ) | |
| # Autocast produces BF16 expert outputs while the residual may be FP32. | |
| # Both backends must mix in the residual dtype; index_add does not promote. | |
| result = result.to(flat.dtype) | |
| weighted = result * weights.flatten()[order, None].to(result.dtype) | |
| mixed = torch.zeros_like(flat).index_add(0, token_ids, weighted) | |
| frequency = counts.float() / experts.numel() | |
| balance = cfg.balance_coef * cfg.num_experts * (frequency * prob.mean(0)).sum() | |
| return ( | |
| mixed.view_as(x), | |
| balance + z_loss, | |
| { | |
| "expert_frequency": frequency.detach(), | |
| "router_z_loss": z_loss.detach(), | |
| "expert_router_entropy": -( | |
| prob.detach() * prob.detach().clamp_min(1e-9).log() | |
| ) | |
| .sum(-1) | |
| .mean(), | |
| }, | |
| ) | |
| def _expert(self, x, i): | |
| gate, value = (x @ self.up[i]).chunk(2, -1) | |
| return (F.silu(gate) * value) @ self.down[i] | |
| def _bank_forward(self, x, flat, prob, weights, experts): | |
| cfg = self.cfg | |
| # Compute tiny router logits, not unselected FFN banks. Avoid gathering | |
| # a [tokens,chosen_experts,width,banks] copy of router parameters. | |
| with torch.autocast(device_type=x.device.type, enabled=False): | |
| logits = torch.einsum("nd,edp->nep", flat.float(), self.bank_router.float()) | |
| selected_logits = logits.gather( | |
| 1, experts[..., None].expand(-1, -1, cfg.expert_banks) | |
| ) | |
| bank_prob = selected_logits.softmax(-1) | |
| bank_weights, banks = bank_prob.topk(cfg.expert_bank_top_k, dim=-1) | |
| # Original mass keeps a task-loss gradient when only one bank is chosen. | |
| # Mean scale is one at a uniform bank router, including top-1. | |
| bank_weights = bank_weights * (cfg.expert_banks / cfg.expert_bank_top_k) | |
| paths = experts[..., None] * cfg.expert_banks + banks | |
| path_weights = weights[..., None] * bank_weights | |
| paths_per_token = cfg.expert_top_k * cfg.expert_bank_top_k | |
| order = paths.flatten().argsort(stable=True) | |
| token_ids = order // paths_per_token | |
| dispatched = flat[token_ids] | |
| count = cfg.num_experts * cfg.expert_banks | |
| counts = torch.zeros(count, device=x.device, dtype=torch.int32) | |
| counts.scatter_add_( | |
| 0, paths.flatten(), torch.ones_like(paths.flatten(), dtype=torch.int32) | |
| ) | |
| if cfg.expert_backend == "grouped" and x.is_cuda: | |
| offsets = counts.cumsum(0, dtype=torch.int32) | |
| h = grouped_mm( | |
| dispatched.to(torch.bfloat16), self.up.to(torch.bfloat16), offsets | |
| ) | |
| gate, value = h.chunk(2, dim=-1) | |
| result = grouped_mm( | |
| (F.silu(gate) * value).contiguous(), | |
| self.down.to(torch.bfloat16), | |
| offsets, | |
| ) | |
| else: | |
| chunks = dispatched.split(counts.cpu().tolist(), dim=0) | |
| # Do not invoke even an empty FFN for an unselected expert-bank. | |
| result = torch.cat( | |
| [ | |
| self._expert(chunk, i) | |
| for i, chunk in enumerate(chunks) | |
| if chunk.shape[0] | |
| ], | |
| dim=0, | |
| ) | |
| weighted = result.to(flat.dtype) * path_weights.flatten()[order, None].to( | |
| flat.dtype | |
| ) | |
| mixed = torch.zeros_like(flat).index_add(0, token_ids, weighted) | |
| frequency = F.one_hot(experts, cfg.num_experts).float().mean(dim=(0, 1)) | |
| balance = cfg.balance_coef * cfg.num_experts * (frequency * prob.mean(0)).sum() | |
| # Conditional bank balance for each expert, weighted by its assignments. | |
| expert_ids = experts.flatten() | |
| bank_sum = bank_prob.new_zeros(cfg.num_experts, cfg.expert_banks).index_add( | |
| 0, expert_ids, bank_prob.flatten(0, 1) | |
| ) | |
| assignments = torch.bincount(expert_ids, minlength=cfg.num_experts).float() | |
| bank_frequency = counts.reshape(cfg.num_experts, cfg.expert_banks).float() | |
| bank_frequency = bank_frequency / ( | |
| assignments[:, None] * cfg.expert_bank_top_k | |
| ).clamp_min(1) | |
| balance = ( | |
| balance | |
| + cfg.balance_coef | |
| * cfg.expert_banks | |
| * (bank_frequency * bank_sum).sum() | |
| / expert_ids.numel() | |
| ) | |
| stats = { | |
| "router_z_loss": ( | |
| cfg.router_z_loss_coef * selected_logits.logsumexp(-1).square().mean() | |
| if cfg.router_z_loss_coef | |
| else selected_logits.new_zeros(()) | |
| ), | |
| "expert_frequency": frequency.detach(), | |
| "expert_bank_frequency": bank_frequency.detach(), | |
| "expert_bank_probability": ( | |
| bank_sum / assignments[:, None].clamp_min(1) | |
| ).detach(), | |
| "expert_bank_selected_mass": bank_prob.topk(cfg.expert_bank_top_k, dim=-1) | |
| .values.sum(-1) | |
| .mean() | |
| .detach(), | |
| } | |
| return mixed.view_as(x), balance, stats | |
| class AttentionBlock(nn.Module): | |
| def __init__(self, cfg): | |
| super().__init__() | |
| self.hnorm, self.dnorm, self.mnorm = (RMSNorm(cfg.embed_dim) for _ in range(3)) | |
| ac = RoutedAttentionConfig( | |
| d_model=cfg.embed_dim, | |
| n_q_heads=cfg.n_q_heads, | |
| n_kv_heads=cfg.n_kv_heads, | |
| top_k=cfg.attention_top_k, | |
| tile=cfg.tile, | |
| local_window=cfg.local_window, | |
| strided_recent=cfg.strided_recent, | |
| strided_every=cfg.strided_every, | |
| graph_top_r=cfg.graph_top_r, | |
| graph_recent=cfg.graph_recent, | |
| max_seq_len=cfg.max_seq_len, | |
| router_init_std=cfg.router_init_std, | |
| balance_coef=cfg.balance_coef, | |
| backend=cfg.attention_backend, | |
| ) | |
| head_dim = cfg.embed_dim // cfg.n_q_heads | |
| if cfg.rope_type == "warped": | |
| pos = WarpedRoPE(cfg.embed_dim, head_dim, cfg.n_q_heads, cfg.n_kv_heads) | |
| elif cfg.rope_type == "blackhole": | |
| pos = BlackHolePos( | |
| BlackHoleRoPE(head_dim, cfg.max_seq_len, discrepancy_modulation=False) | |
| ) | |
| else: | |
| pos = None | |
| self.horizontal = RoutedSequenceAttention(ac, pos) | |
| self.vertical = DepthAttention(cfg) | |
| self.moe = DroplessMoE(cfg) | |
| self.depth_mode = cfg.depth_mode | |
| def forward(self, x, bank, cache=None, start_pos=0): | |
| h, aux = self.horizontal(self.hnorm(x), cache=cache, start_pos=start_pos) | |
| x = x + h | |
| if self.depth_mode == "attention": | |
| x = x + self.vertical(self.dnorm(x), bank) | |
| m, mloss, freq = self.moe(self.mnorm(x)) | |
| if isinstance(freq, dict): | |
| aux.update(freq) | |
| else: | |
| aux["expert_frequency"] = freq | |
| aux["depth_gate"] = self.vertical.gate.detach().tanh() | |
| return x + m, aux.get("balance_loss", x.new_zeros(())) + mloss, aux | |
| # ============================================================================= | |
| # Hugging Face cache and output interfaces | |
| # ============================================================================= | |
| class TAMECache(Cache): | |
| """Per-sequence KV and tile-route state with HF beam and rollback operations. | |
| Physical token count includes padding; each row's rotary position counts only | |
| real tokens. Depth attention is same-token across layers, so its bank is | |
| reconstructed for new tokens and needs no cross-token cache. | |
| """ | |
| def __init__(self, num_layers, tile): | |
| super().__init__(layers=[]) | |
| self.num_layers, self.tile = num_layers, tile | |
| self.rows = [] | |
| self.mask = None | |
| def get_seq_length(self, layer_idx=0): | |
| return 0 if self.mask is None else self.mask.shape[1] | |
| def get_max_cache_shape(self, layer_idx=0): | |
| return -1 | |
| def get_mask_sizes(self, query_length, layer_idx=0): | |
| return self.get_seq_length() + query_length, 0 | |
| def is_compileable(self): | |
| return False | |
| def is_initialized(self): | |
| return bool(self.rows) | |
| def is_sliding(self): | |
| return [False] * self.num_layers | |
| def max_batch_size(self): | |
| return len(self.rows) | |
| def reset(self): | |
| self.rows = [] | |
| self.mask = None | |
| def row_length(self, index): | |
| row = self.rows[index] | |
| return row[0]["k"].shape[2] if row and "k" in row[0] else 0 | |
| def reorder_cache(self, beam_idx): | |
| indices = beam_idx.tolist() | |
| self.rows = [[dict(layer) for layer in self.rows[i]] for i in indices] | |
| if self.mask is not None: | |
| self.mask = self.mask.index_select(0, beam_idx.to(self.mask.device)) | |
| def batch_select_indices(self, indices): | |
| self.reorder_cache(indices) | |
| def batch_repeat_interleave(self, repeats): | |
| if self.mask is not None: | |
| indices = torch.arange( | |
| len(self.rows), device=self.mask.device | |
| ).repeat_interleave(repeats) | |
| self.reorder_cache(indices) | |
| def crop(self, max_length): | |
| seen = self.get_seq_length() | |
| end = max(0, seen + max_length) if max_length < 0 else min(seen, max_length) | |
| if self.mask is None: | |
| return | |
| self.mask = self.mask[:, :end] | |
| for i, row in enumerate(self.rows): | |
| length = int(self.mask[i].sum()) | |
| tiles = (length + self.tile - 1) // self.tile | |
| for layer in row: | |
| if length == 0: | |
| layer.clear() | |
| continue | |
| for key in ("k", "v", "k_raw", "reasoning_k", "reasoning_v"): | |
| if key in layer: | |
| layer[key] = layer[key][:, :, :length] | |
| if "clock" in layer: # [B, S, Hkv] warped time | |
| layer["clock"] = layer["clock"][:, :length] | |
| for key in ("w", "idx", "sel"): # [B, tiles, ...] | |
| if key in layer: | |
| layer[key] = layer[key][:, :tiles] | |
| class TAMEOutput(ModelOutput): | |
| loss: torch.Tensor | None = None | |
| logits: torch.Tensor | None = None | |
| past_key_values: TAMECache | list | None = None | |
| aux_losses: dict | None = None | |
| attention_stats: list | None = None | |
| reasoning_stats: dict | list | None = None | |
| # ============================================================================= | |
| # Complete language model | |
| # ============================================================================= | |
| class TAMELM(PreTrainedModel, GenerationMixin): | |
| config_class = TAMEConfig | |
| base_model_prefix = "tamelm" | |
| _tied_weights_keys = {"lm_head.weight": "token_embedding.weight"} | |
| # Construction and checkpoint compatibility | |
| def _init_weights(self, module): | |
| # Initialization below is the existing TAMELM scheme. HF post_init | |
| # records model metadata but must not draw extra random numbers or | |
| # change the seeded backbone used by the pilot and matched controls. | |
| return | |
| def __init__(self, config): | |
| super().__init__(config) | |
| self.token_embedding = nn.Embedding(config.vocab_size, config.embed_dim) | |
| self.blocks = nn.ModuleList( | |
| [AttentionBlock(config) for _ in range(config.num_layers)] | |
| ) | |
| self.final_norm = RMSNorm(config.embed_dim) | |
| self.depth_norm = RMSNorm(config.embed_dim) | |
| self.depth_kv = nn.Linear(config.embed_dim, 2 * config.depth_dim, bias=False) | |
| self.lm_head = nn.Linear(config.embed_dim, config.vocab_size, bias=False) | |
| self.lm_head.weight = self.token_embedding.weight | |
| self.post_init() | |
| nn.init.normal_(self.token_embedding.weight, std=0.02) | |
| for module in self.modules(): | |
| if isinstance(module, nn.Linear) and module is not self.lm_head: | |
| nn.init.normal_(module.weight, std=0.02) | |
| # HF loads under no_init_weights(); torch.ones there may leave this | |
| # nonpersistent routing mask uninitialized. It is fixed config state. | |
| for block in self.blocks: | |
| block.horizontal.allowed.fill_(True) | |
| if config.init_scheme == "v1": | |
| # The generic Linear loop above overwrites module-specific schemes. | |
| # Restore them so the run config describes the network that trains. | |
| out_std = 0.02 / math.sqrt(2 * config.num_layers) | |
| for block in self.blocks: | |
| nn.init.normal_( | |
| block.horizontal.router.weight, std=config.router_init_std | |
| ) | |
| nn.init.normal_(block.horizontal.o_proj.weight, std=out_std) | |
| nn.init.normal_(block.vertical.out_proj.weight, std=out_std) | |
| for block in self.blocks: | |
| if isinstance(block.horizontal.pos, WarpedRoPE): | |
| block.horizontal.pos.reset_parameters() # exactly standard RoPE at step 0 | |
| # Construct after backbone initialization, preserving legacy seeded weights | |
| # when reasoning is disabled. Old saved configs explicitly resolve to none. | |
| self.reasoning = ( | |
| FoldUnfoldReasoning(config) | |
| if config.reasoning_mode == "fold_unfold" | |
| else None | |
| ) | |
| self.sinusoidal = ( | |
| ScaledSinusoidalEmbedding(config.embed_dim) | |
| if config.add_sinusoidal_embeddings | |
| else None | |
| ) | |
| if self.reasoning is not None: | |
| for module in self.reasoning.modules(): | |
| if isinstance(module, nn.Linear): | |
| nn.init.normal_(module.weight, std=0.02) | |
| self.tokenizer = None | |
| def from_baseline( | |
| cls, baseline, bank_router_noise=1e-4, expansion_seed=0, **capacity_config | |
| ): | |
| """Expand a single-bank checkpoint, preserving its initial function to O(noise). | |
| Replicate expert weights into banks and zero the new reasoning readout gates. | |
| The bank router starts near-uniform, NOT exactly zero: replicated banks with a | |
| zero router are a symmetric fixed point (tied banks get identical gradients | |
| and Adam updates forever, so 4 banks/top-2 trains as 2 banks/top-1). Tiny | |
| seeded noise sends different tokens to different bank pairs; because the | |
| banks are still identical, the output changes only by O(noise). | |
| Train with a fresh optimizer; its moments are not compatible with expanded | |
| tensors. The original model is untouched. Only capacity settings may change. | |
| """ | |
| if not (math.isfinite(bank_router_noise) and bank_router_noise > 0): | |
| raise ValueError( | |
| "bank_router_noise must be positive: zero leaves banks tied" | |
| ) | |
| allowed = { | |
| "reasoning_mode", | |
| "reasoning_slots", | |
| "reasoning_steps", | |
| "reasoning_heads", | |
| "reasoning_chunk_size", | |
| "reasoning_gate_init", | |
| "expert_banks", | |
| "expert_bank_top_k", | |
| } | |
| if set(capacity_config) - allowed: | |
| raise ValueError( | |
| "from_baseline accepts only reasoning and bank capacity settings" | |
| ) | |
| if ( | |
| getattr(baseline.config, "expert_banks", 1) != 1 | |
| or getattr(baseline, "reasoning", None) is not None | |
| ): | |
| raise ValueError( | |
| "from_baseline requires a single-bank model without reasoning" | |
| ) | |
| values = baseline.config.to_dict() | |
| values.update(reasoning_mode="fold_unfold", expert_banks=4, expert_bank_top_k=2) | |
| values.update(capacity_config) | |
| config = TAMEConfig.from_dict(values) | |
| # New modules (reasoning) are drawn from a fixed seed, so the expansion is a | |
| # pure function of (baseline, config, expansion_seed) and the caller's RNG is untouched. | |
| with torch.random.fork_rng(devices=[]): | |
| torch.random.default_generator.manual_seed(expansion_seed) | |
| target = cls(config) | |
| target = target.to( | |
| device=baseline.token_embedding.weight.device, | |
| dtype=baseline.token_embedding.weight.dtype, | |
| ) | |
| source = baseline.state_dict() | |
| target_state = target.state_dict() | |
| with torch.no_grad(): | |
| for name, value in source.items(): | |
| if name.endswith((".moe.up", ".moe.down")): | |
| value = value.repeat_interleave(config.expert_banks, dim=0) | |
| target_state[name].copy_(value) | |
| generator = torch.Generator(device="cpu").manual_seed(expansion_seed) | |
| for block in target.blocks: | |
| if block.moe.bank_router is not None: | |
| noise = torch.randn( | |
| block.moe.bank_router.shape, generator=generator | |
| ) | |
| block.moe.bank_router.copy_(noise * bank_router_noise) | |
| if target.reasoning is not None: | |
| target.reasoning.unfold_gate.zero_() | |
| target.reasoning.direct_gate.zero_() | |
| target.tokenizer = baseline.tokenizer | |
| import copy | |
| target.generation_config = copy.deepcopy(baseline.generation_config) | |
| return target.train(baseline.training) | |
| # Embedding and tokenizer interfaces | |
| def get_input_embeddings(self): | |
| return self.token_embedding | |
| def load_state_dict(self, state_dict, strict=True, assign=False): | |
| # Pilot checkpoints predate serialization of this fixed routing mask. | |
| # Fill only missing masks; leave every learned tensor untouched. | |
| missing = [ | |
| f"blocks.{i}.horizontal.allowed" | |
| for i in range(len(self.blocks)) | |
| if f"blocks.{i}.horizontal.allowed" not in state_dict | |
| ] | |
| if missing: | |
| state_dict = dict(state_dict) | |
| for key in missing: | |
| state_dict[key] = torch.ones_like(self.get_buffer(key)) | |
| return super().load_state_dict(state_dict, strict=strict, assign=assign) | |
| def set_input_embeddings(self, value): | |
| self.token_embedding = value | |
| self.lm_head.weight = value.weight | |
| def get_output_embeddings(self): | |
| return self.lm_head | |
| def set_output_embeddings(self, value): | |
| self.lm_head = value | |
| self.token_embedding.weight = value.weight | |
| def attach_tokenizer(self, tokenizer): | |
| import hashlib | |
| import json | |
| if len(tokenizer) != self.config.vocab_size: | |
| raise ValueError("Tokenizer vocabulary does not match model") | |
| for name in ("pad", "bos", "eos"): | |
| if getattr(tokenizer, name + "_token_id") != getattr( | |
| self.config, name + "_token_id" | |
| ): | |
| raise ValueError(f"Tokenizer {name} ID does not match model") | |
| backend = json.loads(tokenizer.backend_tokenizer.to_str()) | |
| backend.pop("truncation", None) | |
| backend.pop("padding", None) | |
| identity = { | |
| "backend": backend, | |
| "special_ids": { | |
| name: getattr(tokenizer, name + "_token_id") | |
| for name in ("pad", "bos", "eos") | |
| }, | |
| } | |
| digest = hashlib.sha256( | |
| json.dumps(identity, sort_keys=True, separators=(",", ":")).encode() | |
| ).hexdigest() | |
| if getattr(self.config, "tokenizer_sha256", digest) != digest: | |
| raise ValueError( | |
| "Tokenizer identity differs from the checkpoint vocabulary/policy" | |
| ) | |
| self.config.tokenizer_sha256 = digest | |
| self.tokenizer = tokenizer | |
| # Depth state and packed forward path | |
| def _write_depth(self, x): | |
| b, t, _ = x.shape | |
| k, v = self.depth_kv(self.depth_norm(x)).chunk(2, -1) | |
| shape = ( | |
| b, | |
| t, | |
| self.config.depth_heads, | |
| self.config.depth_dim // self.config.depth_heads, | |
| ) | |
| return k.reshape(shape), v.reshape(shape) | |
| def _forward_unpadded( | |
| self, | |
| input_ids, | |
| labels=None, | |
| attention_mask=None, | |
| use_cache=False, | |
| past_key_values=None, | |
| start_pos=0, | |
| return_logits=None, | |
| reasoning_steps=None, | |
| logit_positions=None, | |
| **kwargs, | |
| ): | |
| if ( | |
| input_ids.ndim != 2 | |
| or not 0 < input_ids.shape[1] <= self.config.max_seq_len - start_pos | |
| ): | |
| raise ValueError("Input must be [batch, tokens] within max_seq_len") | |
| # Packed training has no padding. Do not accept a mask and silently ignore it. | |
| if attention_mask is not None: | |
| raise ValueError( | |
| "Use packed unpadded input_ids; padding masks are not supported" | |
| ) | |
| if (use_cache or past_key_values is not None) and ( | |
| labels is not None or torch.is_grad_enabled() | |
| ): | |
| raise ValueError( | |
| "KV cache requires inference without labels under torch.no_grad()" | |
| ) | |
| caches = ( | |
| past_key_values | |
| if past_key_values is not None | |
| else ([{} for _ in self.blocks] if use_cache else None) | |
| ) | |
| if caches is not None and len(caches) != len(self.blocks): | |
| raise ValueError("One cache per layer required") | |
| x = self.token_embedding(input_ids) | |
| if self.sinusoidal is not None: | |
| x = x + self.sinusoidal(x, start_pos=start_pos) | |
| bank = [self._write_depth(x)] if self.config.depth_mode == "attention" else [] | |
| losses, stats = [], [] | |
| for i, block in enumerate(self.blocks): | |
| if ( | |
| self.config.checkpoint_backbone | |
| and self.training | |
| and torch.is_grad_enabled() | |
| ): | |
| from torch.utils.checkpoint import checkpoint | |
| # Freeze bank membership: later layer writes must not change the | |
| # inputs replayed during backward. Tensor gradients stay intact. | |
| x, loss, info = checkpoint(block, x, tuple(bank), use_reentrant=False) | |
| else: | |
| x, loss, info = block( | |
| x, bank, None if caches is None else caches[i], start_pos | |
| ) | |
| losses.append(loss) | |
| stats.append({k: v.detach() for k, v in info.items()}) | |
| if self.config.depth_mode == "attention" and i + 1 < len(self.blocks): | |
| bank.append(self._write_depth(x)) | |
| if len(bank) > self.config.depth_slots: | |
| bank = ( | |
| [bank[0]] + bank[-(self.config.depth_slots - 1) :] | |
| if self.config.depth_slots > 1 | |
| else bank[-1:] | |
| ) | |
| reasoning_stats = None | |
| if self.reasoning is not None: | |
| x, reasoning_stats = self.reasoning( | |
| x, | |
| cache=None if caches is None else caches[-1], | |
| start_pos=start_pos, | |
| steps=reasoning_steps, | |
| ) | |
| x = self.final_norm(x) | |
| aux = torch.stack(losses).mean() | |
| z_loss = torch.stack([info["router_z_loss"] for info in stats]).mean() | |
| primary, total = None, None | |
| if labels is not None: | |
| # Checkpoint the vocabulary projection/CE chunks: no retained [B,T,V] | |
| # logits. Recompute only this head in backward, not the full model. | |
| from torch.utils.checkpoint import checkpoint | |
| states, targets = x[:, :-1].reshape(-1, x.shape[-1]), labels[:, 1:].reshape( | |
| -1 | |
| ) | |
| if targets.numel() == 0: | |
| raise ValueError("Language-model loss requires at least two tokens") | |
| parts = [] | |
| def chunk_loss(h, y): | |
| return F.cross_entropy( | |
| F.linear(h, self.lm_head.weight).float(), | |
| y, | |
| reduction="sum", | |
| ignore_index=-100, | |
| ) | |
| for offset in range(0, targets.numel(), self.config.loss_chunk_size): | |
| h, y = ( | |
| states[offset : offset + self.config.loss_chunk_size], | |
| targets[offset : offset + self.config.loss_chunk_size], | |
| ) | |
| parts.append( | |
| checkpoint(chunk_loss, h, y, use_reentrant=False) | |
| if torch.is_grad_enabled() | |
| else chunk_loss(h, y) | |
| ) | |
| primary = torch.stack(parts).sum() / (targets != -100).sum().clamp_min(1) | |
| total = primary + aux | |
| if return_logits is None: | |
| return_logits = labels is None | |
| # Loss above still uses every target. Inference only projects requested | |
| # positions, avoiding the temporary [batch, full_prompt, vocabulary]. | |
| logit_states = x if logit_positions is None else x[:, logit_positions] | |
| logits = self.lm_head(logit_states) if return_logits else None | |
| return TAMEOutput( | |
| loss=total, | |
| logits=logits, | |
| past_key_values=caches, | |
| aux_losses={ | |
| "primary": None if primary is None else primary.detach(), | |
| "router_balance": aux.detach() - z_loss, | |
| "router_z_loss": z_loss, | |
| "auxiliary_total": aux.detach(), | |
| }, | |
| attention_stats=stats, | |
| reasoning_stats=reasoning_stats, | |
| ) | |
| # Generation integration | |
| def _supports_default_dynamic_cache(cls): | |
| # A plain DynamicCache has no tile-routing state. | |
| return False | |
| def _prepare_cache_for_generation( | |
| self, generation_config, model_kwargs, *args, **kwargs | |
| ): | |
| implementation = generation_config.cache_implementation | |
| if implementation not in (None, "dynamic"): | |
| raise ValueError( | |
| "TAMELM supports its dynamic KV/routing cache; static, offloaded and quantized caches are unsupported" | |
| ) | |
| cache = model_kwargs.get("past_key_values") | |
| if cache is not None and not isinstance(cache, TAMECache): | |
| raise TypeError("TAMELM requires TAMECache to preserve tile-routing state") | |
| def _validate_generated_length( | |
| self, generation_config, input_ids_length, has_default_max_length | |
| ): | |
| super()._validate_generated_length( | |
| generation_config, input_ids_length, has_default_max_length | |
| ) | |
| if generation_config.max_length > self.config.max_seq_len: | |
| raise ValueError( | |
| f"Requested generation exceeds max_seq_len={self.config.max_seq_len}; shorten the prompt or max_new_tokens" | |
| ) | |
| def prepare_inputs_for_generation( | |
| self, | |
| input_ids, | |
| past_key_values=None, | |
| attention_mask=None, | |
| use_cache=True, | |
| next_sequence_length=None, | |
| position_ids=None, | |
| **kwargs, | |
| ): | |
| seen = past_key_values.get_seq_length() if past_key_values is not None else 0 | |
| if seen: | |
| if input_ids.shape[1] > seen: | |
| input_ids = input_ids[:, seen:] | |
| elif next_sequence_length is not None: | |
| input_ids = input_ids[:, -next_sequence_length:] | |
| if position_ids is not None: | |
| position_ids = position_ids[:, -input_ids.shape[1] :] | |
| return { | |
| "input_ids": input_ids.contiguous(), | |
| "past_key_values": past_key_values, | |
| "attention_mask": attention_mask, | |
| "position_ids": position_ids, | |
| "use_cache": use_cache, | |
| "logits_to_keep": 1, | |
| "reasoning_steps": kwargs.get("reasoning_steps"), | |
| } | |
| # Public forward path with padding and cache handling | |
| def forward( | |
| self, | |
| input_ids, | |
| labels=None, | |
| attention_mask=None, | |
| use_cache=False, | |
| past_key_values=None, | |
| start_pos=None, | |
| return_logits=None, | |
| return_dict=None, | |
| position_ids=None, | |
| logits_to_keep=0, | |
| token_type_ids=None, | |
| reasoning_steps=None, | |
| **kwargs, | |
| ): | |
| if input_ids.ndim != 2 or input_ids.shape[1] < 1: | |
| raise ValueError("input_ids must be a nonempty [batch, tokens] tensor") | |
| if ( | |
| isinstance(logits_to_keep, bool) | |
| or not isinstance(logits_to_keep, int) | |
| or logits_to_keep < 0 | |
| ): | |
| raise ValueError("logits_to_keep must be a nonnegative integer") | |
| if reasoning_steps is not None: | |
| if self.reasoning is None: | |
| raise ValueError( | |
| "reasoning_steps requires reasoning_mode='fold_unfold'" | |
| ) | |
| if ( | |
| not isinstance(reasoning_steps, int) | |
| or isinstance(reasoning_steps, bool) | |
| or reasoning_steps < 1 | |
| ): | |
| raise ValueError("reasoning_steps must be a positive integer") | |
| if token_type_ids is not None and bool(token_type_ids.any()): | |
| raise ValueError("TAMELM does not use token type embeddings") | |
| if kwargs.get("output_attentions") or kwargs.get("output_hidden_states"): | |
| raise NotImplementedError( | |
| "Attention/hidden-state collection is not implemented" | |
| ) | |
| if (use_cache or past_key_values is not None) and ( | |
| labels is not None or torch.is_grad_enabled() | |
| ): | |
| raise ValueError( | |
| "KV cache requires inference without labels under torch.no_grad()" | |
| ) | |
| if past_key_values is not None and not isinstance(past_key_values, TAMECache): | |
| raise TypeError("past_key_values must be a TAMECache") | |
| if past_key_values is not None and not use_cache: | |
| raise ValueError("Set use_cache=True when providing past_key_values") | |
| cache = past_key_values | |
| if use_cache and cache is None: | |
| cache = TAMECache(len(self.blocks), self.config.tile) | |
| seen = cache.get_seq_length() if cache is not None else 0 | |
| if start_pos is not None and start_pos != seen: | |
| raise ValueError("start_pos disagrees with the cache token count") | |
| batch, length = input_ids.shape | |
| kept_length = min(logits_to_keep, length) if logits_to_keep else length | |
| kept_start = length - kept_length | |
| if labels is not None and labels.shape != input_ids.shape: | |
| raise ValueError("labels must match input_ids") | |
| if attention_mask is None: | |
| current_mask = torch.ones_like(input_ids, dtype=torch.bool) | |
| mask = ( | |
| torch.cat((cache.mask, current_mask), dim=1) if seen else current_mask | |
| ) | |
| else: | |
| if attention_mask.shape != (batch, seen + length): | |
| raise ValueError("attention_mask must cover cached and new tokens") | |
| if not bool(((attention_mask == 0) | (attention_mask == 1)).all()): | |
| raise ValueError("attention_mask must contain only zeros and ones") | |
| mask = attention_mask.to(device=input_ids.device, dtype=torch.bool) | |
| if seen and not torch.equal(mask[:, :seen], cache.mask): | |
| raise ValueError("attention_mask changes already cached tokens") | |
| current_mask = mask[:, seen:] | |
| if cache is not None: | |
| if not cache.rows: | |
| cache.rows = [[{} for _ in self.blocks] for _ in range(batch)] | |
| if len(cache.rows) != batch: | |
| raise ValueError( | |
| "Cache batch size differs; reorder or expand it explicitly" | |
| ) | |
| if ( | |
| attention_mask is None | |
| and cache is None | |
| and length > self.config.max_seq_len | |
| ) or ( | |
| (attention_mask is not None or cache is not None) | |
| and bool((mask.sum(1) > self.config.max_seq_len).any()) | |
| ): | |
| raise ValueError("Real token count exceeds max_seq_len") | |
| if position_ids is not None: | |
| expected = mask.long().cumsum(-1)[:, seen:] - 1 | |
| if position_ids.shape != input_ids.shape or not torch.equal( | |
| position_ids[current_mask], expected[current_mask] | |
| ): | |
| raise ValueError("position_ids must follow unpadded token positions") | |
| # Packed training and unpadded full forwards retain the vectorized path. | |
| if cache is None and (attention_mask is None or bool(current_mask.all())): | |
| out = self._forward_unpadded( | |
| input_ids, | |
| labels=labels, | |
| return_logits=return_logits, | |
| reasoning_steps=reasoning_steps, | |
| logit_positions=slice(kept_start, None), | |
| ) | |
| else: | |
| if return_logits is None: | |
| return_logits = labels is None | |
| logits = None | |
| weighted_loss, weighted_primary, weighted_aux, counts = [], [], [], [] | |
| weighted_z = [] | |
| stats, reasoning_stats = [], [] | |
| for i in range(batch): | |
| positions = current_mask[i].nonzero(as_tuple=True)[0] | |
| if not positions.numel(): | |
| raise ValueError( | |
| "Each sequence must provide at least one real token" | |
| ) | |
| ids = input_ids[i : i + 1].index_select(1, positions) | |
| target = ( | |
| labels[i : i + 1].index_select(1, positions) | |
| if labels is not None | |
| else None | |
| ) | |
| offset = cache.row_length(i) if cache is not None else 0 | |
| # Map physical output positions to this row's unpadded states. | |
| retained = positions >= kept_start | |
| native_positions = retained.nonzero(as_tuple=True)[0] | |
| native = self._forward_unpadded( | |
| ids, | |
| labels=target, | |
| use_cache=cache is not None, | |
| past_key_values=cache.rows[i] if cache is not None else None, | |
| start_pos=offset, | |
| return_logits=return_logits, | |
| reasoning_steps=reasoning_steps, | |
| logit_positions=native_positions, | |
| ) | |
| if native.logits is not None: | |
| if logits is None: | |
| logits = native.logits.new_zeros( | |
| batch, kept_length, self.config.vocab_size | |
| ) | |
| logits[i, positions[retained] - kept_start] = native.logits[0] | |
| if labels is not None: | |
| count = (target[:, 1:] != -100).sum() | |
| counts.append(count) | |
| weighted_loss.append(native.loss * count) | |
| weighted_primary.append(native.aux_losses["primary"] * count) | |
| weighted_aux.append(native.aux_losses["router_balance"] * count) | |
| weighted_z.append(native.aux_losses["router_z_loss"] * count) | |
| stats = native.attention_stats | |
| reasoning_stats.append(native.reasoning_stats) | |
| if cache is not None: | |
| cache.mask = mask.detach().clone() | |
| denom = torch.stack(counts).sum().clamp_min(1) if counts else None | |
| out = TAMEOutput( | |
| loss=torch.stack(weighted_loss).sum() / denom if counts else None, | |
| logits=logits, | |
| past_key_values=cache, | |
| aux_losses={ | |
| "router_z_loss": ( | |
| torch.stack(weighted_z).sum() / denom | |
| if counts | |
| else input_ids.new_zeros((), dtype=torch.float32) | |
| ), | |
| "auxiliary_total": ( | |
| ( | |
| torch.stack(weighted_aux).sum() | |
| + torch.stack(weighted_z).sum() | |
| ) | |
| / denom | |
| if counts | |
| else input_ids.new_zeros((), dtype=torch.float32) | |
| ), | |
| "primary": ( | |
| torch.stack(weighted_primary).sum() / denom if counts else None | |
| ), | |
| "router_balance": ( | |
| torch.stack(weighted_aux).sum() / denom | |
| if counts | |
| else input_ids.new_zeros((), dtype=torch.float32) | |
| ), | |
| }, | |
| attention_stats=None, | |
| reasoning_stats=reasoning_stats if self.reasoning is not None else None, | |
| ) # per-layer routing summaries are defined for packed batches | |
| return out if return_dict is not False else out.to_tuple() | |
| # Portable Hugging Face export | |
| def export_hf_code(self, directory): | |
| from pathlib import Path | |
| import inspect | |
| import sys | |
| directory = Path(directory) | |
| directory.mkdir(parents=True, exist_ok=True) | |
| source = _NOTEBOOK_SOURCES.get("model") | |
| if source is None: | |
| source = inspect.getsource(sys.modules[type(self).__module__]) | |
| # Registration is notebook-local; portable loading uses auto_map. | |
| source = source.split("\nAutoConfig.register(TAMEConfig.model_type")[0] | |
| (directory / "modeling_tamelm.py").write_text(source, encoding="utf-8") | |
| (directory / "THIRD_PARTY_NOTICES.txt").write_text( | |
| THIRD_PARTY_NOTICES, encoding="utf-8" | |
| ) | |
| self.config.auto_map = { | |
| "AutoConfig": "modeling_tamelm.TAMEConfig", | |
| "AutoModelForCausalLM": "modeling_tamelm.TAMELM", | |
| } | |
| self.config.architectures = ["TAMELM"] | |
| self.config.save_pretrained(directory) | |
| self.generation_config.save_pretrained(directory) | |
| def save_pretrained(self, save_directory, *args, **kwargs): | |
| self.export_hf_code(save_directory) | |
| result = super().save_pretrained(save_directory, *args, **kwargs) | |
| if self.tokenizer is not None: | |
| self.tokenizer.save_pretrained(save_directory) | |
| return result | |
| _capture_cell_source("model") | |