"""Load the shipped BF16 text tensors and run the original visit-aware loop.""" import hashlib import json import mmap import struct import time from pathlib import Path import torch from torch import nn from transformers import Qwen2Tokenizer from transformers.models.qwen3_5 import modeling_qwen3_5 as hf from bootstrap import PACK_SHA, checked from modeling_sensenova_loop import ( MHCRouter, SenseNovaLoopConfig, SenseNovaLoopForConditionalGeneration, sinkhorn, ) from native_runtime import NativeTextModel, VisitGatedMHC, extend_convolutions CHECKPOINT_SHA = '46f6697cd260e5055280b6f6427896d8df1cfd00cb8b2c3bbbf8586e4fa5fae8' DTYPES = {'torch.float32': torch.float32, 'torch.bfloat16': torch.bfloat16} EOS_ID = 248044 def make_text(config): # Build shapes without allocating the visual weights, which this demo never loads. with torch.device('meta'): full = SenseNovaLoopForConditionalGeneration(config) text = full.model.language_model text.__class__ = NativeTextModel for i in range(4, 28): layer = text.layers[i] layer.__class__ = VisitGatedMHC layer.native_visit_gain = nn.Parameter(torch.empty(2, dtype=torch.float32), requires_grad=False) layer._native_window = 256 if i in (7, 15, 27) else 0 extend_convolutions(full) with torch.device('cpu'): text.rotary_emb = hf.Qwen3_5TextRotaryEmbedding(text.config) return text def load_text_weights(text, pack): checked(pack, PACK_SHA) with pack.open('rb') as stream, mmap.mmap(stream.fileno(), 0, access=mmap.ACCESS_READ) as data: if data[:8] != b'LSENSE01': raise ValueError('Formato de pesos inesperado') header_size = struct.unpack(' 2048: raise ValueError('O protótipo aceita até 2048 tokens de entrada.') ids = torch.tensor([prefix], device=self.device) cache = None tokens = [] started = time.perf_counter() first = None for _ in range(budget): output = self.text(input_ids=ids, past_key_values=cache, use_cache=True) cache = output.past_key_values logits = nn.functional.linear(output.last_hidden_state[:, -1], self.text.embed_tokens.weight).float() next_id = logits.argmax(-1) token = int(next_id.item()) if first is None: first = time.perf_counter() - started tokens.append(token) if token == EOS_ID: break ids = next_id.view(1, 1) seconds = time.perf_counter() - started return { 'text': self.tok.decode(tokens, skip_special_tokens=True), 'tokens': tokens, 'seconds': seconds, 'first_token_seconds': first, 'decode_tokens_per_second': (len(tokens) - 1) / max(1e-9, seconds - first) if len(tokens) > 1 else None, 'ended_eos': tokens[-1] == EOS_ID, 'device': str(self.text.embed_tokens.weight.device), 'physical_layers': len(self.text.layers), 'execution_visits': len(self.text._loop_plan), 'cached_routers': self.cached_routers, 'weights_SHA256': PACK_SHA, 'prototype': True, }