Text Generation
Transformers
Safetensors
English
notoken_gen55
notokenlm
byte-level
tokenizer-free
hybrid
hierarchical
code
code-generation
custom_code
Instructions to use VeroLM/NoTokenLM-CodeGen-5.5 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use VeroLM/NoTokenLM-CodeGen-5.5 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="VeroLM/NoTokenLM-CodeGen-5.5", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("VeroLM/NoTokenLM-CodeGen-5.5", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use VeroLM/NoTokenLM-CodeGen-5.5 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "VeroLM/NoTokenLM-CodeGen-5.5" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "VeroLM/NoTokenLM-CodeGen-5.5", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/VeroLM/NoTokenLM-CodeGen-5.5
- SGLang
How to use VeroLM/NoTokenLM-CodeGen-5.5 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 "VeroLM/NoTokenLM-CodeGen-5.5" \ --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": "VeroLM/NoTokenLM-CodeGen-5.5", "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 "VeroLM/NoTokenLM-CodeGen-5.5" \ --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": "VeroLM/NoTokenLM-CodeGen-5.5", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use VeroLM/NoTokenLM-CodeGen-5.5 with Docker Model Runner:
docker model run hf.co/VeroLM/NoTokenLM-CodeGen-5.5
Upload 5 files
Browse filesFiles changed (5)
- LICENSEAdded+202
- configuration_notoken_gen55.pyAdded+58
- modeling_notoken_gen55.pyAdded+755
- tokenization_notoken_gen55.pyAdded+48
- tokenizer_config.jsonAdded+11
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
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 [2026] [Ömür Bera Işık]
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.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""Configuration of NoTokenLM-Gen-5.5 (byte-level hierarchical hybrid: byte encoder -> entropy patches -> RWKV-7/attention trunk -> byte decoder)."""from transformers import PretrainedConfig
class NoTokenGen55Config(PretrainedConfig): model_type = "notoken_gen55"
def __init__( self, # ---- trunk (operates on patches) d=768, n_block=5, pattern=("R", "A", "R", "R"), ffn=1792, head_dim=64, lora_decay=64, lora_a=64, lora_v=64, lora_g=128, attn_gate=True, qk_norm=True, attn_block=192, ln_scale=True, # ---- local byte modules d_loc=256, enc_blocks=("conv", "conv", "attn"), n_dec=4, loc_heads=4, loc_window=32, loc_block=0, conv_k=4, loc_ffn=704, pool_heads=8, dec_cross=False, cross_k=8, # ---- hashed n-gram embedding hash_orders=(3, 4, 5, 6, 7, 8), hash_rows=(103424,) * 6, hash_dim=32, # ---- patching seq_len=4096, max_patches=1536, patch_target=6.0, patch_max_len=16, patch_stride=6, chunk=16, # ---- entropy patcher (frozen) ent_d=256, ent_layers=8, ent_ffn=704, ent_k=4, ent_precision="high", vocab=257, # ---- RWKV-8 ideas rosa=True, deepembed="byte", de_rows=65536, de_dim=64, z_loss=1e-5, # ---- frozen patch-boundary threshold (calibrated in stage 0 of training) theta=None, # ---- bookkeeping training_step=None, **kwargs, ): self.d, self.n_block, self.pattern, self.ffn, self.head_dim = d, n_block, tuple(pattern), ffn, head_dim self.lora_decay, self.lora_a, self.lora_v, self.lora_g = lora_decay, lora_a, lora_v, lora_g self.attn_gate, self.qk_norm, self.attn_block, self.ln_scale = attn_gate, qk_norm, attn_block, ln_scale self.d_loc, self.enc_blocks, self.n_dec, self.loc_heads, self.loc_window, self.loc_block = d_loc, tuple(enc_blocks), n_dec, loc_heads, loc_window, loc_block self.conv_k, self.loc_ffn, self.pool_heads, self.dec_cross, self.cross_k = conv_k, loc_ffn, pool_heads, dec_cross, cross_k self.hash_orders, self.hash_rows, self.hash_dim = tuple(hash_orders), tuple(hash_rows), hash_dim self.seq_len, self.max_patches, self.patch_target, self.patch_max_len, self.patch_stride, self.chunk = seq_len, max_patches, patch_target, patch_max_len, patch_stride, chunk self.ent_d, self.ent_layers, self.ent_ffn, self.ent_k, self.ent_precision = ent_d, ent_layers, ent_ffn, ent_k, ent_precision self.vocab, self.rosa, self.deepembed, self.de_rows, self.de_dim, self.z_loss = vocab, bool(rosa), deepembed, de_rows, de_dim, z_loss self.theta, self.training_step = theta, training_step if self.dec_cross: raise NotImplementedError("decoder cross-attention (ablation arm) is not part of the released model") if self.deepembed not in ("off", "byte"): raise NotImplementedError("only deepembed = 'off' | 'byte' are supported by this implementation") super().__init__(**kwargs)
@property def n_layer(self): return self.n_block * len(self.pattern)
@property def n_hash(self): return len(self.hash_orders)
@property def de_byte(self): return self.deepembed in ("byte", "both")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755"""NoTokenLM-Gen-5.5 -- PyTorch inference implementation.
A faithful port of the JAX training code. Byte-level, tokenizer-free, hierarchical:
bytes --(byte emb + hashed past-only n-gram emb + ROSA features)--> local encoder (conv, conv, windowed attention) --> entropy-placed patches (avg ~6, max 16 bytes) --> attention pooling --> trunk over patches: 5 super-blocks of [RWKV-7, NoPE gated attention, RWKV-7, RWKV-7] --> local decoder (4 windowed-attention blocks) --> 256-way byte logits
Parameter names are identical to the dotted tensor names of the training checkpoints (e.g. ``trunk.l0.mix.Wr``, ``enc.0.conv``), so thesafetensors file loads without any renaming. The frozen entropy patcher lives under the ``patcher.`` prefix.
Only closed patches ever reach the decoder, so generation re-runs the (expensive) trunk only when a new patch closes."""import mathfrom typing import List, Optional
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as Ffrom transformers import PreTrainedModelfrom transformers.modeling_outputs import CausalLMOutput
from .configuration_notoken_gen55 import NoTokenGen55Config
EOD = 0BIG_DOC = 1 << 28
def _P(*shape): return nn.Parameter(torch.zeros(*shape))
# ============================================================================= small utilitiesdef rms_norm(x, w, eps=1e-6): x32 = x.float() y = x32 * torch.rsqrt(x32.pow(2).mean(-1, keepdim=True) + eps) * w.float() return y.to(x.dtype)
def causal_conv(x, w, doc, dilation=1): """depthwise causal conv. x (B,T,D), w (K,D). Taps that fall into another document are zeroed.""" K, T = w.shape[0], x.shape[1] pad = (K - 1) * dilation xp = F.pad(x, (0, 0, pad, 0)) dp = F.pad(doc, (pad, 0), value=-1) out = 0.0 for i in range(K): sl = xp[:, i * dilation:i * dilation + T] if i != K - 1: sl = sl * (dp[:, i * dilation:i * dilation + T] == doc).unsqueeze(-1).to(x.dtype) out = out + w[i].to(x.dtype) * sl return out
def rope_tables(n, dh, device): inv = 1.0 / (10000.0 ** (torch.arange(0, dh, 2, dtype=torch.float32, device=device) / dh)) ang = torch.arange(n, dtype=torch.float32, device=device)[:, None] * inv[None, :] return torch.cos(ang), torch.sin(ang)
def apply_rope(x, cos, sin): dh = x.shape[-1] x1, x2 = x[..., :dh // 2], x[..., dh // 2:] c, s = cos[None, None, :, None, :].to(x.dtype), sin[None, None, :, None, :].to(x.dtype) return torch.cat([x1 * c - x2 * s, x1 * s + x2 * c], -1)
def doc_ids(x): e = (x == EOD).long() return torch.cumsum(e, 1) - e
class SwiGLU(nn.Module): def __init__(self, d, ff): super().__init__() self.w1, self.w3, self.w2 = _P(d, ff), _P(d, ff), _P(ff, d)
def forward(self, x, scale=None): hid = F.silu(x @ self.w1.to(x.dtype)) * (x @ self.w3.to(x.dtype)) if scale is not None: hid = hid * scale.to(hid.dtype) return hid @ self.w2.to(x.dtype)
# ============================================================================= entropy patcher (frozen)class PatcherLayer(nn.Module): def __init__(self, cfg): super().__init__() self.n1, self.n2, self.conv = _P(cfg.ent_d), _P(cfg.ent_d), _P(cfg.ent_k, cfg.ent_d) self.ffn = SwiGLU(cfg.ent_d, cfg.ent_ffn)
class Patcher(nn.Module): """small causal TCN byte model; its next-byte entropy decides where patches start"""
def __init__(self, cfg): super().__init__() self.emb, self.nf, self.head = _P(256, cfg.ent_d), _P(cfg.ent_d), _P(cfg.ent_d, 256) self.layers = nn.ModuleList([PatcherLayer(cfg) for _ in range(cfg.ent_layers)])
def forward(self, x, doc): h = self.emb[x] for i, L in enumerate(self.layers): h = h + causal_conv(rms_norm(h, L.n1), L.conv, doc, dilation=2 ** i) h = h + L.ffn(rms_norm(h, L.n2)) return rms_norm(h, self.nf) @ self.head
# ============================================================================= local byte modulesclass LocalBlock(nn.Module): def __init__(self, kind, cfg): super().__init__() d, ff = cfg.d_loc, cfg.loc_ffn self.kind, self.heads, self.window, self.block = kind, cfg.loc_heads, cfg.loc_window, cfg.loc_block self.n1, self.n2 = _P(d), _P(d) self.ffn = SwiGLU(d, ff) if kind == "attn": self.wq, self.wk, self.wv, self.wo = _P(d, d), _P(d, d), _P(d, d), _P(d, d) else: self.conv = _P(cfg.conv_k, d) if cfg.de_byte: self.de = _P(cfg.vocab, ff)
def window_attn(self, x, doc): B, T, D = x.shape w = self.window blk = max(int(self.block or w), w) dh = D // self.heads padn = (-T) % blk if padn: x = F.pad(x, (0, 0, 0, padn)) doc = F.pad(doc, (0, padn), value=-2) Tp = T + padn nb = Tp // blk H = self.heads q = (x @ self.wq).reshape(B, nb, blk, H, dh) k = (x @ self.wk).reshape(B, nb, blk, H, dh) v = (x @ self.wv).reshape(B, nb, blk, H, dh) prev = lambda t: torch.cat([torch.zeros_like(t[:, :1]), t[:, :-1]], 1) k2 = torch.cat([prev(k), k], 2) v2 = torch.cat([prev(v), v], 2) dq = doc.reshape(B, nb, blk) dk = torch.cat([torch.cat([torch.full((B, 1, blk), -1, dtype=doc.dtype, device=doc.device), dq[:, :-1]], 1), dq], 2) cos, sin = rope_tables(2 * blk, dh, x.device) q = apply_rope(q, cos[blk:], sin[blk:]) k2 = apply_rope(k2, cos, sin) sc = torch.einsum("bnqhd,bnkhd->bnhqk", q, k2).float() / math.sqrt(dh) qpos = torch.arange(blk, device=x.device)[:, None] + blk kpos = torch.arange(2 * blk, device=x.device)[None, :] m = ((kpos <= qpos) & (qpos - kpos < w))[None, None, None] & (dk[:, :, None, None, :] == dq[:, :, None, :, None]) att = torch.softmax(sc.masked_fill(~m, -1e30), -1).to(x.dtype) y = torch.einsum("bnhqk,bnkhd->bnqhd", att, v2).reshape(B, Tp, D)[:, :T] return y @ self.wo
def forward(self, x, doc, xb): h = rms_norm(x, self.n1) x = x + (self.window_attn(h, doc) if self.kind == "attn" else causal_conv(h, self.conv, doc)) sc = (1.0 + self.de[xb]) if hasattr(self, "de") else None return x + self.ffn(rms_norm(x, self.n2), sc)
class Pool(nn.Module): def __init__(self, cfg): super().__init__() dl, d = cfg.d_loc, cfg.d self.ws, self.wv, self.wo, self.up = _P(dl, cfg.pool_heads), _P(dl, dl), _P(dl, dl), _P(dl, d) self.len_emb, self.pool_nf = _P(16, d), _P(d) self.heads = cfg.pool_heads
def forward(self, h, starts, lens): """h (1,T,dl); starts/lens (n,) of the closed patches -> (n,d)""" _, T, dl = h.shape n, K, Hp = starts.shape[0], 16, self.heads dh = dl // Hp sc = 5.0 * torch.tanh((h.float() @ self.ws) / 5.0)[0] # (T,Hp) hv = (h @ self.wv)[0] # (T,dl) idx = torch.clamp(starts[:, None] + torch.arange(K, device=h.device)[None, :], max=T - 1) ok = torch.arange(K, device=h.device)[None, :] < lens[:, None] # (n,K) scg = sc[idx] # (n,K,Hp) vg = hv[idx].reshape(n, K, Hp, dh) w = torch.softmax(scg.masked_fill(~ok[..., None], -1e30), dim=1) pooled = torch.einsum("pkh,pkhd->phd", w.to(h.dtype), vg).reshape(n, dl) out = (pooled @ self.wo) @ self.up out = out + self.len_emb[torch.clamp(lens, 1, 16) - 1] return rms_norm(out, self.pool_nf)
class Rosa(nn.Module): def __init__(self, cfg): super().__init__() self.pe, self.lg, self.lb, self.boost = _P(257, cfg.d_loc), _P(16, cfg.d_loc), _P(16, cfg.d_loc), _P(16)
# ============================================================================= trunkclass AttnParams(nn.Module): def __init__(self, cfg): super().__init__() n, d, hd = cfg.n_block, cfg.d, cfg.head_dim H = d // hd self.wq, self.wk, self.wv, self.wo = _P(n, d, d), _P(n, d, d), _P(n, d, d), _P(n, d, d) if cfg.qk_norm: self.qn, self.kn = _P(n, hd), _P(n, hd) if cfg.attn_gate: self.gate_w, self.gate_b = _P(n, d, H), _P(n, H)
class RwkvParams(nn.Module): def __init__(self, cfg): super().__init__() n, C, N = cfg.n_block, cfg.d, cfg.head_dim H = C // N for nm in ("x_r", "x_w", "x_k", "x_v", "x_a", "x_g", "w0", "a0", "k_k", "k_a", "v0", "ln_w", "ln_b"): setattr(self, nm, _P(n, C)) self.w1, self.w2 = _P(n, C, cfg.lora_decay), _P(n, cfg.lora_decay, C) self.a1, self.a2 = _P(n, C, cfg.lora_a), _P(n, cfg.lora_a, C) self.g1, self.g2 = _P(n, C, cfg.lora_g), _P(n, cfg.lora_g, C) self.v1, self.v2 = _P(n, C, cfg.lora_v), _P(n, cfg.lora_v, C) self.r_k = _P(n, H, N) self.Wr, self.Wk, self.Wv, self.Wo = _P(n, C, C), _P(n, C, C), _P(n, C, C), _P(n, C, C)
class StackedFFN(nn.Module): def __init__(self, cfg): super().__init__() n, d, ff = cfg.n_block, cfg.d, cfg.ffn self.w1, self.w3, self.w2 = _P(n, d, ff), _P(n, d, ff), _P(n, ff, d)
class TrunkLayer(nn.Module): """one position of the super-block pattern, parameters stacked over the n_block super-blocks"""
def __init__(self, kind, cfg): super().__init__() self.kind = kind self.n1, self.n2 = _P(cfg.n_block, cfg.d), _P(cfg.n_block, cfg.d) self.mix = AttnParams(cfg) if kind == "A" else RwkvParams(cfg) self.ffn = StackedFFN(cfg)
def wkv7_chunked(r, lw, k, v, kk, a, L, doc): """chunk-parallel RWKV-7 with document resets (port of the training kernel in plain XLA form). All (B,T,H,N) fp32, doc (B,T) long.""" B, T, H, N = r.shape nC = T // L assert nC * L == T dev = r.device
def rs(x): return x.reshape(B, nC, L, H, N).permute(0, 3, 1, 2, 4)
r, lw, k, v, kk, a = map(rs, (r, lw, k, v, kk, a)) u, b = kk, kk * a lg = torch.cumsum(lw, dim=3) lgp = lg - lw lgL = lg[:, :, :, -1:, :] Up, Rp, Kp, Bp = u * torch.exp(lgp), r * torch.exp(lg), k * torch.exp(-lg), b * torch.exp(-lg) Khat, Bhat = k * torch.exp(lgL - lg), b * torch.exp(lgL - lg) mm = lambda A, Bm: A @ Bm.transpose(-1, -2) strict = torch.tril(torch.ones(L, L, device=dev), -1) incl = torch.tril(torch.ones(L, L, device=dev)) dch = doc.reshape(B, nC, L) dc = dch[:, None] # (B,1,nC,L) same = (dc[..., :, None] == dc[..., None, :]).float() strict, incl = strict * same, incl * same d_in = torch.cat([torch.full((B, 1), -1, dtype=dch.dtype, device=dev), dch[:, :-1, -1]], 1) d_out = dch[:, :, -1] cm = (dc == d_in[:, None, :, None]).float()[..., None] om = (dc == d_out[:, None, :, None]).float()[..., None] keep = (d_in == d_out).float()[:, None, :, None, None] Kc, Bc, Kr, Br = mm(Up, Kp) * strict, mm(Up, Bp) * strict, mm(Rp, Kp) * incl, mm(Rp, Bp) * incl I = torch.eye(L, device=dev) Minv, Pw = I - Bc, Bc # (I+Bc)^-1 for nilpotent Bc for _ in range(int(math.log2(L)) - 1): Pw = Pw @ Pw Minv = Minv @ (I + Pw) Mu = Minv @ Up Cstat = Minv @ (Kc @ v) Ra = Rp - Br @ Mu Ystat = Kr @ v - Br @ Cstat expL = torch.exp(lgL[:, :, :, 0, :]) Ach = expL[..., :, None] * torch.eye(N, device=dev) - torch.einsum("...ln,...lm->...nm", Mu, Bhat) vs, Cs = v * om, Cstat * om Sst = torch.einsum("...lv,...lk->...vk", vs, Khat) - torch.einsum("...lv,...lk->...vk", Cs, Bhat) Ach = Ach * keep S = torch.zeros(B, H, N, N, device=dev) starts = [] for c in range(nC): starts.append(S) S = S @ Ach[:, :, c] + Sst[:, :, c] Sstart = torch.stack(starts, 2) # (B,H,nC,N,N) Ra = Ra * cm Y = torch.einsum("...lk,...vk->...lv", Ra, Sstart) + Ystat return Y.permute(0, 2, 3, 1, 4).reshape(B, T, H, N), S # S: state after the last token
def wkv7_step(S, r, lw, k, v, kk, a): """one-token RWKV-7 recurrence. S (H,N,N) [v,k]; r,lw,k,v,kk,a (H,N). returns (y (H,N), S')""" Skk = torch.einsum("hij,hj->hi", S, kk) S = S * torch.exp(lw)[:, None, :] - Skk[..., None] * (kk * a)[:, None, :] + v[..., None] * k[:, None, :] return torch.einsum("hij,hj->hi", S, r), S
def rwkv_tmix(mx, b, x, v_first, first, xprev, wkv, cfg): """x, xprev (B,T,C) (xprev = token-shifted input, already zeroed at document starts); wkv(r,lw,k,v,kk,a) -> y (B,T,H,N) on (B,T,H,N) fp32 inputs""" B, T, C = x.shape N = cfg.head_dim H = C // N g_ = lambda nm: getattr(mx, nm)[b] xx = xprev - x xr, xw, xk, xv, xa, xg = [x + xx * g_(n).to(x.dtype) for n in ("x_r", "x_w", "x_k", "x_v", "x_a", "x_g")] r, k, v = xr @ g_("Wr"), xk @ g_("Wk"), xv @ g_("Wv") wl = g_("w0") + torch.tanh(xw.float() @ g_("w1")) @ g_("w2") lw = -torch.sigmoid(wl) * math.exp(-0.5) if first: v_first = v else: v = v + (v_first - v) * torch.sigmoid(g_("v0") + (xv.float() @ g_("v1")) @ g_("v2")).to(v.dtype) a = torch.sigmoid(g_("a0") + (xa.float() @ g_("a1")) @ g_("a2")) g = torch.sigmoid(xg.float() @ g_("g1")) @ g_("g2") r32, k32, v32 = r.float(), k.float(), v.float() kk = (k32 * g_("k_k")).reshape(B, T, H, N) kk = kk / torch.sqrt((kk * kk).sum(-1, keepdim=True) + 1e-24) k32 = k32 * (1 + (a - 1) * g_("k_a")) hs = lambda t: t.reshape(B, T, H, N) y = wkv(hs(r32), hs(lw), hs(k32), hs(v32), kk, hs(a)) mu = y.mean(-1, keepdim=True) var = ((y - mu) ** 2).mean(-1, keepdim=True) y = ((y - mu) * torch.rsqrt(var + 64e-5)).reshape(B, T, C) * g_("ln_w") + g_("ln_b") y = y + ((hs(r32) * hs(k32) * g_("r_k")).sum(-1, keepdim=True) * hs(v32)).reshape(B, T, C) return (y * g).to(x.dtype) @ g_("Wo"), v_first
def trunk_attention(mx, b, x, pdoc, valid, cfg): B, T, D = x.shape hd = cfg.head_dim H = D // hd q = (x @ mx.wq[b]).reshape(B, T, H, hd) k = (x @ mx.wk[b]).reshape(B, T, H, hd) v = (x @ mx.wv[b]).reshape(B, T, H, hd) if cfg.qk_norm: q, k = rms_norm(q, mx.qn[b]), rms_norm(k, mx.kn[b]) q, k, v = (t.transpose(1, 2) for t in (q, k, v)) # (B,H,T,hd) sc = (q @ k.transpose(-1, -2)).float() / math.sqrt(hd) m = (pdoc[:, :, None] == pdoc[:, None, :]) & valid[:, None, :] & torch.tril(torch.ones(T, T, dtype=torch.bool, device=x.device))[None] att = torch.softmax(sc.masked_fill(~m[:, None], -1e30), -1).to(x.dtype) y = (att @ v).transpose(1, 2) # (B,T,H,hd) if cfg.attn_gate: y = y * torch.sigmoid(x.float() @ mx.gate_w[b] + mx.gate_b[b]).to(x.dtype)[..., None] return y.reshape(B, T, D) @ mx.wo[b], k, v
def trunk_attention_step(mx, b, x, kc, vc, same, cfg): """one new patch attends to the cached keys/values (kc, vc: (H,n,hd), already containing the new patch). x (1,1,D); same (n,) bool = key belongs to the same document""" D = x.shape[-1] hd = cfg.head_dim H = D // hd q = (x @ mx.wq[b]).reshape(1, 1, H, hd) if cfg.qk_norm: q = rms_norm(q, mx.qn[b]) q = q[0, 0] # (H,hd) sc = torch.einsum("hd,hnd->hn", q, kc).float() / math.sqrt(hd) att = torch.softmax(sc.masked_fill(~same[None], -1e30), -1).to(x.dtype) y = torch.einsum("hn,hnd->hd", att, vc) # (H,hd) if cfg.attn_gate: y = y * torch.sigmoid(x[0, 0].float() @ mx.gate_w[b] + mx.gate_b[b]).to(x.dtype)[:, None] return (y.reshape(1, 1, D) @ mx.wo[b])
# ============================================================================= hashed n-gram embedding (host-side, uint32 wrap-around like the training code)def _mix32(h): h = h ^ (h >> np.uint32(16)) h = h * np.uint32(0x7feb352d) h = h ^ (h >> np.uint32(15)) h = h * np.uint32(0x846ca68b) return h ^ (h >> np.uint32(16))
def hash_rows_np(x, doc, cfg): """x, doc (T,) int arrays -> rows (T,O) int64 into the concatenated hash table and valid (T,O) bool""" T = len(x) u = x.astype(np.uint32) + np.uint32(1) M = np.uint32(0x9E3779B1) h = u.copy() hs = {1: h} with np.errstate(over="ignore"): for n in range(2, max(cfg.hash_orders) + 1): h = np.concatenate([np.zeros(1, np.uint32), h[:-1]]) * M + u hs[n] = h rows, valids, off = [], [], 0 pos = np.arange(T) for n, nr in zip(cfg.hash_orders, cfg.hash_rows): g = _mix32(hs[n] ^ np.uint32((n * 0x85EBCA6B) & 0xFFFFFFFF)) rows.append((g % np.uint32(nr)).astype(np.int64) + off) off += nr dshift = np.concatenate([np.full(min(n - 1, T), -3, doc.dtype), doc[:max(T - (n - 1), 0)]]) if n > 1 else doc valids.append((pos >= n - 1) & (dshift == doc)) return np.stack(rows, -1), np.stack(valids, -1)
# ============================================================================= ROSA (online suffix automaton on bytes, host-side)_EDGES = (1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 128, 256)
def _bucket(m): if m <= 0: return 0 for i, e in enumerate(_EDGES): if m <= e: return i + 1 return 15
def rosa_features(x): """x: sequence of byte ids. returns (pred1, bucket) int arrays: pred1 = predicted next byte + 1 (0 = none), bucket = match-length bucket (0 = none). The automaton is reset after every EOD byte; the features at position j only depend on x[0..j].""" n = len(x) pred1 = np.zeros(n, np.int64) bkt = np.zeros(n, np.int64) nxt, link, ln, pos = [{}], [-1], [0], [-1] last = 0 for i in range(n): c = int(x[i]) if c == 0 or c > 255: nxt, link, ln, pos = [{}], [-1], [0], [-1] last = 0 continue cur = len(nxt) nxt.append({}) link.append(0) ln.append(ln[last] + 1) pos.append(i) p = last while p != -1 and c not in nxt[p]: nxt[p][c] = cur p = link[p] if p == -1: link[cur] = 0 else: q = nxt[p][c] if ln[p] + 1 == ln[q]: link[cur] = q else: cl = len(nxt) nxt.append(dict(nxt[q])) link.append(link[q]) ln.append(ln[p] + 1) pos.append(pos[q]) while p != -1 and nxt[p].get(c) == q: nxt[p][c] = cl p = link[p] link[q] = cl link[cur] = cl last = cur m = link[cur] if m > 0 and pos[m] + 1 <= i: pred1[i] = int(x[pos[m] + 1]) + 1 bkt[i] = _bucket(min(ln[m], 8192)) pos[m] = i return pred1, bkt
# ============================================================================= modelclass NoTokenGen55PreTrainedModel(PreTrainedModel): config_class = NoTokenGen55Config base_model_prefix = "" supports_gradient_checkpointing = False _tied_weights_keys = [] _no_split_modules = []
def _init_weights(self, module): # weights always come from the checkpoint pass
class NoTokenGen55ForCausalLM(NoTokenGen55PreTrainedModel): def __init__(self, config: NoTokenGen55Config): super().__init__(config) cfg = config dl, d = cfg.d_loc, cfg.d self.emb_in = _P(cfg.vocab, dl) self.enc = nn.ModuleList([LocalBlock(k, cfg) for k in cfg.enc_blocks]) self.enc_nf = _P(dl) self.pool = Pool(cfg) self.trunk = nn.ModuleDict({f"l{j}": TrunkLayer(k, cfg) for j, k in enumerate(cfg.pattern)}) self.nf = _P(d) self.down, self.down_nf, self.bos = _P(d, dl), _P(dl), _P(dl) self.dec = nn.ModuleList([LocalBlock("attn", cfg) for _ in range(cfg.n_dec)]) self.dec_nf = _P(dl) self.head = _P(dl, 256) if cfg.rosa: self.rosa = Rosa(cfg) if cfg.n_hash: self.hash_table = _P(int(sum(cfg.hash_rows)), cfg.hash_dim) self.hash_nw = _P(cfg.n_hash * cfg.hash_dim) self.hash_proj = _P(cfg.n_hash * cfg.hash_dim, dl) self.patcher = Patcher(cfg) self.post_init()
# ------------------------------------------------------------------------- pieces def _embed(self, x_np, x, doc): cfg = self.config h = self.emb_in[x] if cfg.rosa: p1, bk = rosa_features(x_np) p1, bk = torch.as_tensor(p1, device=x.device), torch.as_tensor(bk, device=x.device) R = self.rosa h = h + R.pe[p1] * R.lg[bk] + R.lb[bk] else: p1 = bk = None if cfg.n_hash: rows, valid = hash_rows_np(x_np, doc.cpu().numpy(), cfg) rows, valid = torch.as_tensor(rows, device=x.device), torch.as_tensor(valid, device=x.device) e = self.hash_table[rows] * valid[..., None].to(h.dtype) # (T,O,hd) e = rms_norm(e.reshape(len(x_np), cfg.n_hash * cfg.hash_dim), self.hash_nw) h = h + e @ self.hash_proj return h[None], p1, bk
def _layout(self, x, ent_logits, theta): """patch boundaries of the T bytes + whether the NEXT byte would start a patch. Everything is causal: the patcher output at position j (which only saw bytes <= j) decides whether byte j+1 starts a patch, so the open/closed state of the last patch is known at generation time.""" T = x.shape[0] L = self.config.patch_max_len lp = torch.log_softmax(ent_logits[0].float(), -1) H = -(lp.exp() * lp).sum(-1) # (T,) ent_ext = torch.cat([torch.full((1,), float("inf"), device=x.device), H]) # ent_ext[j] = entropy of the belief about byte j prev_eod = torch.cat([torch.ones(1, dtype=torch.bool, device=x.device), x == EOD]) force = prev_eod | (ent_ext > theta) idx = torch.arange(T + 1, device=x.device) fpos = torch.cummax(torch.where(force, idx, torch.full_like(idx, -1)), 0).values s_ext = force | (((idx - fpos) % L) == 0) s, s_next = s_ext[:T], s_ext[1:] starts_all = torch.nonzero(s).squeeze(1) n_closed = int(starts_all.numel()) - 1 + int(s_ext[T]) ends = torch.cat([starts_all[1:], torch.full((1,), T, device=x.device, dtype=starts_all.dtype)])[:n_closed] starts = starts_all[:n_closed] pid = torch.cumsum(s.long(), 0) - 1 didx = pid + s_next.long() # number of closed patches after byte j return dict(starts=starts, lens=ends - starts, n_closed=n_closed, didx=didx)
def _lscale(self, b, j): cfg = self.config return 1.0 / math.sqrt(b * len(cfg.pattern) + j + 1) if cfg.ln_scale else 1.0
def _trunk(self, pv, pdoc, capture=None): """pv (n,d) pooled vectors of the closed patches -> (n,d) latents. Padding goes to the FRONT (with its own document id), so the recurrent state after the last chunk is exactly the state after the last real patch; `capture` (a dict) receives that state + the attention keys/values.""" cfg = self.config n, d = pv.shape Ch = cfg.chunk pad = (-n) % Ch dev = pv.device xx = F.pad(pv, (0, 0, pad, 0))[None] pd = torch.cat([torch.full((pad,), -5, dtype=pdoc.dtype, device=dev), pdoc])[None] valid = torch.cat([torch.zeros(pad, dtype=torch.bool, device=dev), torch.ones(n, dtype=torch.bool, device=dev)])[None] doc_start = torch.cat([torch.ones(1, 1, dtype=torch.bool, device=dev), pd[:, 1:] != pd[:, :-1]], 1) vf = torch.zeros_like(xx) pat = cfg.pattern if capture is not None: capture.update(S={}, xp={}, K={}, V={}) for b in range(cfg.n_block): for j, kind in enumerate(pat): Lr = self.trunk[f"l{j}"] s = self._lscale(b, j) h = rms_norm(xx, Lr.n1[b]) * s if kind == "A": y, k, v = trunk_attention(Lr.mix, b, h, pd, valid, cfg) if capture is not None: capture["K"][(b, j)], capture["V"][(b, j)] = k[0, :, pad:], v[0, :, pad:] # (H,n,hd) else: xprev = torch.where(doc_start[..., None], torch.zeros_like(h), F.pad(h, (0, 0, 1, 0))[:, :-1]) fin = {}
def wkv(r, lw, k, v, kk, a, fin=fin): y, S = wkv7_chunked(r, lw, k, v, kk, a, cfg.chunk, pd) fin["S"] = S return y
y, vf = rwkv_tmix(Lr.mix, b, h, vf, (b == 0 and j == 0), xprev, wkv, cfg) if capture is not None: capture["S"][(b, j)], capture["xp"][(b, j)] = fin["S"][0], h[0, -1] xx = xx + y h2 = rms_norm(xx, Lr.n2[b]) * s f = Lr.ffn xx = xx + (F.silu(h2 @ f.w1[b]) * (h2 @ f.w3[b])) @ f.w2[b] if capture is not None: capture["last_doc"] = int(pdoc[-1]) capture["pdoc"] = pdoc.clone() return rms_norm(xx, self.nf)[0, pad:]
def _trunk_step(self, pv, doc_id, st): """ONE new patch (pv (d,), document id) through the trunk, updating the state `st` in place. returns its latent (d,)""" cfg = self.config N = cfg.head_dim new_doc = (doc_id != st["last_doc"]) st["pdoc"] = torch.cat([st["pdoc"], torch.full((1,), doc_id, dtype=st["pdoc"].dtype, device=pv.device)]) same = st["pdoc"] == doc_id xx = pv[None, None] vf = torch.zeros_like(xx) pat = cfg.pattern for b in range(cfg.n_block): for j, kind in enumerate(pat): Lr = self.trunk[f"l{j}"] s = self._lscale(b, j) h = rms_norm(xx, Lr.n1[b]) * s if kind == "A": mx = Lr.mix k = (h @ mx.wk[b]).reshape(1, 1, -1, cfg.head_dim) v = (h @ mx.wv[b]).reshape(1, 1, -1, cfg.head_dim) if cfg.qk_norm: k = rms_norm(k, mx.kn[b]) st["K"][(b, j)] = torch.cat([st["K"][(b, j)], k[0].transpose(0, 1)], 1) # (H,n+1,hd) st["V"][(b, j)] = torch.cat([st["V"][(b, j)], v[0].transpose(0, 1)], 1) y = trunk_attention_step(mx, b, h, st["K"][(b, j)], st["V"][(b, j)], same, cfg) else: xprev = torch.zeros_like(h) if new_doc else st["xp"][(b, j)][None, None] if new_doc: st["S"][(b, j)] = torch.zeros_like(st["S"][(b, j)]) st["xp"][(b, j)] = h[0, 0] box = {}
def wkv(r, lw, k, v, kk, a, box=box, key=(b, j)): y, S = wkv7_step(st["S"][key], r[0, 0], lw[0, 0], k[0, 0], v[0, 0], kk[0, 0], a[0, 0]) st["S"][key] = S return y[None, None]
y, vf = rwkv_tmix(Lr.mix, b, h, vf, (b == 0 and j == 0), xprev, wkv, cfg) xx = xx + y h2 = rms_norm(xx, Lr.n2[b]) * s f = Lr.ffn xx = xx + (F.silu(h2 @ f.w1[b]) * (h2 @ f.w3[b])) @ f.w2[b] st["last_doc"] = doc_id return rms_norm(xx, self.nf)[0, 0]
# ------------------------------------------------------------------------- forward over one byte sequence def _forward_one(self, x_np, cache=None, last_only=False): cfg = self.config dev = self.head.device T = len(x_np) assert T >= 1 x = torch.as_tensor(np.asarray(x_np), dtype=torch.long, device=dev) doc = doc_ids(x[None]) theta = float(cfg.theta) ent_logits = self.patcher(x[None], doc) lay = self._layout(x, ent_logits, theta) h, p1, bk = self._embed(np.asarray(x_np), x, doc[0]) for L in self.enc: h = L(h, doc, x[None]) h = rms_norm(h, self.enc_nf) n = lay["n_closed"] pdoc_all = doc[0][lay["starts"]] if n > 0 else torch.zeros(0, dtype=torch.long, device=dev) if n == 0: gl = torch.zeros(0, cfg.d_loc, device=dev) if cache is not None: cache.clear() elif cache is not None and cache.get("st") is not None and cache["n"] <= n: # incremental: only the newly closed patches go through the trunk (the state of the earlier ones is cached) n0 = cache["n"] gl_parts = [cache["gl"]] if n > n0: pv = self.pool(h, lay["starts"][n0:], lay["lens"][n0:]) for i in range(n - n0): g = self._trunk_step(pv[i], int(pdoc_all[n0 + i]), cache["st"]) gl_parts.append(rms_norm(g @ self.down, self.down_nf)[None]) gl = torch.cat(gl_parts, 0) cache["n"], cache["gl"] = n, gl else: pv = self.pool(h, lay["starts"], lay["lens"]) st = {} if cache is not None else None g = self._trunk(pv, pdoc_all, capture=st) gl = rms_norm(g @ self.down, self.down_nf) if cache is not None: cache["st"], cache["n"], cache["gl"] = st, n, gl gext = torch.cat([self.bos[None], gl], 0) pdoc_ext = torch.cat([torch.full((1,), -1, device=dev, dtype=torch.long), doc[0][lay["starts"]]]) if n > 0 else torch.full((1,), -1, device=dev, dtype=torch.long) didx = lay["didx"] didx = torch.where(pdoc_ext[didx] == doc[0], didx, torch.zeros_like(didx)) # first bytes of a document see BOS u = h[0] + gext[didx] sl = slice(max(0, T - 192), T) if last_only else slice(0, T) # decoder receptive field is 4 x 31 bytes u, dsl, xs = u[sl][None], doc[:, sl], x[sl][None] for L in self.dec: u = L(u, dsl, xs) logits = rms_norm(u, self.dec_nf) @ (self.head - self.head.mean(1, keepdim=True)) logits = logits[0].float() if cfg.rosa: pp, bb = p1[sl], bk[sl] oh = (pp[:, None] - 1) == torch.arange(256, device=dev)[None, :] logits = logits + oh.float() * self.rosa.boost[bb][:, None] return logits[-1:] if last_only else logits
# ------------------------------------------------------------------------- HF API def forward(self, input_ids=None, labels=None, **kwargs): """input_ids (B,T) byte ids (0..255; 0 = end of document). returns logits (B,T,256): logits[:,j] predict byte j+1.""" ids = input_ids.detach().cpu().numpy() logits = torch.stack([self._forward_one(row) for row in ids]) loss = None if labels is not None: loss = F.cross_entropy(logits[:, :-1].reshape(-1, 256), labels[:, 1:].reshape(-1).to(logits.device)) return CausalLMOutput(loss=loss, logits=logits)
@torch.no_grad() def generate(self, input_ids=None, prompt: Optional[str] = None, max_new_tokens: int = 300, temperature: float = 0.8, top_p: float = 1.0, top_k: Optional[int] = 0, do_sample: bool = True, seed: Optional[int] = None, stop_at_eod: bool = True, streamer=None, **kwargs): """byte-by-byte generation. Give `input_ids` (LongTensor (1,T) / list of byte ids) or `prompt` (str). Returns a LongTensor (1, T + new) of byte ids (byte 0 = end-of-document; generation stops when it is emitted unless stop_at_eod=False). do_sample=False or temperature<=0 -> greedy. Sampling uses temperature, top_k (0/None = off) and top_p. seed makes it reproducible. `max_new_bytes` is accepted as an alias of `max_new_tokens`. The trunk state of closed patches is cached, so each new byte is cheap.""" max_new_tokens = int(kwargs.pop("max_new_bytes", max_new_tokens)) if prompt is not None: ids = list(prompt.encode("utf-8")) else: ids = [int(t) for t in (input_ids.flatten().tolist() if torch.is_tensor(input_ids) else input_ids)] if not ids: ids = [32] # never feed an empty sequence if self.config.theta is None: raise ValueError("config.theta is missing (the calibrated patch threshold). Run convert_checkpoint.py or use the official config.json.") limit = self.config.seq_len if len(ids) + max_new_tokens > limit: # stay inside the trained 4096-byte window ids = ids[-max(1, limit - max_new_tokens):] max_new_tokens = min(max_new_tokens, limit - len(ids)) gen = torch.Generator(device="cpu") if seed is not None: gen.manual_seed(int(seed)) else: gen.seed() # non-deterministic: every call gives a different sample greedy = (not do_sample) or temperature is None or temperature <= 0 cache = {} for _ in range(max_new_tokens): lg = self._forward_one(ids, cache=cache, last_only=True)[0].float().cpu() if greedy: nxt = int(lg.argmax()) else: lg = lg / temperature if top_k and top_k > 0: kth = torch.topk(lg, min(int(top_k), 256)).values[-1] lg = lg.masked_fill(lg < kth, float("-inf")) pr = torch.softmax(lg, -1) if top_p is not None and top_p < 1.0: sp, si = torch.sort(pr, descending=True) sp = sp.masked_fill(torch.cumsum(sp, 0) - sp > top_p, 0.0) pr = torch.zeros_like(pr).scatter(0, si, sp) pr = pr / pr.sum() nxt = int(torch.multinomial(pr, 1, generator=gen)) ids.append(nxt) if streamer is not None: streamer(nxt) if stop_at_eod and nxt == EOD: break return torch.tensor([ids], dtype=torch.long)
def generate_text(self, prompt: str, return_prompt: bool = True, **kw) -> str: """convenience: str in, str out (the end-of-document byte is dropped; invalid UTF-8 from a cut multi-byte character becomes U+FFFD)""" out = self.generate(prompt=prompt, **kw)[0].tolist() n0 = len(prompt.encode("utf-8")) return bytes(i for i in out[(0 if return_prompt else n0):] if i != EOD).decode("utf-8", errors="replace")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Byte "tokenizer" of NoTokenLM-Gen-5.5: token id == UTF-8 byte value (0..255). Byte 0 is the end-of-document marker (EOD)."""import jsonimport osfrom typing import Dict, List, Optional, Tuple
from transformers import PreTrainedTokenizer
class NoTokenGen55Tokenizer(PreTrainedTokenizer): vocab_files_names = {} model_input_names = ["input_ids"]
def __init__(self, eod_token="\x00", **kwargs): self._byte_tokens = [chr(i) for i in range(256)] # token i is the single character whose code point is i (only used as a label) super().__init__(eos_token=eod_token, pad_token=eod_token, bos_token=None, unk_token=None, **kwargs)
@property def vocab_size(self) -> int: return 256
def get_vocab(self) -> Dict[str, int]: return {t: i for i, t in enumerate(self._byte_tokens)}
# text <-> byte ids (does not go through a vocabulary) def encode(self, text, add_special_tokens=False, **kwargs) -> List[int]: ids = list(text.encode("utf-8")) return ids + [0] if add_special_tokens else ids
def decode(self, token_ids, skip_special_tokens=True, **kwargs) -> str: if hasattr(token_ids, "tolist"): token_ids = token_ids.tolist() bs = bytes(int(i) for i in token_ids if not (skip_special_tokens and int(i) == 0)) return bs.decode("utf-8", errors="replace")
def _tokenize(self, text, **kwargs) -> List[str]: return [self._byte_tokens[b] for b in text.encode("utf-8")]
def _convert_token_to_id(self, token) -> int: return ord(token) if len(token) == 1 and ord(token) < 256 else 0
def _convert_id_to_token(self, index) -> str: return self._byte_tokens[int(index)]
def convert_tokens_to_string(self, tokens) -> str: return bytes(ord(t) for t in tokens).decode("utf-8", errors="replace")
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]: return ()1234567891011{ "tokenizer_class": "NoTokenGen55Tokenizer", "auto_map": { "AutoTokenizer": [ "tokenization_notoken_gen55.NoTokenGen55Tokenizer", null ] }, "model_max_length": 4096, "eod_token": "\u0000"}LICENSEAdded+202
configuration_notoken_gen55.pyAdded+58
modeling_notoken_gen55.pyAdded+755
tokenization_notoken_gen55.pyAdded+48
tokenizer_config.jsonAdded+11