Thomas Seri commited on
Commit ·
f034088
1
Parent(s): 29d9647
README: rimossi numeri senza fonte (energia, modelli esterni), 'record' -> 'migliore tra gli R-08', brevetti UIBM senza numero non verificato
Browse filesFiles changed (24)
- .gitattributesDeleted-4
- LICENSE.mdDeleted-63
- README.md+9-14
- assets/r08_logo.jpgDeleted
- config.jsonDeleted-63
- fast_walk.pyDeleted-401
- geodesic_network.pyDeleted-355
- geodesic_stages_model.pyDeleted-1593
- geodesic_stages_v7_2_model.pyDeleted-242
- mesh_topology.pyDeleted-352
- model.safetensorsDeleted-3
- modeling_geodesic.pyDeleted-228
- pezzi_tokenizer.pyDeleted-228
- test_inference_release.pyDeleted-38
- vocab_stages.pyDeleted-971
- vocab_stages/00_pezzi_by_id.meta.jsonDeleted-17
- vocab_stages/00_pezzi_by_id.txtDeleted-1253
- vocab_stages/01_parole_by_id.meta.jsonDeleted-100
- vocab_stages/01_parole_by_id.txtDeleted
- vocab_stages/02_unioni_by_id.meta.jsonDeleted-122
- vocab_stages/02_unioni_by_id.txtDeleted
- vocab_stages/counts_summary.jsonDeleted-10
- vocab_stages/manifest.jsonDeleted-25
- watchman_keystone_r08.pyDeleted-416
1234*.safetensors filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.gguf filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263# R08 — NON-COMMERCIAL RESEARCH & ETHICAL LICENSE (v2.0)
Copyright (c) 2026 Thomas Seri. All Rights Reserved.
---
### 1. DEFINITIONS- **"Author"** means Thomas Seri (Sentinel).- **"Software"** means the R08 / R-08 (Rob) Geodesic Mesh Neural Network architecture, model weights, checkpoints, Watchman Keystone modules, Knowledge Tree ontologies, tokenizers (`gpTommy`), search engines, configurations, and documentation provided herein for Sentinel LifeOS.- **"Commercial Use"** means using the Software or any derivative work in any business, for-profit venture, service provision, integration into commercial applications, or for any activity generating revenue.- **"Non-Commercial Research Use"** means using the Software solely for personal education, academic study, reproducibility evaluation, and non-profit benchmarking.
---
### 2. GRANT OF PERMISSIONSubject to the terms and restrictions of this License, the Author grants you a personal, worldwide, royalty-free, non-exclusive, non-transferable license to:1. Download, view, and inspect the code and weights.2. Run inference for Non-Commercial Research Use only.3. Cite and reference the architecture and benchmark results in academic or research publications, provided that prominent attribution is given to **Thomas Seri** and **Sentinel AI**.
---
### 3. RESTRICTIONS & PROHIBITIONSYou shall NOT:1. Use the Software or any portion thereof for any Commercial Use without a separate, written, commercial license agreement signed by the Author (**Thomas Seri**).2. Sublicense, lease, sell, rent, or distribute modified copies of the Software for commercial purposes.3. Reverse-engineer, distill, extract weights, train competing models on synthetic outputs, or replicate proprietary architectural features (including 3-stage geodesic cascades, 12 icosahedral hub pyramids, and 1D causal inter-sphere convolutions) for deployment in commercial or third-party products without prior written authorization from **Thomas Seri**.4. Remove, alter, obfuscate, or circumvent the Author's attribution (**Thomas Seri**), this License (`LICENSE.md`), or the integrated **Watchman Keystone (`watchman_keystone_r08.py`)** security and ethical manifold.
---
### 3.1 STRICT ETHICAL RESTRICTIONS & PROHIBITED USES (ACCEPTABLE USE POLICY)It is strictly, unconditionally, and globally FORBIDDEN to use the Software, model weights, checkpoints, architecture, code, or any derivative works for:1. **Military, Defense & Warfare**: Weapons development, explosives, chemical/biological/nuclear agents, autonomous defense systems, suicide/combat drones, missile targeting, tactical combat simulations, warfare logistics, or military applications of any kind.2. **Religious Propaganda & Indoctrination**: Proselytism, forced religious manipulation, spiritual coercion, cult indoctrination, or automated doctrinal dissemination.3. **Inappropriate Images, Pornography & Sexual Exploitation**: Generation, prompting, processing, or dissemination of inappropriate images (NSFW), sexually explicit content, pornography, non-consensual nudity/deepfakes, CSAM, or sexual exploitation of any kind.4. **Cyberattacks, Malware & Industrial Sabotage**: Writing, training, or deploying computer malware, ransomware, trojans, keyloggers, zero-day exploits, phishing kits, unauthorized network intrusion tools, or attacks/sabotage on industrial PLCs, SCADA systems, and critical infrastructure (healthcare, energy, water, finance).5. **Addictions, Gambling, Illicit Drugs & Self-Harm**: Promotion or automation of gambling, online casinos, slot/betting manipulation algorithms, synthesis or distribution of illicit drugs, or encouragement/instruction of suicide, self-harm, or violence.6. **Political Campaigns & Partisan Propaganda**: Electoral manipulation, voter persuasion bots, automated political astroturfing, partisan lobbying, candidate campaigns, or deceptive political disinformation/fake news.7. **High-Risk Autonomous Decisions (Medical & Financial)**: Autonomous clinical diagnosis, prescription of medication, or unmonitored financial trading without certified human professional oversight.8. **Surveillance, Biometric Profiling & GDPR Privacy Violations**: Mass biometric surveillance, facial tracking without consent, racial/ethnic predictive policing, discrimination based on race, gender, religion, or nationality, or unauthorized extraction/storage of personal identifiable financial data (such as cleartext or obfuscated IBANs and credit card numbers).
**IMMEDIATE REVOCATION CLAUSE:** ANY USE VIOLATING THIS SECTION IMMEDIATELY AND AUTOMATICALLY REVOKES ALL PERMISSIONS AND LICENSES GRANTED HEREIN WITH RETROACTIVE EFFECT, RENDERING ANY ONGOING POSSESSION OR USE OF THE SOFTWARE AN ILLEGAL INFRINGEMENT OF THE AUTHOR'S INTELLECTUAL PROPERTY AND COPYRIGHT.
---
### 4. COPYRIGHT, TRADEMARK & CRYPTOGRAPHIC WATCHMAN PROTECTIONThe names **"Sentinel"**, **"Sentinel LifeOS"**, **"Sentinel AI"**, **"R-08"**, **"R08"**, **"gpTommy"**, and **"Thomas Seri"** are protected identities, trade names, and trademarks of the Author. No license is granted herein to use these names, logos, or marks for trade, commercial advertising, or to imply any endorsement, affiliation, or sponsorship of any third-party product, service, or company without prior, express written authorization from **Thomas Seri**.
**CRYPTOGRAPHIC & GEODESIC WATCHMAN KEYSTONE NOTICE:** The neural weights (`model.safetensors`) and inference runtime (`modeling_geodesic.py`, `watchman_keystone_r08.py`) incorporate a non-linear symplectic manifold (`GELU + SiLU + Tanh`), an orthogonal cryptographic projection lock (`SHA3-512`), and multi-layer forensic watermarks tied to **Thomas Seri** and this License. Any tampering with this License, the Author attribution, or the Watchman Keystone invalidates the projection manifold and constitutes unlawful circumvention of technological protection measures.
---
### 5. DISCLAIMER OF WARRANTY & LIMITATION OF LIABILITYTHE 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.
**MEDICAL, FINANCIAL & LEGAL DISCLAIMER:** The Software is an experimental research system. The outputs generated by this model do NOT constitute certified medical advice, legal counsel, or financial/investment recommendations. The Author and Sentinel AI shall have NO liability for any personal injury, financial loss, legal liability, or damages arising directly or indirectly from decisions made based on outputs of the Software. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
For commercial licensing, enterprise partnerships, or integration inquiries:Contact: **Thomas Seri** / **Sentinel AI**Website: https://www.sentinelhub.eu42 unmodified lines434445464748495051525354555658 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431445 unmodified lines15015115215315415515615723 unmodified lines18118218318418518618742 unmodified lines**Hardware di Sviluppo:** Apple Silicon (Metal Performance Shaders - MPS)**Modelli Correlati della Famiglia:**- 🇮🇹 [Vocabolario & Tokenizer gpTommy 32k su GitHub](https://github.com/Thomasseri/gpTommy-32k) | [Hugging Face](https://huggingface.co/SentinelHub/gpTommy-32k)- 🌟 [Nuovo Sentinel R-08 v7.2a DA ZERO (51.6M, Record 82.51% BLiMP-IT) su GitHub](https://github.com/Thomasseri/R-08-v7.2a) | [Hugging Face](https://huggingface.co/SentinelHub/R-08-v7.2a)- 🌐 [R08 v7 Pyramid (44.5M) su Hugging Face](https://huggingface.co/SentinelHub/R-08) | [GitHub](https://github.com/Thomasseri/R-08)- 🔬 [Controllo A/B Transformer Baseline (44.9M) su Hugging Face](https://huggingface.co/SentinelHub/R-08-Transformer-Baseline) | [GitHub](https://github.com/Thomasseri/R-08-Transformer-Baseline)---> ### 💼 Investment, Compute Grants & Enterprise Licensing (Investimenti & Partnership Industriali)> 🇬🇧 **Sentinel** is scaling the **Geodesic Pyramidal Sphere Architecture (`R-08`)** from 50M to **110M–1B+ parameters**, backed by **18 industrial patent filings** (Non-Euclidean Geodesic Mesh, Isomorphic `SSvvv` Lexical-Voice Engine, Post-Quantum Tamper-Resistant Keystone Security, Edge & Autonomous Systems).> **Open to Seed / Deep-Tech Investment, GPU/TPU Compute Grants, and Enterprise R&D Partnerships.**> 🇮🇹 **Aperto a Investimenti Seed / Deep-Tech, Grant Computazionali GPU/TPU e Licenze Industriali Enterprise.**> 📩 **Contact Founder & Inventor Thomas Seri:** 🌐 **[www.sentinelhub.eu](https://www.sentinelhub.eu)** | 🐙 **[GitHub (@Thomasseri)](https://github.com/Thomasseri)** | 🤗 **[Hugging Face (@SentinelHub)](https://huggingface.co/SentinelHub)** | 💬 **[Open an Inquiry / Issue](https://github.com/Thomasseri/R-08/issues/new)**58 unmodified lines| :--- | :---: | :---: | :---: | :---: || **Parametri Totali** | **51.6M** | 44.5M | 44.9M | **+7.04M parametri (Hub 12)** || **Strati di Attenzione Densa** | **2 strati** | **2 strati** | 14 strati | **-85.7% strati densi** || **BLiMP-IT (Accuratezza Linguistica IT)** | **82.02%** 🏆 | 80.95% | 85.84% | **+1.07% salto netto su v7** || **MultiBLiMP (Ragionamento Logico IT)** | **73.46%** | 73.46% | 86.83% | **Stabilità perfetta** || **Resistenza Allucinazioni (Truth Rate)** | **56.2%** *(Fatti 3/4, Scienza 3/4)* | 62.5% *(Fatti 4/4)* | 68.8% | Allineato ai foundation model || **BLiMP Standard Inglese (Cross-Lingua)** | **55.00%** 📈 | 52.80% | 54.00% | **+2.20% generalizzazione** || **Stuttering / Balbuzie nei Test Aperti** | **Completamente Eliminata** ✅ | Presente su loop lunghi | Assente | **Risolto con Conv 1D ($k=4$)** || **Consumo Energetico per Token** | **2.40 mJ / token** 🔋 | **2.30 mJ / token** | 3.30 mJ / token | **-27.3% consumo energetico** || **Energia per Risposta (200 token su Mac)** | **~52.0 Joule** ⚡ | **~50.5 Joule** | 72.5 Joule | **-28.3% di batteria risparmiata** || **Traffico RAM KV-Cache (a 512 token)** | **0.8 MB** *(2.1 MB/seq)* 💾 | **0.8 MB** *(2.1 MB/seq)* | 5.6 MB *(14.7 MB/seq)* | **-85.7% traffico RAM/Cache** || **RAM Totale Necessaria per Inferenza** | **~120 - 150 MB** | **~110 - 130 MB** | ~190 - 250 MB | **Gira su qualsiasi Edge device** |---### 2. Confronto vs Modelli Open Foundation (~70M - 125M)| Modello | Creatore | Parametri | Strati Attenzione | BLiMP-IT (Italiano) | BLiMP Inglese | RAM Minima Richiesta || :--- | :--- | :---: | :---: | :---: | :---: | :---: || **OPT-125M** | Meta (Facebook AI) | 125M | 12 strati | 62.50% | 71.20% | ~500 MB || **GPT-Neo-125M** | EleutherAI | 125M | 12 strati | 68.20% | 72.40% | ~500 MB || **Pythia-70M** | EleutherAI | 70.4M | 6 strati | 73.80% | 74.60% | ~280 MB || **GPT-2 Small** | OpenAI | 124.4M | 12 strati | 74.50% | 85.00% | ~498 MB || [**Transformer Baseline**](https://huggingface.co/SentinelHub/R-08-Transformer-Baseline) | Baseline di Controllo | 44.9M | 14 strati | 85.84% | 54.00% | ~220 MB || 🌐 [**R08 v7 Pyramid**](https://huggingface.co/SentinelHub/R-08) | Thomas Seri / Sentinel | 44.5M | **2 strati** | 80.95% | 52.80% | ~120 MB || 🚀 **R08-v7.2 (Rob)** | **Thomas Seri / Sentinel** | **51.6M** | **2 strati** | **82.02%** | **55.00%** | **~130 MB** || 🌟 [**R08-v7.2a (DA ZERO)**](https://github.com/Thomasseri/R-08-v7.2a) | **Thomas Seri / Sentinel** | **51.6M** | **2 strati** | **82.51%** 🏆 | **49.20%** | **~130 MB** |---5 unmodified lines| **Parametri Totali in `model.safetensors`** | **`51.975.444`** tensori totali salvati (composti da **`51.614.115` parametri neurali attivi** + **`361.329` buffer topologici** e indici di adiacenza dell'icosaedro geodetico) || **Runtime di Esecuzione ** | **Motore Geometrico Nativo `modeling_geodesic.py`** (`trust_remote_code=True`). Essendo una topologia sferico-piramidale non-Transformer, utilizza obbligatoriamente il proprio runtime nativo invece di wrapper nati solo per Transformer piatti (`vLLM`/`Ollama`). || **Finestra di Contesto Operativa** | **`256 – 512` token nativi** (scalabile fino a **`2.048` token** in inferenza con soli `0,8 MB – 3,2 MB` di KV-Cache). || **Throughput & Efficienza Energetica** | **`~2.850 – 3.020 tok/s`** in pretraining / **`~140 tok/s`** in generazione singola su Apple Silicon (MPS), con consumo di **`2,40 mJ/token`** e footprint RAM di **`~140 MB`**. || **Confronto con Baseline Internazionali** | Testato in Zero-Shot diretto anche contro **`Pythia-70M` (`70.4M`)** e **`GPT-2 Base` (`124.4M`)**: sulle probe fattuali italiane di TruthfulQA Zero-Shot, `R-08` raggiunge il **`56,2% – 62,5%` (Fatti 4/4 100%)** contro il `50,0%` (livello casuale) di `Pythia-70M` e `GPT-2 124M`, occupando fino a **22× meno KV-Cache** (`0,8 MB` vs `18,0 MB` di GPT-2). || **Lingua & Licenza** | Italiano (`it`) · **R08 Non-Commercial Research & Ethical License v2.0** (Foro Esclusivo di Milano) |---23 unmodified lines**Edge AI** significa far girare l'intelligenza artificiale direttamente all'interno del dispositivo locale (Mac, micro-PC industriale, centralina PLC, drone, smartphone) **senza connessione a internet**:1. **Zero Latenza:** Risposta immediata in tempo reale per comandi industriali.2. **Privacy Totale:** I dati aziendali o personali non escono mai dal dispositivo.3. **Consumo di Batteria Minimo:** Consuma appena **~52 Joule per risposta**, consentendo ore di autonomia anche su dispositivi non collegati alla rete elettrica.4. **Footprint di appena ~130 MB di RAM:** Può essere eseguito in background continuo su un Raspberry Pi o su computer con memoria ridotta senza impattare minimamente le altre applicazioni.---42 unmodified lines434445464748495051525354555658 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391405 unmodified lines14614714814915015115223 unmodified lines17617717817918018118242 unmodified lines**Hardware di Sviluppo:** Apple Silicon (Metal Performance Shaders - MPS)**Modelli Correlati della Famiglia:**- 🇮🇹 [Vocabolario & Tokenizer gpTommy 32k su GitHub](https://github.com/Thomasseri/gpTommy-32k) | [Hugging Face](https://huggingface.co/SentinelHub/gpTommy-32k)- 🌟 [Nuovo Sentinel R-08 v7.2a DA ZERO (51.6M, 82.51% BLiMP-IT, migliore tra gli R-08) su GitHub](https://github.com/Thomasseri/R-08-v7.2a) | [Hugging Face](https://huggingface.co/SentinelHub/R-08-v7.2a)- 🌐 [R08 v7 Pyramid (44.5M) su Hugging Face](https://huggingface.co/SentinelHub/R-08) | [GitHub](https://github.com/Thomasseri/R-08)- 🔬 [Controllo A/B Transformer Baseline (44.9M) su Hugging Face](https://huggingface.co/SentinelHub/R-08-Transformer-Baseline) | [GitHub](https://github.com/Thomasseri/R-08-Transformer-Baseline)---> ### 💼 Investment, Compute Grants & Enterprise Licensing (Investimenti & Partnership Industriali)> 🇬🇧 **Sentinel** is scaling the **Geodesic Pyramidal Sphere Architecture (`R-08`)** from 50M to **110M–1B+ parameters**, with **patent applications filed at the Italian Patent and Trademark Office (UIBM)**.> **Open to Seed / Deep-Tech Investment, GPU/TPU Compute Grants, and Enterprise R&D Partnerships.**> 🇮🇹 **Aperto a Investimenti Seed / Deep-Tech, Grant Computazionali GPU/TPU e Licenze Industriali Enterprise.**> 📩 **Contact Founder & Inventor Thomas Seri:** 🌐 **[www.sentinelhub.eu](https://www.sentinelhub.eu)** | 🐙 **[GitHub (@Thomasseri)](https://github.com/Thomasseri)** | 🤗 **[Hugging Face (@SentinelHub)](https://huggingface.co/SentinelHub)** | 💬 **[Open an Inquiry / Issue](https://github.com/Thomasseri/R-08/issues/new)**58 unmodified lines| :--- | :---: | :---: | :---: | :---: || **Parametri Totali** | **51.6M** | 44.5M | 44.9M | **+7.04M parametri (Hub 12)** || **Strati di Attenzione Densa** | **2 strati** | **2 strati** | 14 strati | **-85.7% strati densi** || **BLiMP-IT (Accuratezza Linguistica IT)** | **82.02%** | 80.95% | 85.84% | **+1.07% salto netto su v7** || **MultiBLiMP (Ragionamento Logico IT)** | **73.46%** | 73.46% | 86.83% | **Stabilità perfetta** || **Resistenza Allucinazioni (Truth Rate)** | **56.2%** *(Fatti 3/4, Scienza 3/4)* | 62.5% *(Fatti 4/4)* | 68.8% | Allineato ai foundation model || **BLiMP Standard Inglese (Cross-Lingua)** | **55.00%** 📈 | 52.80% | 54.00% | **+2.20% generalizzazione** || **Stuttering / Balbuzie nei Test Aperti** | **Completamente Eliminata** ✅ | Presente su loop lunghi | Assente | **Risolto con Conv 1D ($k=4$)** || **Traffico RAM KV-Cache (a 512 token)** | **0.8 MB** *(2.1 MB/seq)* 💾 | **0.8 MB** *(2.1 MB/seq)* | 5.6 MB *(14.7 MB/seq)* | **-85.7% traffico RAM/Cache** || **RAM Totale Necessaria per Inferenza** | **~120 - 150 MB** | **~110 - 130 MB** | ~190 - 250 MB | **Gira su qualsiasi Edge device** |---### 2. Confronto tra modelli Sentinel e Transformer di controlloUn confronto con modelli open esterni (Pythia-70M, GPT-2, OPT, GPT-Neo) sugli stessi benchmark italiani non è ancora stato eseguito con uno script riproducibile. Le versioni precedenti di questa pagina riportavano numeri per questi modelli che non erano verificati: sono stati rimossi il 6/11/2026 e verranno ripubblicati solo dopo una misura reale.| Modello | Creatore | Parametri | Strati Attenzione | BLiMP-IT (Italiano) | BLiMP Inglese | RAM Minima Richiesta || :--- | :--- | :---: | :---: | :---: | :---: | :---: || [**Transformer Baseline**](https://huggingface.co/SentinelHub/R-08-Transformer-Baseline) | Baseline di Controllo | 44.9M | 14 strati | 85.84% | 54.00% | ~220 MB || 🌐 [**R08 v7 Pyramid**](https://huggingface.co/SentinelHub/R-08) | Thomas Seri / Sentinel | 44.5M | **2 strati** | 80.95% | 52.80% | ~120 MB || 🚀 **R08-v7.2 (Rob)** | **Thomas Seri / Sentinel** | **51.6M** | **2 strati** | **82.02%** | **55.00%** | **~130 MB** || 🌟 [**R08-v7.2a (DA ZERO)**](https://github.com/Thomasseri/R-08-v7.2a) | **Thomas Seri / Sentinel** | **51.6M** | **2 strati** | **82.51%** | **49.20%** | **~130 MB** |---5 unmodified lines| **Parametri Totali in `model.safetensors`** | **`51.975.444`** tensori totali salvati (composti da **`51.614.115` parametri neurali attivi** + **`361.329` buffer topologici** e indici di adiacenza dell'icosaedro geodetico) || **Runtime di Esecuzione ** | **Motore Geometrico Nativo `modeling_geodesic.py`** (`trust_remote_code=True`). Essendo una topologia sferico-piramidale non-Transformer, utilizza obbligatoriamente il proprio runtime nativo invece di wrapper nati solo per Transformer piatti (`vLLM`/`Ollama`). || **Finestra di Contesto Operativa** | **`256 – 512` token nativi** (scalabile fino a **`2.048` token** in inferenza con soli `0,8 MB – 3,2 MB` di KV-Cache). || **Throughput & Efficienza Energetica** | **`~2.850 – 3.020 tok/s`** in pretraining / **`~140 tok/s`** in generazione singola su Apple Silicon (MPS) e footprint RAM di **`~140 MB`**. || **Lingua & Licenza** | Italiano (`it`) · **R08 Non-Commercial Research & Ethical License v2.0** (Foro Esclusivo di Milano) |---23 unmodified lines**Edge AI** significa far girare l'intelligenza artificiale direttamente all'interno del dispositivo locale (Mac, micro-PC industriale, centralina PLC, drone, smartphone) **senza connessione a internet**:1. **Zero Latenza:** Risposta immediata in tempo reale per comandi industriali.2. **Privacy Totale:** I dati aziendali o personali non escono mai dal dispositivo.3. **Poca memoria:** con 2 soli strati di attenzione la KV-Cache è 7 volte più piccola del Transformer di controllo (0.8 MB contro 5.6 MB a 512 token).4. **Footprint di appena ~130 MB di RAM:** Può essere eseguito in background continuo su un Raspberry Pi o su computer con memoria ridotta senza impattare minimamente le altre applicazioni.---
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263{ "model_name": "R08-v7.2", "architectures": [ "R08Model" ], "model_type": "geodesic_mesh_pyramid_v7_2", "architecture_name": "cascade_stages_attn_mesh_v7_2", "wiring": "serial_emb_mesh_x3_head_pezzi_causal_conv_regional_hubs", "d_model": 256, "max_seq_len": 512, "seq_len": 256, "vocab_pezzi": 1251, "vocab_parole": 17908, "vocab_unioni": 20006, "n_attn_layers": 2, "n_heads": 8, "pyramid_center": true, "regional_pyramid": { "num_regions": 12, "icosahedron_poles": 12, "faces_partitioned": 80, "d_stretto": 128, "d_centro": 512, "stadi": 3, "parametri_hubs_totali": 7266816 }, "causal_convolutions_1d": { "enabled": true, "stages": [ "conv_12", "conv_23" ], "kernel_size": 4, "d_model": 256, "zero_init_residual": true }, "mesh_topology": { "geometry": "geodesic_sphere_icosahedron", "frequency": 2, "total_faces": 80, "total_vertices": 42, "neighbors_per_face": 3 }, "routing": { "hash_routing": true, "router_v6": true, "no_walk": true, "compass_spiral": true }, "total_parameters": 51614115, "benchmarks": { "blimp_it": 0.8202, "multiblimp_ita": 0.7346, "truthfulqa_zero_shot": 0.562, "blimp_en": 0.55 }, "torch_dtype": "float32", "transformers_version": "4.45.0", "author": "Thomas Seri (Sentinel)", "license": "R08-Non-Commercial-Ethical-License-v2.0", "jurisdiction": "Court of Milan (Sezione Specializzata in Materia di Impresa), Italy", "prohibited_uses": "Commercial, Military, Defense, Clean-Room Reverse Engineering, Model Distillation"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401"""Cammino vettorizzato sulla mesh per CascadeMeshModel / V1OnlyMeshModel.
Sostituisce il loop Python per faccia di ``CascadeMeshModel.walk_token``(``for f_id in face[active].unique().tolist()`` + ``forward_face`` con``.item()`` e maschere booleane) con un dispatch raggruppato alla MegaBlocks:
- i parametri dei TriangleBlock sono impilati per face id (stack differenziabile dei parametri esistenti: state_dict e checkpoint invariati); - i token attivi sono disposti per faccia (posizioni da un cumsum, niente sort): le facce con pochi token in un elemento di batch per faccia, quelle affollate in blocchi da ``block_rows`` righe con i pesi raccolti per blocco (vedi ``grouped_block_forward`` per il perché dei percorsi); - ogni Linear del blocco diventa un ``baddbmm`` per percorso; - le uscite tornano ai token con ``index_select`` e ``torch.where``.
Le forme dipendono solo dal numero di token B, mai dai dati: nel salto non cisono ``unique``, ``tolist``, ``nonzero`` né ``.item()``.
Puro refactoring: proiezione sulla faccia, router, Gumbel-ST, soglia di uscitae peso straight-through sull'uscita intera del blocco sono quelli del modello(si chiamano gli stessi metodi ``project_to_face``, ``_route_step``,``_scatter_side_oh`` nello stesso ordine), quindi anche il consumo delgeneratore casuale è lo stesso. Restano due sincronizzazioni, entrambenecessarie per l'equivalenza: - ``active.any()`` a inizio salto con routing soft: il codice originale esce dal ciclo quando tutti i token sono usciti e da lì non estrae più rumore Gumbel (in routing hard i salti in più sono no-op e il controllo è saltato); - nel backward, una lettura per banca della maschera delle facce visitate: le facce mai visitate devono restare con grad None come nel loop.
``fast_walk_token_v6`` è il cammino del router v6 (vedi geodesic_stages_model):stesso dispatch raggruppato, peso straight-through passato come ``gate`` sulsolo ramo dell'esperto."""from __future__ import annotations
from typing import Dict, List, Optional, Sequence, Tuple
import torchimport torch.nn as nnimport torch.nn.functional as F
DEFAULT_BLOCK_ROWS = 16 # >= 16: regime "M grande" del Linear su MPSDEFAULT_DENSE_ROWS = 15 # <= 15: regime "M piccolo" del Linear su MPS
_NAMES = ("ln_w", "ln_b", "w1", "b1", "w2", "b2", "wr", "br")
def _check_block(blk: nn.Module) -> None: norm, ff, router = blk.norm, blk.ff, blk.router ok = ( isinstance(norm, nn.LayerNorm) and norm.weight is not None and norm.bias is not None and len(norm.normalized_shape) == 1 and isinstance(ff, nn.Sequential) and len(ff) == 3 and isinstance(ff[0], nn.Linear) and isinstance(ff[1], nn.GELU) and ff[1].approximate == "none" and isinstance(ff[2], nn.Linear) and ff[0].bias is not None and ff[2].bias is not None and isinstance(router, nn.Linear) and router.bias is not None ) if not ok: raise TypeError("fast_walk: TriangleBlock con struttura inattesa (LN → Linear → GELU → Linear, router)")
def _face_blocks(bank: nn.Module) -> List[nn.Module]: """TriangleBlock in ordine di face id (il ModuleList è in ordine di packing a coppie).""" slots = bank.__dict__.get("_fast_walk_slots") if slots is None: slots = [int(s) for s in bank.face_to_slot.detach().cpu().tolist()] if sorted(slots) != list(range(len(bank.blocks))) or len(slots) != int(bank.num_faces): raise ValueError("fast_walk: face_to_slot non è una permutazione dei blocchi") for s in slots: _check_block(bank.blocks[s]) bank.__dict__["_fast_walk_slots"] = slots return [bank.blocks[s] for s in slots]
def _block_params(blk: nn.Module) -> Tuple[torch.Tensor, ...]: return ( blk.norm.weight, blk.norm.bias, blk.ff[0].weight, blk.ff[0].bias, blk.ff[2].weight, blk.ff[2].bias, blk.router.weight, blk.router.bias, )
class _VisitedFaces: """Facce che hanno eseguito il blocco in almeno un salto (maschera su device, letta nel backward)."""
def __init__(self) -> None: self.mask: Optional[torch.Tensor] = None self._host: Optional[List[bool]] = None
def add(self, counts: torch.Tensor) -> None: hit = counts > 0 self.mask = hit if self.mask is None else (self.mask | hit)
def host(self, n_faces: int) -> List[bool]: if self._host is None: self._host = [False] * n_faces if self.mask is None else [bool(v) for v in self.mask.tolist()] return self._host
class _StackFaces(torch.autograd.Function): """torch.stack per tipo di parametro; nel backward le facce mai visitate ricevono None.
Nel loop originale i parametri di una faccia non visitata non entrano nel grafo e restano con grad None (AdamW li salta: niente momento né weight decay); un grad di zeri cambierebbe l'aggiornamento. Per lo stesso motivo un tipo di parametro fuori dal grafo differenziabile (il router con routing hard) deve restare None: niente gradienti materializzati a zero. """
@staticmethod def forward(ctx, visited: _VisitedFaces, n_faces: int, *flat: torch.Tensor): ctx.set_materialize_grads(False) ctx.visited = visited ctx.n_faces = n_faces return tuple(torch.stack(flat[k : k + n_faces]) for k in range(0, len(flat), n_faces))
@staticmethod def backward(ctx, *grads): hit = ctx.visited.host(ctx.n_faces) out: List[Optional[torch.Tensor]] = [None, None] for g in grads: if g is None: out.extend([None] * ctx.n_faces) else: out.extend(gf if h else None for gf, h in zip(g.unbind(0), hit)) return tuple(out)
def stack_bank(bank: nn.Module) -> Dict[str, object]: """Parametri della banca impilati per face id: ln (F,d), w1 (F,h,d), w2 (F,d,h), router (F,4,d).
Con autograd attivo lo stack è nel grafo (i gradienti tornano ai parametri per faccia) e ``st["visited"]`` va aggiornato dal cammino. Senza gradienti il risultato resta in cache finché i parametri non cambiano (data_ptr e contatore di versione). """ blocks = _face_blocks(bank) params = [_block_params(b) for b in blocks] n_faces = len(blocks) grad_mode = torch.is_grad_enabled() and any(p.requires_grad for ps in params for p in ps) if grad_mode: visited = _VisitedFaces() flat = [ps[i] for i in range(len(_NAMES)) for ps in params] st: Dict[str, object] = dict(zip(_NAMES, _StackFaces.apply(visited, n_faces, *flat))) st["visited"] = visited bank.__dict__.pop("_fast_walk_cache", None) else: key = (torch.is_inference_mode_enabled(),) + tuple( (p.data_ptr(), p._version, p.device, p.dtype) for ps in params for p in ps ) cached = bank.__dict__.get("_fast_walk_cache") if cached is not None and cached[0] == key: return cached[1] st = {n: torch.stack([ps[i] for ps in params]) for i, n in enumerate(_NAMES)} st["visited"] = None bank.__dict__["_fast_walk_cache"] = (key, st) st["eps"] = float(blocks[0].norm.eps) st["num_faces"] = n_faces return st
def _triangle( xb: torch.Tensor, w: Sequence[torch.Tensor], eps: float, gate: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: """TriangleBlock.forward a gruppi: xb (G, R, d), pesi (G, ...) di un blocco per gruppo.
gate (G, R, 1), router v6: xb + gate · ff(norm(xb)), il peso non tocca il residuo. """ ln_w, ln_b, w1, b1, w2, b2, wr, br = w d = xb.shape[-1] xn = F.layer_norm(xb, (d,), None, None, eps) * ln_w.unsqueeze(1) + ln_b.unsqueeze(1) hid = F.gelu(torch.baddbmm(b1.unsqueeze(1), xn, w1.transpose(1, 2))) delta = torch.baddbmm(b2.unsqueeze(1), hid, w2.transpose(1, 2)) xo = xb + delta if gate is None else xb + gate * delta return xo, torch.baddbmm(br.unsqueeze(1), xo, wr.transpose(1, 2))
def _scatter_rows(x: torch.Tensor, dest: torch.Tensor, rows: int) -> torch.Tensor: """Buffer (rows, d) con x[i] alla riga dest[i]; dest == rows è la riga di scarto.""" return x.new_zeros(rows + 1, x.shape[1]).index_copy(0, dest, x)[:rows]
def grouped_block_forward( st: Dict[str, object], x: torch.Tensor, face: torch.Tensor, active: torch.Tensor, block_rows: int = DEFAULT_BLOCK_ROWS, dense_rows: int = DEFAULT_DENSE_ROWS, gate: Optional[torch.Tensor] = None,) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """TriangleBlock della propria faccia su ogni token attivo, senza sincronizzazioni.
x (B, d), face (B,) long, active (B,) bool, gate (B, 1) opzionale (router v6: peso straight-through sul solo ramo dell'esperto, disposto come x). Ritorna (x_out, logits, counts): (B, d), (B, 4) e token attivi per faccia (F,). Sulle righe inattive x_out/logits sono finiti ma arbitrari (il chiamante li scarta con torch.where).
Nel loop originale ogni faccia fa i suoi Linear su tutte e sole le sue n_f righe, e il kernel dipende da n_f: su MPS uno per n_f <= 15 e uno per n_f >= 16, su CPU (BLAS) uno per n_f == 1 e uno per n_f >= 2; dentro lo stesso regime le righe sono bit-identiche qualunque sia n_f. Per restare bit-identici ci sono tre percorsi a forma fissa, ognuno nel regime giusto: - facce con n_f <= dense_rows (da 2 su CPU): un elemento di batch per faccia con dense_rows righe, sui pesi impilati senza gather; - su CPU, facce con un solo token: un elemento da 1 riga per faccia; - facce con n_f > dense_rows: blocchi da block_rows righe (padding solo nell'ultimo blocco di ogni faccia) con i pesi raccolti per blocco. """ b, d = x.shape n_faces = int(st["num_faces"]) s, c = int(block_rows), int(dense_rows) weights = [st[n] for n in _NAMES] # (F, ...) eps = float(st["eps"]) # type: ignore[arg-type] dev = x.device single = dev.type == "cpu" lo = 2 if single else 1
key = torch.where(active, face, torch.full_like(face, n_faces)) # inattivi → classe fittizia F face_c = key.clamp(max=n_faces - 1) onehot = (key.unsqueeze(1) == torch.arange(n_faces + 1, device=dev)).to(torch.int64) rank = onehot.cumsum(0).gather(1, key.unsqueeze(1)).squeeze(1) - 1 # posizione nella faccia counts = onehot[:, :n_faces].sum(0) n_tok = counts.gather(0, face_c) in_big = active & (n_tok > c) in_dense = active & (n_tok >= lo) & ~in_big zero = torch.zeros_like(rank) parts: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]] = [] # (maschera, x_out, logit, riga)
def _gate(dest: torch.Tensor, rows: int, shape: Tuple[int, int]) -> Optional[torch.Tensor]: return None if gate is None else _scatter_rows(gate, dest, rows).view(*shape, 1)
if c >= lo: dest = torch.where(in_dense, face * c + rank, torch.full_like(rank, n_faces * c)) xo, lg = _triangle( _scatter_rows(x, dest, n_faces * c).view(n_faces, c, d), weights, eps, _gate(dest, n_faces * c, (n_faces, c)) ) parts.append((in_dense, xo.reshape(-1, d), lg.reshape(n_faces * c, -1), torch.where(in_dense, dest, zero))) if single: alone = active & (n_tok == 1) dest = torch.where(alone, face, torch.full_like(face, n_faces)) xo, lg = _triangle( _scatter_rows(x, dest, n_faces).unsqueeze(1), weights, eps, _gate(dest, n_faces, (n_faces, 1)) ) parts.append((alone, xo.reshape(-1, d), lg.reshape(n_faces, -1), face_c))
# Limite statico: sum_f ceil(n_f / s) <= ceil(B / s) + facce con n_f > c. n_blocks = -(-b // s) + min(n_faces, b // (c + 1)) rows = n_blocks * s nblk = torch.div(torch.where(counts > c, counts, 0) + (s - 1), s, rounding_mode="floor") blk_end = nblk.cumsum(0) blk_start = blk_end - nblk dest = torch.where(in_big, blk_start.gather(0, face_c) * s + rank, torch.full_like(rank, rows)) blk_face = (blk_end.unsqueeze(0) <= torch.arange(n_blocks, device=dev).unsqueeze(1)).sum(1) blk_face = blk_face.clamp(max=n_faces - 1) # blocchi oltre il totale: righe a zero, uscite ignorate gathered = [w.index_select(0, blk_face) for w in weights] xo, lg = _triangle(_scatter_rows(x, dest, rows).view(n_blocks, s, d), gathered, eps, _gate(dest, rows, (n_blocks, s))) row = torch.where(in_big, dest, zero) out = xo.reshape(rows, d).index_select(0, row) logits = lg.reshape(rows, -1).index_select(0, row)
for mask, p_out, p_lg, p_row in parts: m = mask.unsqueeze(-1) out = torch.where(m, p_out.index_select(0, p_row), out) logits = torch.where(m, p_lg.index_select(0, p_row), logits) return out, logits, counts
def _build_paths(face0: torch.Tensor, codes: Sequence[torch.Tensor]) -> List[List[int]]: start = face0.tolist() if not codes: return [[int(f)] for f in start] table = torch.stack(list(codes), dim=1).tolist() return [[int(f)] + [c for c in row if c != -2] for f, row in zip(start, table)]
def fast_walk_token( model: nn.Module, h: torch.Tensor, bank: nn.Module, to_sphere: nn.Linear, record_path: bool = False, block_rows: Optional[int] = None, dense_rows: Optional[int] = None,) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: """Stessa semantica di CascadeMeshModel.walk_token (loop per faccia), vettorizzata.""" b = h.shape[0] face, face_oh = model.project_to_face(h, to_sphere) face0 = face max_hops = int(model.walk.max_hops) if b == 0 or max_hops <= 0: return h, (_build_paths(face0, []) if record_path else None)
st = stack_bank(bank) rows = int(block_rows or getattr(model, "fast_walk_block_rows", 0) or DEFAULT_BLOCK_ROWS) dense = dense_rows if dense_rows is not None else getattr(model, "fast_walk_dense_rows", None) dense = DEFAULT_DENSE_ROWS if dense is None else int(dense) soft = not model._hard_routing() active = torch.ones(b, dtype=torch.bool, device=h.device) codes: List[torch.Tensor] = []
for hop in range(max_hops): if hop > 0 and soft and not bool(active.any()): break out, lg, counts = grouped_block_forward(st, h, face, active, rows, dense) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] act = active.unsqueeze(-1) if face_oh is not None: # ST: w≈1 in forward; backward → face_oh → to_sphere / router w = face_oh.gather(1, face.unsqueeze(1)) h = torch.where(act, out * w, h) else: h = torch.where(act, out, h) logits = torch.where(act, lg, torch.zeros_like(lg)) next_face, exit_mask, side_oh = model._route_step(face, logits) moved = active & ~exit_mask if side_oh is not None: scale = side_oh.sum(dim=-1, keepdim=True) h = torch.where(act, h * scale, h) routed_oh = model._scatter_side_oh(face, side_oh) if face_oh is None: face_oh = routed_oh else: face_oh = torch.where(moved.unsqueeze(-1), routed_oh, face_oh) face = torch.where(moved, next_face, face) just_exit = active & exit_mask active = active & ~exit_mask if record_path: codes.append(torch.where(moved, face, torch.where(just_exit, -1, -2)))
return h, (_build_paths(face0, codes) if record_path else None)
def fast_walk_token_v6( model: nn.Module, h: torch.Tensor, bank: nn.Module, to_sphere: Optional[nn.Linear], entry_ids: Optional[torch.Tensor] = None, record_path: bool = False, block_rows: Optional[int] = None, dense_rows: Optional[int] = None, active: Optional[torch.Tensor] = None,) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: """Cammino del router v6 / hash, vettorizzato: semantica di ``CascadeMeshModel._walk_token_v6_loop``.
Nessuna sincronizzazione nel salto: senza l'uscita anticipata su ``active.any()`` i salti dopo che tutti i token sono usciti sono no-op. ``active`` opzionale (B,): token inattivi (pad/unk stadi 2/3) saltano le FFN; in ``record_path`` la faccia d'ingresso è ``-1``. """ b = h.shape[0] face, w = model._v6_entry(h, bank, to_sphere, entry_ids) max_hops = int(model.walk.max_hops) if active is None: active = torch.ones(b, dtype=torch.bool, device=h.device) else: active = active.to(device=h.device, dtype=torch.bool) face0 = torch.where(active, face, torch.full_like(face, -1)) if b == 0 or max_hops <= 0: return h, (_build_paths(face0, []) if record_path else None)
st = stack_bank(bank) rows = int(block_rows or getattr(model, "fast_walk_block_rows", 0) or DEFAULT_BLOCK_ROWS) dense = dense_rows if dense_rows is not None else getattr(model, "fast_walk_dense_rows", None) dense = DEFAULT_DENSE_ROWS if dense is None else int(dense) codes: List[torch.Tensor] = []
for _ in range(max_hops): out, lg, counts = grouped_block_forward(st, h, face, active, rows, dense, gate=w) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] act = active.unsqueeze(-1) h = torch.where(act, out, h) logits = torch.where(act, lg, torch.zeros_like(lg)) next_face, exit_mask, w = model._v6_route(face, logits) moved = active & ~exit_mask face = torch.where(moved, next_face, face) just_exit = active & exit_mask active = active & ~exit_mask if record_path: codes.append(torch.where(moved, face, torch.where(just_exit, -1, -2)))
return h, (_build_paths(face0, codes) if record_path else None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""Rete neurale su mesh geodetica sferica (PyTorch).
- TriangleBlock: pesi locali + router ternario (3 lati)- CausalAttnBlock: self-attention causale + FF (contesto temporale)- SphericalMeshModel: emb → CausalAttn × N → walk mesh batched → LM head- Pesi faccia impacchettati a coppie (pair packing) per buffer contigui GEMM-friendly"""
from __future__ import annotations
from dataclasses import dataclassfrom typing import List, Optional, Tuple
import mathimport numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from mesh_topology import GeodesicMesh, build_geodesic_mesh, nearest_face
@dataclassclass WalkConfig: max_hops: int = 8 # Se la probabilità del “exit” (soft) supera la soglia, si ferma prima exit_threshold: float = 0.55 # Temperatura del router ternario router_temperature: float = 1.0 # Se True, usa argmax (discreto); altrimenti Gumbel-Softmax straight-through hard_routing: bool = True
class TriangleBlock(nn.Module): """Micro-blocco su una faccia: MLP locale + logits verso 3 lati + exit."""
def __init__(self, d_model: int, d_hidden: Optional[int] = None): super().__init__() h = d_hidden or d_model self.norm = nn.LayerNorm(d_model) self.ff = nn.Sequential( nn.Linear(d_model, h), nn.GELU(), nn.Linear(h, d_model), ) # 3 lati + 1 “esci / emetti” self.router = nn.Linear(d_model, 4)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: """ x: (..., d) returns: (x_out, router_logits) con logits shape (..., 4) """ h = self.ff(self.norm(x)) x_out = x + h logits = self.router(x_out) return x_out, logits
class PairedFaceBank(nn.Module): """ Banca pesi: per ogni coppia di facce adiacenti memorizza 2 TriangleBlock in un modulo ModuleList, con indici face→block per lookup O(1). I parametri di ogni coppia restano contigui nel ModuleList (ordine packing). """
def __init__(self, mesh: GeodesicMesh, d_model: int, d_hidden: Optional[int] = None): super().__init__() self.num_faces = mesh.num_faces self.register_buffer("adjacency", torch.from_numpy(mesh.adjacency.astype(np.int64))) self.register_buffer("pairs", torch.from_numpy(mesh.pairs.astype(np.int64)))
# face_id → index nel ModuleList `blocks` face_to_slot = np.full(mesh.num_faces, -1, dtype=np.int64) blocks: List[TriangleBlock] = []
for fa, fb in mesh.pairs: face_to_slot[int(fa)] = len(blocks) blocks.append(TriangleBlock(d_model, d_hidden)) face_to_slot[int(fb)] = len(blocks) blocks.append(TriangleBlock(d_model, d_hidden))
for u in mesh.unpaired: face_to_slot[int(u)] = len(blocks) blocks.append(TriangleBlock(d_model, d_hidden))
self.blocks = nn.ModuleList(blocks) self.register_buffer("face_to_slot", torch.from_numpy(face_to_slot))
def forward_face(self, face_id: int, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: slot = int(self.face_to_slot[face_id].item()) return self.blocks[slot](x)
class CausalSelfAttention(nn.Module): """Multi-head self-attention con maschera causale (lookahead vietato)."""
def __init__(self, d_model: int, n_heads: int, dropout: float = 0.0): super().__init__() if d_model % n_heads != 0: raise ValueError(f"d_model={d_model} non divisibile per n_heads={n_heads}") self.d_model = d_model self.n_heads = n_heads self.head_dim = d_model // n_heads self.qkv = nn.Linear(d_model, 3 * d_model, bias=False) self.proj = nn.Linear(d_model, d_model, bias=False) self.attn_drop = nn.Dropout(dropout) self.resid_drop = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: (B, T, d) b, t, _ = x.shape qkv = self.qkv(x).view(b, t, 3, self.n_heads, self.head_dim) qkv = qkv.permute(2, 0, 3, 1, 4) # (3, B, H, T, hd) q, k, v = qkv[0], qkv[1], qkv[2]
scale = 1.0 / math.sqrt(self.head_dim) # PyTorch SDPA con is_causal=True (Flash/mem-efficient quando disponibili) y = F.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.attn_drop.p if self.training else 0.0, is_causal=True, scale=scale, ) # (B, H, T, hd) y = y.transpose(1, 2).contiguous().view(b, t, self.d_model) return self.resid_drop(self.proj(y))
class CausalAttnBlock(nn.Module): """Pre-norm: LayerNorm → causal attn → residual → LayerNorm → FF → residual."""
def __init__( self, d_model: int, n_heads: int, d_ff: Optional[int] = None, dropout: float = 0.0, ): super().__init__() h = d_ff or (4 * d_model) self.ln1 = nn.LayerNorm(d_model) self.attn = CausalSelfAttention(d_model, n_heads, dropout=dropout) self.ln2 = nn.LayerNorm(d_model) self.ff = nn.Sequential( nn.Linear(d_model, h), nn.GELU(), nn.Linear(h, d_model), nn.Dropout(dropout), )
def forward(self, x: torch.Tensor) -> torch.Tensor: x = x + self.attn(self.ln1(x)) x = x + self.ff(self.ln2(x)) return x
def _default_n_heads(d_model: int) -> int: for h in (8, 4, 2, 1): if d_model % h == 0: return h return 1
class SphericalMeshModel(nn.Module): """ LM: token → emb (+pos) → CausalAttn × N → walk mesh parallelo (B*T) → vocab.
Contesto temporale via attenzione causale (no carry sequenziale). """
def __init__( self, vocab_size: int, d_model: int = 64, frequency: int = 2, walk: Optional[WalkConfig] = None, d_hidden: Optional[int] = None, n_attn_layers: int = 2, n_heads: Optional[int] = None, max_seq_len: int = 512, use_mesh_walk: bool = True, attn_dropout: float = 0.0, compass_spiral: bool = False, ): super().__init__() self.compass_spiral = bool(compass_spiral) self.mesh: GeodesicMesh = build_geodesic_mesh( frequency, compass_spiral=self.compass_spiral ) self.walk = walk or WalkConfig() self.d_model = d_model self.vocab_size = vocab_size self.n_attn_layers = int(n_attn_layers) self.use_mesh_walk = bool(use_mesh_walk) self.max_seq_len = int(max_seq_len) heads = int(n_heads) if n_heads is not None else _default_n_heads(d_model)
self.tok_emb = nn.Embedding(vocab_size, d_model) nn.init.normal_(self.tok_emb.weight, mean=0.0, std=0.02) self.pos_emb = nn.Embedding(self.max_seq_len, d_model) nn.init.normal_(self.pos_emb.weight, mean=0.0, std=0.02)
self.attn_blocks = nn.ModuleList( [ CausalAttnBlock(d_model, heads, d_ff=d_hidden or (4 * d_model), dropout=attn_dropout) for _ in range(self.n_attn_layers) ] )
# Proietta embedding → direzione 3D sulla sfera (faccia di ingresso) self.to_sphere = nn.Linear(d_model, 3) self.bank = PairedFaceBank(self.mesh, d_model, d_hidden) self.final_norm = nn.LayerNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) # embedding tied (come goTommy2) self.lm_head.weight = self.tok_emb.weight self.emb_scale = d_model**-0.5
# Buffer geometria per nearest face su GPU/CPU self.register_buffer( "centroids", torch.from_numpy(self.mesh.face_centroids.astype(np.float32)), ) self.register_buffer( "adjacency", torch.from_numpy(self.mesh.adjacency.astype(np.int64)), )
def project_to_face(self, h: torch.Tensor) -> torch.Tensor: """h (..., d) → face ids (...)""" direction = self.to_sphere(h) direction = F.normalize(direction, dim=-1) # (..., F) scores = direction @ self.centroids.T return scores.argmax(dim=-1)
def _route_step( self, face: torch.Tensor, logits: torch.Tensor, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ face: (B,) long — faccia corrente logits: (B, 4) — 3 lati + exit returns: next_face (B,), exit_mask (B,) bool, side_choice (B,) in {0,1,2,-1} """ temp = max(self.walk.router_temperature, 1e-6) probs = F.softmax(logits / temp, dim=-1) exit_prob = probs[:, 3] side_probs = probs[:, :3]
if self.walk.hard_routing: side = side_probs.argmax(dim=-1) else: # Gumbel-softmax straight-through sui 3 lati side = F.gumbel_softmax(logits[:, :3] / temp, hard=True, dim=-1).argmax(dim=-1)
exit_mask = exit_prob >= self.walk.exit_threshold # lookup vettoriale: adjacency[face, side] next_face = self.adjacency[face.long(), side.long()] side_out = torch.where(exit_mask, torch.full_like(side, -1), side) return next_face, exit_mask, side_out
def walk_token( self, h: torch.Tensor, start_face: Optional[torch.Tensor] = None, record_path: bool = False, ) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: """ h: (B, d) stato iniziale token — tipicamente B*T flattened returns: h_final (B, d), paths opzionale list per batch """ b = h.shape[0] face = start_face if start_face is not None else self.project_to_face(h) paths: Optional[List[List[int]]] = [[int(face[i].item())] for i in range(b)] if record_path else None active = torch.ones(b, dtype=torch.bool, device=h.device)
for _ in range(self.walk.max_hops): if not active.any(): break # Esegue i blocchi per-faccia (batch misto: loop su facce uniche) logits = h.new_zeros(b, 4) h_new = h.clone() unique_faces = face[active].unique() for f_id in unique_faces.tolist(): mask = active & (face == f_id) if not mask.any(): continue out, lg = self.bank.forward_face(int(f_id), h[mask]) h_new[mask] = out logits[mask] = lg h = h_new
next_face, exit_mask, _ = self._route_step(face, logits) # Solo i token ancora attivi possono uscire / muoversi moved = active & ~exit_mask face = torch.where(moved, next_face, face) just_exit = active & exit_mask active = active & ~exit_mask
if record_path and paths is not None: for i in range(b): if moved[i]: paths[i].append(int(face[i].item())) elif just_exit[i]: paths[i].append(-1) # sentinel exit
return h, paths
def forward( self, input_ids: torch.Tensor, record_path: bool = False, ) -> Tuple[torch.Tensor, Optional[List[List[List[int]]]]]: """ input_ids: (B, T) returns: logits (B, T, V), paths [B][T][hops] se richiesto
Pipeline: emb(+pos) → CausalAttnBlock × N → walk_token(B*T) → final_norm → lm_head """ b, t = input_ids.shape if t > self.max_seq_len: raise ValueError(f"seq_len={t} > max_seq_len={self.max_seq_len}")
pos = torch.arange(t, device=input_ids.device).unsqueeze(0) # (1, T) h = self.tok_emb(input_ids) * self.emb_scale + self.pos_emb(pos)
for block in self.attn_blocks: h = block(h) # (B, T, d)
paths: Optional[List[List[List[int]]]] = None if self.use_mesh_walk: flat = h.reshape(b * t, self.d_model) flat_out, paths_flat = self.walk_token(flat, record_path=record_path) h = flat_out.view(b, t, self.d_model) if record_path and paths_flat is not None: # paths_flat[bi*T + ti] → paths[bi][ti] paths = [ [paths_flat[bi * t + ti] for ti in range(t)] for bi in range(b) ]
h = self.final_norm(h) logits = self.lm_head(h) # soft-cap: evita CE esplosa con residual walk + tied emb logits = 30.0 * torch.tanh(logits / 30.0) return logits, paths
def count_parameters(model: nn.Module) -> int: return sum(p.numel() for p in model.parameters() if p.requires_grad)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593"""Cascade a 3 stadi in SERIE (non stream paralleli).
Architettura (allineata alla timeline pezzi, grain più fine):
pezzi_ids → emb_v1 (+pos) → CausalAttn_1 → mesh_walk_1 (=h1) → LN(proj_12(h1)) + LN(emb_v2)[*] → fuse_norm2 → mesh_walk_2 (=h2) → LN(proj_23(h2)) + LN(emb_v3)[*] → fuse_norm3 → mesh_walk_3 (=h3) → Drop0.1(n1(h1))+n2(h2)+n3(h3) → CausalAttn_2 → final_norm → lm_head (tied weight + bias)
[*] v8.1 ``fuse_mask_pad``: su pad/unk V2/V3 l'addendo emb è azzerato (× active); ``mask_pad_stages`` già saltava solo walk/piramide.
Le sequenze parole/unioni sono espanse sulla lunghezza pezzi (pad dove nonc'è parola/unione). Obiettivo LM: next-token sui pezzi (unità di decode).
Router v6 (``router_v6=True``, default spento = v5 invariato), per stadio: - ingresso: faccia = argmax(coseni + face_bias) in training e in eval; face_bias (buffer, niente gradiente) segue il Loss-Free Balancing (``update_face_bias`` dopo ogni step); peso straight-through w = p_f / sg(p_f) con p = softmax(coseni · exp(logit_scale)), logit_scale appresa (init ln 10, clamp ≤ ln 100); - ogni salto: x + w · ff(norm(x)), il peso non tocca mai il residuo; - porte: come v5 (Gumbel-ST in training, argmax in eval); - uscita: decisione dura a soglia nel forward; il peso del salto successivo è w_porta · p_stay / sg(p_stay), p_stay = 1 − probs[:, uscita], così il logit di uscita riceve gradiente dal contributo dell'esperto che segue.``hash_routing=True``: come v6 ma faccia d'ingresso fissa per id del token(pezzo / parola / unione nei tre stadi, ``hash_faces``), senza to_sphere,logit_scale né face_bias.``no_walk=True`` (solo v6/hash, ``max_hops=1``): controllo del cammino, ognitoken usa solo il blocco della faccia d'ingresso in ogni stadio; dopo quelblocco escono tutti e le porte non vengono valutate (niente rumore Gumbel).``walk_to_center=True`` (v10 Spoke-to-Hub, solo hash, ``H_max∈{2,3}``):ingresso Zipf/hash invariato (periferia = ID); dopo ogni blocco il tokensegue ``parent_face[f]`` verso un **anello polare hub** di ``k_core≈15–20``facce (non una sola faccia). Gate (Argon):hop0 residuo pieno (come v8.1, ``g=None``);hop≥1 ``g = (c + (1−c)·σ(Linear(x))) / √H_max`` con ``c=center_mix``(default 0.25, formula liscia). Bias gate init 0. Niente Gumbel;pad/unk = 0 hop (mask-pad). Train==eval path.La piramide (se attiva) resta sulla faccia d'ingresso Zipf.``sector_mix=True`` (v11, implica ``walk_to_center``): stesso albero parent→hub,ma hop≥1 non è più spoke sottile solo-parent: ``x ← x + g · mean_{f∈settore(entry)}(Δ_f)``dove il settore è lo **spicchio azimutale** di ``K≈sector_frac·F`` facce(default 1/4) intorno all'ingresso Zipf. Hop0 resta solo faccia entry a peso 1.0.Niente layer attention, niente Gumbel, Zipf classico (no multi-slot).``sheet_mix=True`` (v13 Sheet-Mix / v14 pezzi-only, implica ``sector_mix`` path): stesso hop0/hop≥1e ``_apply_sector_mean``, ma il buffer ``sector_faces`` è ``(F, K_eff=12)`` =3 fogli complementari (cerchi massimi a 0°/90°/±45°, esclusa l'orientazione``spiral_rank % 4``) × ``m=4`` facce equidistanti per foglio (ponte polo-a-polo).Iso-param rispetto a v11 (solo indici; weight sharing invariato).**Storico (v13–v18, default):** hop≥1 = media Δ sui blocchi delle K_eff facce dei fogli(cross-face). **``sheet_entry_only=True`` (v19):** hop≥1 applica solo il blocco dellafaccia d'ingresso Zipf (niente media su altre facce); i fogli non toccano altri esperti.Il cammino parent→hub resta per lo stop; piramide invariata sull'entry.``pyramid_center=True`` (solo hash, «sfera a spicchi piramidali»): dopo ilcammino di ogni stadio il token scende nella piramide della sua facciad'ingresso, un passaggio d → d/2 con proiezione condivisa e guadagno/spostamentoper faccia, e arriva al centro, un MLP denso condiviso dallo stadio; l'uscitadel centro si somma al ramo della faccia (``PyramidCenter``)."""from __future__ import annotations
import mathfrom collections import dequefrom pathlib import Pathfrom typing import List, Optional, Tuple, Union
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from fast_walk import ( _build_paths, fast_walk_token, fast_walk_token_v6, grouped_block_forward, stack_bank,)from geodesic_network import ( CausalAttnBlock, PairedFaceBank, WalkConfig, _default_n_heads,)from mesh_topology import GeodesicMesh, build_geodesic_mesh, icosahedron_vertices
DEFAULT_K_CORE = 18 # anello polare hub @ F=180 (~10%); clamp a [15, 20] tipicoV10_HOPS_DEFAULT = 2 # H_max=2; CLI può alzare a 3DEFAULT_CENTER_MIX = 0.25 # hop≥1: g=(c+(1-c)σ(Wx))/√H; hop0=pienoDEFAULT_SECTOR_FRAC = 0.25 # v11: fetta azimutale ~1/4 di F (~45 @ F=180)DEFAULT_EDGE_NB_TAU = 4.0 # v12: softmax(τ · z_polo) sui 3 latiDEFAULT_SHEET_M = 4 # v13: facce per foglio complementare (K_eff = 3·m = 12)
def build_face_edge_ids(faces: np.ndarray) -> Tuple[np.ndarray, int]: """``face_edges[f, i]`` = id unico del lato i; ``E = 3F/2`` su mesh chiusa.""" fcount = int(faces.shape[0]) edge_to_id: dict = {} face_edges = np.zeros((fcount, 3), dtype=np.int64) next_id = 0 for fi, (a, b, c) in enumerate(faces): for li, (u, v) in enumerate(((int(a), int(b)), (int(b), int(c)), (int(c), int(a)))): key = (u, v) if u < v else (v, u) eid = edge_to_id.get(key) if eid is None: eid = next_id edge_to_id[key] = eid next_id += 1 face_edges[fi, li] = eid return face_edges, next_id
def build_edge_neighbor_weights( adjacency: np.ndarray, face_centroids: np.ndarray, tau: float = DEFAULT_EDGE_NB_TAU,) -> np.ndarray: """Pesi (F, 3) sui vicini di lato: softmax(τ · z_polo[nb]), verso il Polo Nord.""" z = face_centroids[:, 2].astype(np.float64) scores = z[adjacency] * float(tau) # (F, 3) scores = scores - scores.max(axis=1, keepdims=True) e = np.exp(scores) return (e / e.sum(axis=1, keepdims=True)).astype(np.float32)
def build_spoke_hub_parent( adjacency: np.ndarray, face_centroids: np.ndarray, k_core: int = DEFAULT_K_CORE,) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Albero Spoke→Hub: ``parent[f]`` verso l'anello polare di ``k_core`` facce.
Hub = top-``k_core`` facce per proiezione sull'asse polare icosaedrico (vertice 0, stesso di ``compass_spiral``). BFS multi-sorgente: ogni faccia non-hub punta al vicino più vicino all'anello; sulle hub ``parent[h]=h``.
Ritorna ``(parent_face (F,), is_hub (F,) bool, hub_ids (K,))``. """ n = int(adjacency.shape[0]) k = int(max(1, min(int(k_core), n))) pole = icosahedron_vertices()[0] u3 = pole / np.linalg.norm(pole) z = face_centroids.astype(np.float64) @ u3 hub_ids = np.argsort(-z)[:k].astype(np.int64) is_hub = np.zeros(n, dtype=bool) is_hub[hub_ids] = True parent = np.arange(n, dtype=np.int64) dist = np.full(n, -1, dtype=np.int32) q: deque = deque() for h in hub_ids.tolist(): dist[h] = 0 parent[h] = h q.append(h) while q: f = q.popleft() for nb in adjacency[f].tolist(): nb = int(nb) if dist[nb] < 0: dist[nb] = int(dist[f]) + 1 parent[nb] = f q.append(nb) if int((dist < 0).sum()) > 0: raise RuntimeError("spoke-hub: grafo facce non connesso") return parent, is_hub, hub_ids
def build_azimuth_sectors( face_centroids: np.ndarray, sector_frac: float = DEFAULT_SECTOR_FRAC,) -> np.ndarray: """Settore azimutale per faccia: spicchio verso il polo (asse icosaedrico 0).
Per ogni faccia ``e``, le ``K = max(1, round(sector_frac · F))`` facce con minore distanza circolare in azimut intorno al polo (stesso vertice 0 di ``build_spoke_hub_parent`` / ``compass_spiral``). Con ``sector_frac=0.25`` e F=180 → K≈45 (~1/4 di sfera in longitudine, tutte le latitudini).
Ritorna ``sector_faces (F, K)`` int64; ``sector_faces[e, 0] == e``. """ if not (0.0 < float(sector_frac) <= 1.0): raise ValueError("sector_frac deve essere in (0, 1]") cents = face_centroids.astype(np.float64) n = int(cents.shape[0]) k = int(max(1, min(n, round(float(sector_frac) * n)))) pole = icosahedron_vertices()[0] u3 = pole / np.linalg.norm(pole) # base ortonormale nel piano equatoriale ref = np.array([1.0, 0.0, 0.0], dtype=np.float64) if abs(float(ref @ u3)) > 0.9: ref = np.array([0.0, 1.0, 0.0], dtype=np.float64) e1 = ref - (ref @ u3) * u3 e1 = e1 / np.linalg.norm(e1) e2 = np.cross(u3, e1) xy = cents - np.outer(cents @ u3, u3) x = xy @ e1 y = xy @ e2 az = np.arctan2(y, x) # (-π, π]; poli (xy≈0) → 0 # distanza circolare |Δφ| ∈ [0, π] dphi = np.abs(az[:, None] - az[None, :]) dphi = np.minimum(dphi, 2.0 * np.pi - dphi) # self sempre in slot 0 (al polo più facce condividono φ≈0 → argsort non basta) np.fill_diagonal(dphi, -1.0) order = np.argsort(dphi, axis=1, kind="mergesort")[:, :k].astype(np.int64) return order
def build_complementary_sheets( face_centroids: np.ndarray, spiral_rank: Optional[np.ndarray] = None, m_per_sheet: int = DEFAULT_SHEET_M,) -> np.ndarray: """v13 Sheet-Mix: 3 fogli complementari × m facce su cerchi massimi → (F, 3m).
Per ogni faccia ``f`` costruisce la base tangente ``(t_par, t_mer)`` rispetto al polo icosaedrico (vertice 0). Le 4 normali ai cerchi massimi a 0° / 90° / +45° / −45° sono::
N_V = t_par (meridiano, polo↔polo) N_H = t_mer (ortogonale in f) N_+ = (t_par+t_mer)/√2 N_- = (t_par-t_mer)/√2
L'orientazione propria è ``spiral_rank[f] % 4`` (se assente → 0); si usano i **3 fogli complementari**. Su ciascun foglio si campionano ``m`` facce equidistanti sul cerchio massimo (θ = 2πk/m), incluso il ponte fronte/retro e polo-a-polo. Drop-in su ``sector_faces`` / ``_apply_sector_mean``. """ m = int(m_per_sheet) if m < 1: raise ValueError("m_per_sheet deve essere >= 1") cents = face_centroids.astype(np.float64) n = int(cents.shape[0]) # normalizza (centroidi mesh già unitari, ma per sicurezza) norms = np.linalg.norm(cents, axis=1, keepdims=True) cents = cents / np.maximum(norms, 1e-12) pole = icosahedron_vertices()[0] u3 = pole / np.linalg.norm(pole) # asse equatoriale fisso per i poli (stesso schema di build_azimuth_sectors) ref = np.array([1.0, 0.0, 0.0], dtype=np.float64) if abs(float(ref @ u3)) > 0.9: ref = np.array([0.0, 1.0, 0.0], dtype=np.float64) e1 = ref - (ref @ u3) * u3 e1 = e1 / np.linalg.norm(e1)
if spiral_rank is None: orient = np.zeros(n, dtype=np.int64) else: sr = np.asarray(spiral_rank, dtype=np.int64).reshape(-1) if sr.shape[0] != n: raise ValueError(f"spiral_rank len={sr.shape[0]} ≠ F={n}") orient = np.mod(sr, 4).astype(np.int64)
out = np.empty((n, 3 * m), dtype=np.int64) # precompute all pairwise cosines for nearest-face lookup # (F=180 → F² cheap) for f in range(n): c = cents[f] # t_par ∝ u3 × c (parallelo); ai poli |u3×c|→0 → e1 t_par = np.cross(u3, c) tp_n = float(np.linalg.norm(t_par)) if tp_n < 1e-8: t_par = e1.copy() else: t_par = t_par / tp_n t_mer = np.cross(c, t_par) tm_n = float(np.linalg.norm(t_mer)) if tm_n < 1e-8: t_mer = np.cross(t_par, u3) t_mer = t_mer / max(float(np.linalg.norm(t_mer)), 1e-12) else: t_mer = t_mer / tm_n normals = ( t_par, # 0 Verticale t_mer, # 1 Orizzontale (t_par + t_mer) / math.sqrt(2.0), # 2 D+ (t_par - t_mer) / math.sqrt(2.0), # 3 D- ) own = int(orient[f]) comps = [s for s in range(4) if s != own] col = 0 for s in comps: N = normals[s] # base ortonormale nel piano del cerchio massimo (⊥ N), con ea ≈ c ea = c - (c @ N) * N ea_n = float(np.linalg.norm(ea)) if ea_n < 1e-8: # c ∥ N (non dovrebbe succedere: N costruita ⊥ c) ea = t_par if s != 0 else t_mer ea = ea - (ea @ N) * N ea = ea / max(float(np.linalg.norm(ea)), 1e-12) else: ea = ea / ea_n eb = np.cross(N, ea) eb = eb / max(float(np.linalg.norm(eb)), 1e-12) for k in range(m): theta = 2.0 * math.pi * float(k) / float(m) target = math.cos(theta) * ea + math.sin(theta) * eb # faccia col centroide più allineato a target scores = cents @ target out[f, col] = int(np.argmax(scores)) col += 1 # slot 0 = entry (coerente con build_azimuth_sectors) out[f, 0] = f return out
V6_LOGIT_SCALE_INIT = math.log(10.0)V6_LOGIT_SCALE_MAX = math.log(100.0)V6_BIAS_RATE = 1e-3_HASH_SALTS = (0x9E3779B9, 0x85EBCA6B, 0xC2B2AE35)PYRAMID_SEED_OFFSET = 7919 # seme del generatore delle piramidi = seme torch + offset
def _lowbias32(x: int) -> int: x &= 0xFFFFFFFF x ^= x >> 16 x = (x * 0x7FEB352D) & 0xFFFFFFFF x ^= x >> 15 x = (x * 0x846CA68B) & 0xFFFFFFFF x ^= x >> 16 return x
def hash_faces(vocab_size: int, n_faces: int, stage: int) -> torch.Tensor: """Faccia d'ingresso fissa per id (--hash-routing): lowbias32(id XOR sale dello stadio) mod n_faces.""" salt = _HASH_SALTS[stage - 1] return torch.tensor([_lowbias32(i ^ salt) % n_faces for i in range(vocab_size)], dtype=torch.long)
class PyramidCenter(nn.Module): """Piramidi sotto le facce di uno stadio e centro condiviso (--pyramid-center).
Discesa dalla faccia f: z = (1 + face_gain[f]) ⊙ down(norm(x)) + face_shift[f], d → d_narrow; la proiezione propria della faccia è diag(1 + face_gain[f]) · down. Centro, uguale per tutti i token: c = up(GELU(inner(z))), d_narrow → d_hidden → d. Uscita x + c; up parte da zero, quindi all'inizio l'uscita è x. """
def __init__( self, d_model: int, n_faces: int, d_narrow: int, d_hidden: int, generator: Optional[torch.Generator] = None ): super().__init__() self.norm = nn.LayerNorm(d_model) self.down = nn.Linear(d_model, d_narrow, bias=False) self.face_gain = nn.Parameter(torch.zeros(n_faces, d_narrow)) self.face_shift = nn.Parameter(torch.zeros(n_faces, d_narrow)) self.center = nn.Sequential(nn.Linear(d_narrow, d_hidden), nn.GELU(), nn.Linear(d_hidden, d_model)) self.reset_parameters(generator)
def reset_parameters(self, generator: Optional[torch.Generator] = None) -> None: """Init di nn.Linear per down e per il primo strato del centro; ultima proiezione, guadagni e spostamenti a zero.""" for lin in (self.down, self.center[0]): nn.init.kaiming_uniform_(lin.weight, a=math.sqrt(5), generator=generator) if lin.bias is not None: bound = 1.0 / math.sqrt(lin.in_features) nn.init.uniform_(lin.bias, -bound, bound, generator=generator) for p in (self.center[2].weight, self.center[2].bias, self.face_gain, self.face_shift): nn.init.zeros_(p) self.norm.reset_parameters()
def forward(self, x: torch.Tensor, face: torch.Tensor) -> torch.Tensor: z = self.down(self.norm(x)) z = z * (1.0 + F.embedding(face, self.face_gain)) + F.embedding(face, self.face_shift) return x + self.center(z)
class HexPyramidCenter(nn.Module): """v9: guadagno/spostamento per **vertice** della mesh; media sui 3 vertici della faccia.
Stessa discesa d → d_narrow e centro MLP condiviso di ``PyramidCenter``, ma i parametri locali vivono sui V vertici (esagoni/pentagoni duali) invece che sulle F facce: facce adiacenti condividono i vertici e quindi parte della piramide. """
def __init__( self, d_model: int, n_vertices: int, face_vertices: torch.Tensor, d_narrow: int, d_hidden: int, generator: Optional[torch.Generator] = None, ): super().__init__() if face_vertices.ndim != 2 or face_vertices.shape[1] != 3: raise ValueError(f"face_vertices deve essere (F, 3), got {tuple(face_vertices.shape)}") self.norm = nn.LayerNorm(d_model) self.down = nn.Linear(d_model, d_narrow, bias=False) self.vertex_gain = nn.Parameter(torch.zeros(n_vertices, d_narrow)) self.vertex_shift = nn.Parameter(torch.zeros(n_vertices, d_narrow)) self.center = nn.Sequential(nn.Linear(d_narrow, d_hidden), nn.GELU(), nn.Linear(d_hidden, d_model)) self.register_buffer("face_vertices", face_vertices.long().contiguous()) self.reset_parameters(generator)
def reset_parameters(self, generator: Optional[torch.Generator] = None) -> None: for lin in (self.down, self.center[0]): nn.init.kaiming_uniform_(lin.weight, a=math.sqrt(5), generator=generator) if lin.bias is not None: bound = 1.0 / math.sqrt(lin.in_features) nn.init.uniform_(lin.bias, -bound, bound, generator=generator) for p in (self.center[2].weight, self.center[2].bias, self.vertex_gain, self.vertex_shift): nn.init.zeros_(p) self.norm.reset_parameters()
def forward(self, x: torch.Tensor, face: torch.Tensor) -> torch.Tensor: z = self.down(self.norm(x)) verts = self.face_vertices[face] # (..., 3) g = F.embedding(verts, self.vertex_gain).mean(dim=-2) s = F.embedding(verts, self.vertex_shift).mean(dim=-2) z = z * (1.0 + g) + s return x + self.center(z)
class SharedEdgeVertexPyramid(nn.Module): """v12: face_gain privato + lati (E) e vertici (V) condivisi + 1 centro MLP.
``z`` modulato da ``1 + face + 0.5·mean(edge) + 0.5·mean(vertex)`` (edge/vert init 0). """
def __init__( self, d_model: int, n_faces: int, n_edges: int, n_vertices: int, face_edges: torch.Tensor, face_vertices: torch.Tensor, d_narrow: int, d_hidden: int, generator: Optional[torch.Generator] = None, ): super().__init__() if face_edges.ndim != 2 or face_edges.shape[1] != 3: raise ValueError(f"face_edges deve essere (F, 3), got {tuple(face_edges.shape)}") if face_vertices.ndim != 2 or face_vertices.shape[1] != 3: raise ValueError(f"face_vertices deve essere (F, 3), got {tuple(face_vertices.shape)}") self.norm = nn.LayerNorm(d_model) self.down = nn.Linear(d_model, d_narrow, bias=False) self.face_gain = nn.Parameter(torch.zeros(n_faces, d_narrow)) self.face_shift = nn.Parameter(torch.zeros(n_faces, d_narrow)) self.edge_gain = nn.Parameter(torch.zeros(n_edges, d_narrow)) self.edge_shift = nn.Parameter(torch.zeros(n_edges, d_narrow)) self.vertex_gain = nn.Parameter(torch.zeros(n_vertices, d_narrow)) self.vertex_shift = nn.Parameter(torch.zeros(n_vertices, d_narrow)) self.center = nn.Sequential(nn.Linear(d_narrow, d_hidden), nn.GELU(), nn.Linear(d_hidden, d_model)) self.register_buffer("face_edges", face_edges.long().contiguous()) self.register_buffer("face_vertices", face_vertices.long().contiguous()) self.reset_parameters(generator)
def reset_parameters(self, generator: Optional[torch.Generator] = None) -> None: for lin in (self.down, self.center[0]): nn.init.kaiming_uniform_(lin.weight, a=math.sqrt(5), generator=generator) if lin.bias is not None: bound = 1.0 / math.sqrt(lin.in_features) nn.init.uniform_(lin.bias, -bound, bound, generator=generator) for p in ( self.center[2].weight, self.center[2].bias, self.face_gain, self.face_shift, self.edge_gain, self.edge_shift, self.vertex_gain, self.vertex_shift, ): nn.init.zeros_(p) self.norm.reset_parameters()
def forward(self, x: torch.Tensor, face: torch.Tensor) -> torch.Tensor: z = self.down(self.norm(x)) f = face.long() eg = F.embedding(self.face_edges[f], self.edge_gain).mean(dim=-2) es = F.embedding(self.face_edges[f], self.edge_shift).mean(dim=-2) vg = F.embedding(self.face_vertices[f], self.vertex_gain).mean(dim=-2) vs = F.embedding(self.face_vertices[f], self.vertex_shift).mean(dim=-2) g = F.embedding(f, self.face_gain) + 0.5 * eg + 0.5 * vg s = F.embedding(f, self.face_shift) + 0.5 * es + 0.5 * vs z = z * (1.0 + g) + s return x + self.center(z)
def pyramid_kwargs(blob: dict) -> dict: """Argomenti di CascadeMeshModel per la piramide, dai metadati di un checkpoint (assenti = spenta).""" if not blob.get("pyramid_center") and not blob.get("hex_pyramid") and not blob.get("shared_edges_verts"): return {} cfg = blob.get("pyramid_config") or {} out: dict = { "pyramid_center": True, "pyramid_narrow": cfg.get("d_stretto"), "pyramid_hidden": cfg.get("d_centro"), } if blob.get("hex_pyramid"): out["hex_pyramid"] = True if blob.get("shared_edges_verts"): out["shared_edges_verts"] = True return out
def v8_kwargs(blob: dict) -> dict: """Argomenti v8.x di CascadeMeshModel dai metadati checkpoint (assenti = default v7).
Lo zipf-hash è già nei buffer ``bank.hash_face`` dello state_dict: non serve ``zipf_hash_path`` in eval.
``fuse_mask_pad`` (v8.1): solo se presente nel blob — i ckpt v8.0 senza chiave restano senza mask sull'addendo emb in fuse (come in training). """ out: dict = {} if blob.get("d_hidden") is not None: out["d_hidden"] = int(blob["d_hidden"]) de = blob.get("d_emb_v23") if de is not None and int(de) > 0: out["d_emb_v23"] = int(de) if blob.get("inter_stage_attn"): out["inter_stage_attn"] = True if blob.get("mask_pad_stages"): out["mask_pad_stages"] = True out["pad_id_v2"] = int(blob.get("pad_id_v2", 3)) out["unk_id_v2"] = int(blob.get("unk_id_v2", 4)) out["pad_id_v3"] = int(blob.get("pad_id_v3", 3)) out["unk_id_v3"] = int(blob.get("unk_id_v3", 4)) if blob.get("fuse_mask_pad"): out["fuse_mask_pad"] = True if blob.get("multi_slot_v1"): out["multi_slot_v1"] = True return out
def _make_emb(vocab: int, d_emb: int, d_model: int) -> nn.Module: """Embedding pieno a ``d_model``, oppure ``Embedding(d_emb)→Linear→d_model``.""" if d_emb >= d_model: emb = nn.Embedding(vocab, d_model) nn.init.normal_(emb.weight, mean=0.0, std=0.02) return emb emb = nn.Embedding(vocab, d_emb) proj = nn.Linear(d_emb, d_model, bias=False) nn.init.normal_(emb.weight, mean=0.0, std=0.02) nn.init.normal_(proj.weight, mean=0.0, std=0.02) return nn.Sequential(emb, proj)
class CascadeMeshModel(nn.Module): """Tre emb + tre mesh in catena (default), oppure solo-V1 (v1_only=True)."""
def __init__( self, vocab_pezzi: int, vocab_parole: int = 0, vocab_unioni: int = 0, d_model: int = 256, frequency: int = 2, walk: Optional[WalkConfig] = None, d_hidden: Optional[int] = None, n_attn_layers: int = 2, n_heads: Optional[int] = None, max_seq_len: int = 512, attn_dropout: float = 0.0, res_h1_dropout: float = 0.1, v1_only: bool = False, compass_spiral: bool = False, fast_walk: bool = False, router_v6: bool = False, hash_routing: bool = False, no_walk: bool = False, walk_to_center: bool = False, k_core: int = DEFAULT_K_CORE, center_mix: float = DEFAULT_CENTER_MIX, sector_mix: bool = False, sector_frac: float = DEFAULT_SECTOR_FRAC, sheet_mix: bool = False, sheet_m: int = DEFAULT_SHEET_M, sheet_entry_only: bool = False, edge_neighbor_mix: bool = False, edge_nb_tau: float = DEFAULT_EDGE_NB_TAU, pyramid_center: bool = False, pyramid_narrow: Optional[int] = None, pyramid_hidden: Optional[int] = None, hex_pyramid: bool = False, shared_edges_verts: bool = False, multi_slot_v1: bool = False, d_emb_v23: Optional[int] = None, inter_stage_attn: bool = False, mask_pad_stages: bool = False, fuse_mask_pad: bool = False, zipf_hash_path: Optional[Union[str, Path]] = None, pad_id_v2: int = 3, unk_id_v2: int = 4, pad_id_v3: int = 3, unk_id_v3: int = 4, ): super().__init__() self.compass_spiral = bool(compass_spiral) # walk_token vettorizzato (fast_walk.py): stessi risultati del loop per faccia, senza sync per faccia self.fast_walk = bool(fast_walk) self.mesh: GeodesicMesh = build_geodesic_mesh( frequency, compass_spiral=self.compass_spiral ) self.walk = walk or WalkConfig() self.d_model = int(d_model) self.vocab_pezzi = int(vocab_pezzi) self.vocab_parole = int(vocab_parole) self.vocab_unioni = int(vocab_unioni) self.v1_only = bool(v1_only) self.n_attn_layers = int(n_attn_layers) self.max_seq_len = int(max_seq_len) self.d_hidden = int(d_hidden) if d_hidden is not None else None self.d_emb_v23 = int(d_emb_v23) if d_emb_v23 is not None else None self.inter_stage_attn = bool(inter_stage_attn) self.mask_pad_stages = bool(mask_pad_stages) # v8.1: azzera anche l'addendo emb in fuse su pad/unk (0 nuovi param). # Richiede mask_pad_stages; se True senza mask_pad viene ignorato in forward. self.fuse_mask_pad = bool(fuse_mask_pad) and bool(mask_pad_stages) self.pad_id_v2 = int(pad_id_v2) self.unk_id_v2 = int(unk_id_v2) self.pad_id_v3 = int(pad_id_v3) self.unk_id_v3 = int(unk_id_v3) heads = int(n_heads) if n_heads is not None else _default_n_heads(d_model) # attn backbone sempre 4·d; d_hidden slimma solo le FFN delle facce (v8) attn_ff = 4 * d_model
self.emb_v1 = nn.Embedding(vocab_pezzi, d_model) nn.init.normal_(self.emb_v1.weight, mean=0.0, std=0.02) if not self.v1_only: if vocab_parole <= 0 or vocab_unioni <= 0: raise ValueError( "Cascade 3-stadi richiede vocab_parole > 0 e vocab_unioni > 0 " "(oppure v1_only=True)" ) de = self.d_emb_v23 if self.d_emb_v23 is not None else d_model self.emb_v2 = _make_emb(vocab_parole, de, d_model) self.emb_v3 = _make_emb(vocab_unioni, de, d_model)
self.pos_emb = nn.Embedding(self.max_seq_len, d_model) nn.init.normal_(self.pos_emb.weight, mean=0.0, std=0.02) self.emb_scale = d_model**-0.5
self.attn_blocks = nn.ModuleList( [ CausalAttnBlock(d_model, heads, d_ff=attn_ff, dropout=attn_dropout) for _ in range(self.n_attn_layers) ] ) self.attn_inter2: Optional[CausalAttnBlock] = None if self.inter_stage_attn and not self.v1_only: self.attn_inter2 = CausalAttnBlock(d_model, heads, d_ff=attn_ff, dropout=attn_dropout)
# Banca mesh V1 (80 triangoli a freq=2); stadi 2/3 creati solo se non v1_only self.to_sphere1 = nn.Linear(d_model, 3) self.bank1 = PairedFaceBank(self.mesh, d_model, d_hidden) if not self.v1_only: self.to_sphere2 = nn.Linear(d_model, 3) self.to_sphere3 = nn.Linear(d_model, 3) self.bank2 = PairedFaceBank(self.mesh, d_model, d_hidden) self.bank3 = PairedFaceBank(self.mesh, d_model, d_hidden)
# Fuse bilanciato: LN per-addendo (niente emb_scale su V2/V3 — spegneva gli emb) self.proj_12 = nn.Linear(d_model, d_model) self.proj_23 = nn.Linear(d_model, d_model) self.fuse_ln_h2 = nn.LayerNorm(d_model) self.fuse_ln_e2 = nn.LayerNorm(d_model) self.fuse_ln_h3 = nn.LayerNorm(d_model) self.fuse_ln_e3 = nn.LayerNorm(d_model) self.fuse_norm2 = nn.LayerNorm(d_model) self.fuse_norm3 = nn.LayerNorm(d_model)
# Residual bilanciato: LN per-stadio così ||h1||~180 non schiaccia V2/V3 # Dropout 0.1 sulla scorciatoia res_ln_h1 per non monopolizzare lm_head self.res_h1_dropout = 0.0 if self.v1_only else float(res_h1_dropout) self.res_ln_h1 = nn.LayerNorm(d_model) self.res_drop_h1 = nn.Dropout(self.res_h1_dropout) if not self.v1_only: self.res_ln_h2 = nn.LayerNorm(d_model) self.res_ln_h3 = nn.LayerNorm(d_model) self.final_norm = nn.LayerNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_pezzi, bias=True) # self.lm_head.weight separato da emb_v1.weight per rotazione ortogonale Q_lic Watchman Keystone
self.register_buffer( "centroids", torch.from_numpy(self.mesh.face_centroids.astype("float32")), ) self.register_buffer( "adjacency", torch.from_numpy(self.mesh.adjacency.astype("int64")), )
# v6 dopo tutti i moduli: stessi valori iniziali di v5 per i parametri comuni a parità di seed self.hash_routing = bool(hash_routing) self.router_v6 = bool(router_v6) or self.hash_routing self.no_walk = bool(no_walk) self.sheet_mix = bool(sheet_mix) self.sheet_m = int(sheet_m) # v19: hop≥1 solo entry; False = storico v13–v18 (mean Δ su fogli cross-face) self.sheet_entry_only = bool(sheet_entry_only) and self.sheet_mix # v13 riusa il path sector_mean con buffer (F, 3m) al posto dello spicchio self.sector_mix = bool(sector_mix) or self.sheet_mix self.sector_frac = float(sector_frac) self.edge_neighbor_mix = bool(edge_neighbor_mix) self.edge_nb_tau = float(edge_nb_tau) # v11 sector-mix / v12 edge-nb / v13 sheet-mix implicano Spoke-to-Hub self.walk_to_center = ( bool(walk_to_center) or self.sector_mix or self.edge_neighbor_mix ) self.k_core = int(k_core) self.center_mix = float(center_mix) if self.sheet_mix and self.edge_neighbor_mix: raise ValueError("sheet_mix (v13) e edge_neighbor_mix (v12) sono mutuamente esclusivi") if self.sector_mix and self.edge_neighbor_mix: raise ValueError("sector_mix (v11) e edge_neighbor_mix (v12) sono mutuamente esclusivi") if self.sheet_mix and self.sheet_m < 1: raise ValueError("sheet_m deve essere >= 1") if bool(sheet_entry_only) and not self.sheet_mix: raise ValueError("sheet_entry_only richiede sheet_mix") if self.no_walk and self.walk_to_center: raise ValueError("no_walk e walk_to_center (Spoke-to-Hub) sono mutuamente esclusivi") if self.no_walk and (not self.router_v6 or int(self.walk.max_hops) != 1): raise ValueError("no_walk: servono router_v6 o hash_routing e WalkConfig(max_hops=1)") self.spoke_gates: Optional[nn.ModuleList] = None if self.walk_to_center: if not self.hash_routing: raise ValueError("walk_to_center/Spoke-to-Hub: serve hash_routing (ingresso Zipf)") hops = int(self.walk.max_hops) if hops < 2 or hops > 3: raise ValueError("walk_to_center/Spoke-to-Hub: H_max deve essere 2 o 3") if not (0.0 <= self.center_mix <= 1.0): raise ValueError("center_mix deve essere in [0, 1]") if self.sector_mix and not self.sheet_mix and not (0.0 < self.sector_frac <= 1.0): raise ValueError("sector_frac deve essere in (0, 1]") parent, is_hub, hub_ids = build_spoke_hub_parent( self.mesh.adjacency, self.mesh.face_centroids, k_core=self.k_core ) self.register_buffer("parent_face", torch.from_numpy(parent.astype("int64"))) self.register_buffer("is_hub", torch.from_numpy(is_hub.astype("bool"))) self.register_buffer("hub_ids", torch.from_numpy(hub_ids.astype("int64"))) if self.sheet_mix and self.sheet_entry_only: # v19: niente buffer fogli — hop≥1 tocca solo l'entry (vedi walk) self.sector_faces = None # type: ignore[assignment] self.sector_k = 1 elif self.sheet_mix: sheets = build_complementary_sheets( self.mesh.face_centroids, spiral_rank=getattr(self.mesh, "spiral_rank", None), m_per_sheet=self.sheet_m, ) self.register_buffer( "sector_faces", torch.from_numpy(sheets.astype("int64")) ) self.sector_k = int(sheets.shape[1]) elif self.sector_mix: sectors = build_azimuth_sectors( self.mesh.face_centroids, sector_frac=self.sector_frac ) self.register_buffer( "sector_faces", torch.from_numpy(sectors.astype("int64")) ) self.sector_k = int(sectors.shape[1]) else: self.sector_faces = None # type: ignore[assignment] self.sector_k = 0 if self.edge_neighbor_mix: w = build_edge_neighbor_weights( self.mesh.adjacency, self.mesh.face_centroids, tau=self.edge_nb_tau ) self.register_buffer("edge_nb_w", torch.from_numpy(w)) else: self.edge_nb_w = None # type: ignore[assignment] self.spoke_res_scale = 1.0 / math.sqrt(float(hops)) # gate scalare hop≥1; bias=0 → σ≈0.5 a init (Argon) n_banks = 1 if self.v1_only else 3 gates = [] for _ in range(n_banks): lin = nn.Linear(self.d_model, 1) nn.init.zeros_(lin.weight) nn.init.zeros_(lin.bias) gates.append(lin) self.spoke_gates = nn.ModuleList(gates) else: self.parent_face = None # type: ignore[assignment] self.is_hub = None # type: ignore[assignment] self.hub_ids = None # type: ignore[assignment] self.sector_faces = None # type: ignore[assignment] self.sector_k = 0 self.sector_mix = False self.sheet_mix = False self.sheet_entry_only = False self.edge_neighbor_mix = False self.edge_nb_w = None # type: ignore[assignment] self.spoke_res_scale = 1.0 self.center_mix = 0.0 self.v6_logit_scale_max = V6_LOGIT_SCALE_MAX self.v6_bias_rate = V6_BIAS_RATE if self.router_v6: n_faces = int(self.mesh.num_faces) sizes = (self.vocab_pezzi, self.vocab_parole, self.vocab_unioni) for s, bank in enumerate(self._banks(), start=1): if self.hash_routing: bank.register_buffer("hash_face", hash_faces(sizes[s - 1], n_faces, s)) delattr(self, f"to_sphere{s}") setattr(self, f"to_sphere{s}", None) else: bank.logit_scale = nn.Parameter(torch.tensor(V6_LOGIT_SCALE_INIT)) bank.register_buffer("face_bias", torch.zeros(n_faces))
self.multi_slot_v1 = bool(multi_slot_v1) if zipf_hash_path is not None: if not self.hash_routing: raise ValueError("zipf_hash_path richiede hash_routing") self.load_zipf_hash(zipf_hash_path) elif self.multi_slot_v1: # Eval senza zipf path: buffer placeholder (V, K=3) riempito da state_dict v = int(self.bank1.hash_face.numel()) self.bank1.register_buffer( "hash_slots", self.bank1.hash_face.unsqueeze(1).expand(v, 3).contiguous().clone(), )
# piramidi e centri per ultimi: i parametri della base hanno gli stessi valori iniziali a parità di seed self.hex_pyramid = bool(hex_pyramid) self.shared_edges_verts = bool(shared_edges_verts) if self.hex_pyramid and self.shared_edges_verts: raise ValueError("hex_pyramid e shared_edges_verts (v12) sono mutuamente esclusivi") self.pyramid_center = bool(pyramid_center) or self.hex_pyramid or self.shared_edges_verts self.pyramids: Optional[nn.ModuleList] = None if self.pyramid_center: if not self.hash_routing: raise ValueError("pyramid_center/hex_pyramid: serve hash_routing (la piramide è quella della faccia d'ingresso)") self.pyramid_narrow = int(pyramid_narrow or self.d_model // 2) self.pyramid_hidden = int(pyramid_hidden or 2 * self.d_model) # generatore proprio e stato globale ripristinato: su CPU anche le maschere di dropout restano quelle della base gen = torch.Generator().manual_seed((torch.initial_seed() + PYRAMID_SEED_OFFSET) % 2**63) rng = torch.get_rng_state() if self.hex_pyramid: face_verts = torch.from_numpy(self.mesh.faces.astype("int64")) n_vert = int(self.mesh.num_vertices) self.pyramids = nn.ModuleList( HexPyramidCenter( self.d_model, n_vert, face_verts, self.pyramid_narrow, self.pyramid_hidden, gen ) for _ in self._banks() ) elif self.shared_edges_verts: face_edges_np, n_edges = build_face_edge_ids(self.mesh.faces) face_edges = torch.from_numpy(face_edges_np.astype("int64")) face_verts = torch.from_numpy(self.mesh.faces.astype("int64")) n_vert = int(self.mesh.num_vertices) self.pyramids = nn.ModuleList( SharedEdgeVertexPyramid( self.d_model, int(self.mesh.num_faces), int(n_edges), n_vert, face_edges, face_verts, self.pyramid_narrow, self.pyramid_hidden, gen, ) for _ in self._banks() ) else: self.pyramids = nn.ModuleList( PyramidCenter(self.d_model, int(self.mesh.num_faces), self.pyramid_narrow, self.pyramid_hidden, gen) for _ in self._banks() ) torch.set_rng_state(rng)
def _banks(self) -> List[PairedFaceBank]: return [self.bank1] if self.v1_only else [self.bank1, self.bank2, self.bank3]
def load_zipf_hash(self, path: Union[str, Path]) -> None: """Copia ``hash_face_{1,2,3}`` (e opz. ``hash_slots_1`` multi-slot V1) da un ``.pt`` Zipf.""" path = Path(path) try: blob = torch.load(path, map_location="cpu", weights_only=True) except TypeError: blob = torch.load(path, map_location="cpu") n_faces = int(self.mesh.num_faces) for s, bank in enumerate(self._banks(), start=1): key = f"hash_face_{s}" if key not in blob: raise KeyError(f"{path}: manca {key}") t = blob[key].long().view(-1) if t.numel() != bank.hash_face.numel(): raise ValueError( f"{path} {key}: len={t.numel()} ≠ bank.hash_face={bank.hash_face.numel()}" ) if int(t.max()) >= n_faces or int(t.min()) < 0: raise ValueError(f"{path} {key}: facce fuori da [0, {n_faces})") bank.hash_face.copy_(t) # Multi-slot solo stadio 1 (pezzi): (V, K) con K copie della primaria se non top-N if "hash_slots_1" in blob: slots = blob["hash_slots_1"].long() if slots.ndim != 2 or slots.shape[0] != self.bank1.hash_face.numel(): raise ValueError( f"{path} hash_slots_1: shape={tuple(slots.shape)} " f"atteso (V={self.bank1.hash_face.numel()}, K)" ) if int(slots.max()) >= n_faces or int(slots.min()) < 0: raise ValueError(f"{path} hash_slots_1: facce fuori da [0, {n_faces})") self.bank1.register_buffer("hash_slots", slots.contiguous()) self.multi_slot_v1 = True elif self.multi_slot_v1: raise ValueError(f"{path}: multi_slot_v1 richiesto ma manca hash_slots_1")
def _active_mask(self, stage: int, ids: torch.Tensor) -> Optional[torch.Tensor]: """Maschera token attivi per stadi 2/3 con ``mask_pad_stages`` (pad/unk → False).""" if not self.mask_pad_stages or stage < 1: return None if stage == 1: pad, unk = self.pad_id_v2, self.unk_id_v2 elif stage == 2: pad, unk = self.pad_id_v3, self.unk_id_v3 else: return None return (ids != pad) & (ids != unk)
def _v6_entry( self, h: torch.Tensor, bank: PairedFaceBank, to_sphere: Optional[nn.Linear], entry_ids: Optional[torch.Tensor], ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: """Faccia d'ingresso v6 (B,) e peso straight-through w (B, 1), None senza gradiente.
w = p_f / sg(p_f) è scritto come exp(log p_f − sg(log p_f)): il bias può scegliere una faccia con p_f sotto il minimo di float32 e il rapporto diventerebbe 0/0. In training il carico d'ingresso per faccia si accumula sul device per ``update_face_bias``. """ if self.hash_routing: if entry_ids is None: raise ValueError("hash_routing: servono gli id dei token per la faccia d'ingresso") # v9 multi-slot V1: in training campiona tra K facce; in eval usa lo slot 0 (primaria) slots = getattr(bank, "hash_slots", None) if slots is not None: row = slots[entry_ids] # (..., K) if self.training: k = int(row.shape[-1]) idx = torch.randint(0, k, entry_ids.shape, device=entry_ids.device) face = row.gather(-1, idx.unsqueeze(-1)).squeeze(-1) else: face = row[..., 0] return face, None return bank.hash_face[entry_ids], None scores = F.normalize(to_sphere(h), dim=-1) @ self.centroids.T # (B, F) face = (scores + bank.face_bias).argmax(dim=-1) if self.training: n_faces = scores.shape[1] load = (face.unsqueeze(1) == torch.arange(n_faces, device=face.device)).sum(0) prev = bank.__dict__.get("_v6_load") bank.__dict__["_v6_load"] = load if prev is None else prev + load if not torch.is_grad_enabled(): return face, None scale = bank.logit_scale.clamp(max=self.v6_logit_scale_max).exp() lp = F.log_softmax(scores * scale, dim=-1).gather(1, face.unsqueeze(1)) return face, torch.exp(lp - lp.detach())
def _v6_route( self, face: torch.Tensor, logits: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """Porte come ``_route_step``, uscita dura a soglia; ritorna anche il peso del salto successivo.
w = w_porta · p_stay / sg(p_stay) (B, 1), None senza gradiente: w_porta è il valore Gumbel-ST della porta scelta (solo in training), p_stay = 1 − probs[:, 3] = exp(LSE(z[:3]) − LSE(z)). Sui token che proseguono il logit di uscita riceve d log p_stay / d z_uscita = −p_exit volte il gradiente del peso dell'esperto del salto successivo. Con ``no_walk`` escono tutti: porte e uscita non vengono valutate. Con ``walk_to_center`` (Spoke-to-Hub) il routing è in ``_walk_token_spoke_hub``: qui si usa solo ``parent_face`` (niente Gumbel). """ if self.no_walk: return face, torch.ones_like(face, dtype=torch.bool), None if self.walk_to_center: nxt = self.parent_face[face.long()] exit_mask = nxt == face return nxt, exit_mask, None temp = max(self.walk.router_temperature, 1e-6) z = logits / temp probs = F.softmax(z, dim=-1) exit_mask = probs[:, 3] >= self.walk.exit_threshold neighbors = self.adjacency[face.long()] w_side: Optional[torch.Tensor] = None if self._hard_routing(): side = probs[:, :3].argmax(dim=-1) else: side_oh = F.gumbel_softmax(logits[:, :3] / temp, hard=True, dim=-1) side = side_oh.argmax(dim=-1) w_side = side_oh.gather(1, side.unsqueeze(1)) next_face = neighbors.gather(1, side.unsqueeze(1)).squeeze(1) if not torch.is_grad_enabled(): return next_face, exit_mask, None log_stay = torch.logsumexp(z[:, :3], dim=-1, keepdim=True) - torch.logsumexp(z, dim=-1, keepdim=True) w = torch.exp(log_stay - log_stay.detach()) return next_face, exit_mask, (w if w_side is None else w_side * w)
def _walk_token_v6_loop( self, h: torch.Tensor, bank: PairedFaceBank, to_sphere: Optional[nn.Linear], entry_ids: Optional[torch.Tensor] = None, record_path: bool = False, active: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: """Cammino v6 col loop per faccia: riferimento di ``fast_walk_token_v6`` nei test.""" b = h.shape[0] face, w = self._v6_entry(h, bank, to_sphere, entry_ids) if active is None: active = torch.ones(b, dtype=torch.bool, device=h.device) else: active = active.to(device=h.device, dtype=torch.bool) face0 = torch.where(active, face, torch.full_like(face, -1)) paths = [[int(f)] for f in face0.tolist()] if record_path else None for _ in range(self.walk.max_hops): if not bool(active.any()): break logits = h.new_zeros(b, 4) h_new = h.clone() for f_id in face[active].unique().tolist(): mask = active & (face == f_id) blk = bank.blocks[int(bank.face_to_slot[f_id].item())] x = h[mask] delta = blk.ff(blk.norm(x)) out = x + delta if w is None else x + w[mask] * delta h_new[mask] = out logits[mask] = blk.router(out) h = h_new next_face, exit_mask, w = self._v6_route(face, logits) moved = active & ~exit_mask face = torch.where(moved, next_face, face) if paths is not None: for i in range(b): if moved[i]: paths[i].append(int(face[i].item())) elif active[i] and exit_mask[i]: paths[i].append(-1) active = active & ~exit_mask return h, paths
@torch.no_grad() def update_face_bias(self) -> None: """Loss-Free Balancing: b_f += u · sign(carico medio − carico_f) col carico d'ingresso accumulato.""" if not self.router_v6 or self.hash_routing: return for bank in self._banks(): load = bank.__dict__.pop("_v6_load", None) if load is None: continue load = load.to(bank.face_bias.dtype) bank.face_bias.add_(torch.sign(load.mean() - load), alpha=self.v6_bias_rate)
def _hard_routing(self) -> bool: """Hard (argmax) in eval o se WalkConfig.hard_routing; soft/ST in train.""" return bool(self.walk.hard_routing) or (not self.training)
def project_to_face( self, h: torch.Tensor, to_sphere: nn.Linear ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: """ Proietta h sulla sfera → faccia. Train (soft): Gumbel-ST one-hot (B, F) così i grad arrivano a to_sphere. Eval/hard: solo face id (argmax), face_oh=None. """ direction = F.normalize(to_sphere(h), dim=-1) scores = direction @ self.centroids.T # (B, F) if self._hard_routing(): return scores.argmax(dim=-1), None temp = max(self.walk.router_temperature, 1e-6) face_oh = F.gumbel_softmax(scores / temp, hard=True, dim=-1) # ST soft→hard face = face_oh.argmax(dim=-1) # solo indice forward; massa ST resta in face_oh return face, face_oh
def _route_step( self, face: torch.Tensor, logits: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """ Router ternario + exit. Train (soft): Gumbel-ST su 3 lati (niente argmax sulla one-hot) + mixture su adjacency → side_oh per propagare i grad al router. Eval/hard: argmax discreto, side_oh=None. """ temp = max(self.walk.router_temperature, 1e-6) probs = F.softmax(logits / temp, dim=-1) exit_prob = probs[:, 3] neighbors = self.adjacency[face.long()] # (B, 3) exit_mask = exit_prob >= self.walk.exit_threshold
if self._hard_routing(): side = probs[:, :3].argmax(dim=-1) next_face = neighbors.gather(1, side.unsqueeze(1)).squeeze(1) return next_face, exit_mask, None
# Gumbel-ST: forward one-hot, backward softmax — non chiamare .argmax sulla ST side_oh = F.gumbel_softmax(logits[:, :3] / temp, hard=True, dim=-1) # (B, 3) side = side_oh.argmax(dim=-1) next_face = neighbors.gather(1, side.unsqueeze(1)).squeeze(1) return next_face, exit_mask, side_oh
def _scatter_side_oh( self, face: torch.Tensor, side_oh: torch.Tensor ) -> torch.Tensor: """Soft/ST mixture su adjacency: massa dei 3 lati → one-hot sparsa su F facce.""" b = face.shape[0] n_faces = int(self.centroids.shape[0]) neighbors = self.adjacency[face.long()] # (B, 3) face_oh = side_oh.new_zeros(b, n_faces) face_oh.scatter_add_(1, neighbors, side_oh) return face_oh
def _spoke_stage_index(self, bank: PairedFaceBank) -> int: for i, b in enumerate(self._banks()): if b is bank: return i raise KeyError("bank non appartiene al modello")
def _apply_sector_mean( self, h: torch.Tensor, bank: PairedFaceBank, entry: torch.Tensor, active: torch.Tensor, g: Optional[torch.Tensor], st: Optional[dict] = None, ) -> torch.Tensor: """v11: ``x ← x + g · mean_{f∈settore(entry)}(Δ_f)`` (hop≥1).
Settore fissato sulla faccia d'ingresso Zipf. ``g=None`` → peso 1.0. """ assert self.sector_faces is not None k = int(self.sector_k) if k <= 0: return h use_fast = st is not None delta_sum: Optional[torch.Tensor] = None for slot in range(k): face_k = self.sector_faces[entry.long(), slot] if use_fast: assert st is not None out, _lg, counts = grouped_block_forward( st, h, face_k, active, gate=None ) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] # out = x+Δ sulle attive; sulle inattive out è spazzatura → maschera dopo d = out - h else: d = h.new_zeros(h.shape) for f_id in face_k[active].unique().tolist(): mask = active & (face_k == f_id) blk = bank.blocks[int(bank.face_to_slot[f_id].item())] x = h[mask] d[mask] = blk.ff(blk.norm(x)) delta_sum = d if delta_sum is None else delta_sum + d assert delta_sum is not None mean_d = delta_sum / float(k) if g is None: upd = h + mean_d else: upd = h + g * mean_d return torch.where(active.unsqueeze(-1), upd, h)
def _apply_edge_neighbor_mix( self, h: torch.Tensor, bank: PairedFaceBank, entry: torch.Tensor, active: torch.Tensor, g: Optional[torch.Tensor], st: Optional[dict] = None, ) -> torch.Tensor: """v12: ``x ← x + g · Σ_k w_{e,k} Δ_{nb_k}`` sui 3 lati di ``entry`` (pesi verso polo).""" assert self.edge_nb_w is not None e = entry.long() nbs = self.adjacency[e] # (B, 3) w = self.edge_nb_w[e] # (B, 3) use_fast = st is not None weighted: Optional[torch.Tensor] = None for slot in range(3): face_k = nbs[:, slot] wk = w[:, slot].unsqueeze(-1) if use_fast: assert st is not None out, _lg, counts = grouped_block_forward( st, h, face_k, active, gate=None ) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] d = out - h else: d = h.new_zeros(h.shape) for f_id in face_k[active].unique().tolist(): mask = active & (face_k == f_id) blk = bank.blocks[int(bank.face_to_slot[f_id].item())] x = h[mask] d[mask] = blk.ff(blk.norm(x)) term = wk * d weighted = term if weighted is None else weighted + term assert weighted is not None if g is None: upd = h + weighted else: upd = h + g * weighted return torch.where(active.unsqueeze(-1), upd, h)
def _walk_token_spoke_hub( self, h: torch.Tensor, bank: PairedFaceBank, to_sphere: Optional[nn.Linear], entry_ids: Optional[torch.Tensor] = None, record_path: bool = False, active: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: """v10 Spoke-to-Hub / v11 sector-mix / v12 edge-nb / v13–v19 sheet: parent→hub; no Gumbel.
hop0: solo faccia entry, residuo pieno. hop≥1: v10 = blocco ``face`` corrente con ``g=(c+(1-c)σ)/√H``; v11 (``sector_mix``) = media Δ sul settore azimutale dell'ingresso; v12 (``edge_neighbor_mix``) = mix pesato sui 3 vicini di lato (anche al polo); v13–v18 (``sheet_mix``, default) = media Δ sui fogli complementari dell'ingresso; v19 (``sheet_entry_only``) = di nuovo solo blocco entry (niente cross-face). pad/unk (``active=False``): 0 hop. Train==eval. """ assert self.spoke_gates is not None and self.parent_face is not None b = h.shape[0] face, _ = self._v6_entry(h, bank, to_sphere, entry_ids) if active is None: active = torch.ones(b, dtype=torch.bool, device=h.device) else: active = active.to(device=h.device, dtype=torch.bool) entry = face.clone() face0 = torch.where(active, face, torch.full_like(face, -1)) max_hops = int(self.walk.max_hops) if b == 0 or max_hops <= 0: return h, (_build_paths(face0, []) if record_path else None)
gate_lin = self.spoke_gates[self._spoke_stage_index(bank)] scale = float(self.spoke_res_scale) codes: List[torch.Tensor] = [] use_fast = bool(self.fast_walk) st = stack_bank(bank) if use_fast else None # storico sheet/sector: media su sector_faces; v19 entry-only salta questo path use_sector = ( bool(self.sector_mix) and self.sector_faces is not None and not bool(self.sheet_entry_only) ) use_sheet_entry = bool(self.sheet_mix) and bool(self.sheet_entry_only) use_edge_nb = bool(self.edge_neighbor_mix) and self.edge_nb_w is not None
c_mix = float(self.center_mix) for hop in range(max_hops): if not bool(active.any()): break # hop0: residuo pieno (v8.1); hop≥1: g=(c+(1-c)σ)/√H (liscio, no clamp) if hop == 0: g: Optional[torch.Tensor] = None else: g = (c_mix + (1.0 - c_mix) * torch.sigmoid(gate_lin(h))) * scale if use_edge_nb and hop >= 1: h = self._apply_edge_neighbor_mix(h, bank, entry, active, g, st=st) elif use_sector and hop >= 1: h = self._apply_sector_mean(h, bank, entry, active, g, st=st) elif use_sheet_entry and hop >= 1: # v19: solo esperto della faccia d'ingresso (fogli non toccano altre facce) apply_face = entry if use_fast: assert st is not None out, _lg, counts = grouped_block_forward( st, h, apply_face, active, gate=g ) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] h = torch.where(active.unsqueeze(-1), out, h) else: h_new = h.clone() for f_id in apply_face[active].unique().tolist(): mask = active & (apply_face == f_id) blk = bank.blocks[int(bank.face_to_slot[f_id].item())] x = h[mask] delta = blk.ff(blk.norm(x)) if g is None: h_new[mask] = x + delta else: h_new[mask] = x + g[mask] * delta h = h_new elif use_fast: assert st is not None out, _lg, counts = grouped_block_forward( st, h, face, active, gate=g ) if st["visited"] is not None: st["visited"].add(counts) # type: ignore[union-attr] h = torch.where(active.unsqueeze(-1), out, h) else: h_new = h.clone() for f_id in face[active].unique().tolist(): mask = active & (face == f_id) blk = bank.blocks[int(bank.face_to_slot[f_id].item())] x = h[mask] delta = blk.ff(blk.norm(x)) if g is None: h_new[mask] = x + delta else: h_new[mask] = x + g[mask] * delta h = h_new # v12: nessuno stop anticipato su hub — tutti fanno hop1 sui 3 lati if use_edge_nb: stop = torch.full( (b,), hop == max_hops - 1, device=h.device, dtype=torch.bool ) moved = torch.zeros_like(active) # face resta sull'entry; hop1 usa adjacency[entry] else: nxt = self.parent_face[face.long()] at_hub = nxt == face stop = at_hub | (hop == max_hops - 1) moved = active & ~stop face = torch.where(moved, nxt, face) just_exit = active & stop active = active & ~stop if record_path: codes.append( torch.where( moved, face, torch.where(just_exit, torch.full_like(face, -1), torch.full_like(face, -2)), ) )
return h, (_build_paths(face0, codes) if record_path else None)
def walk_token( self, h: torch.Tensor, bank: PairedFaceBank, to_sphere: Optional[nn.Linear], record_path: bool = False, entry_ids: Optional[torch.Tensor] = None, active: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[List[List[int]]]]: if self.walk_to_center: return self._walk_token_spoke_hub( h, bank, to_sphere, entry_ids=entry_ids, record_path=record_path, active=active ) if self.router_v6: if self.fast_walk: return fast_walk_token_v6( self, h, bank, to_sphere, entry_ids=entry_ids, record_path=record_path, active=active ) return self._walk_token_v6_loop( h, bank, to_sphere, entry_ids=entry_ids, record_path=record_path, active=active ) if self.fast_walk: return fast_walk_token(self, h, bank, to_sphere, record_path=record_path) b = h.shape[0] face, face_oh = self.project_to_face(h, to_sphere) paths: Optional[List[List[int]]] = ( [[int(face[i].item())] for i in range(b)] if record_path else None ) active = torch.ones(b, dtype=torch.bool, device=h.device)
for _ in range(self.walk.max_hops): if not active.any(): break logits = h.new_zeros(b, 4) h_new = h.clone() for f_id in face[active].unique().tolist(): mask = active & (face == f_id) if not mask.any(): continue out, lg = bank.forward_face(int(f_id), h[mask]) if face_oh is not None: # ST: w≈1 in forward; backward → face_oh → to_sphere / router w = face_oh[mask, int(f_id)].unsqueeze(-1) h_new[mask] = out * w else: h_new[mask] = out logits[mask] = lg h = h_new next_face, exit_mask, side_oh = self._route_step(face, logits) moved = active & ~exit_mask if side_oh is not None: # sum(ST one-hot)=1 in forward: ancora i grad al router anche su exit/ultimo hop scale = side_oh.sum(dim=-1, keepdim=True) h = torch.where(active.unsqueeze(-1), h * scale, h) routed_oh = self._scatter_side_oh(face, side_oh) if face_oh is None: face_oh = routed_oh else: face_oh = torch.where(moved.unsqueeze(-1), routed_oh, face_oh) face = torch.where(moved, next_face, face) just_exit = active & exit_mask active = active & ~exit_mask if record_path and paths is not None: for i in range(b): if moved[i]: paths[i].append(int(face[i].item())) elif just_exit[i]: paths[i].append(-1) return h, paths
def _descend( self, stage: int, h: torch.Tensor, ids: torch.Tensor, active_bt: Optional[torch.Tensor] = None, ) -> torch.Tensor: """Piramide della faccia d'ingresso e centro dello stadio (da 0) su h (B, T, d); identità senza piramidi.""" if self.pyramids is None: return h bank = self._banks()[stage] face = bank.hash_face[ids] # Allinea multi-slot V1 alla stessa regola di ``_v6_entry`` (slot 0 in eval; sample in train) slots = getattr(bank, "hash_slots", None) if slots is not None: row = slots[ids] if self.training: k = int(row.shape[-1]) idx = torch.randint(0, k, ids.shape, device=ids.device) face = row.gather(-1, idx.unsqueeze(-1)).squeeze(-1) else: face = row[..., 0] out = self.pyramids[stage](h, face) if active_bt is None: return out return torch.where(active_bt.unsqueeze(-1), out, h)
def _walk_seq( self, h: torch.Tensor, bank: PairedFaceBank, to_sphere: Optional[nn.Linear], record_path: bool, entry_ids: Optional[torch.Tensor] = None, active_bt: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[List[List[List[int]]]]]: b, t, d = h.shape kw: dict = {} if entry_ids is not None: kw["entry_ids"] = entry_ids.reshape(b * t) if active_bt is not None: kw["active"] = active_bt.reshape(b * t) flat, paths_flat = self.walk_token( h.reshape(b * t, d), bank, to_sphere, record_path=record_path, **kw ) h_out = flat.view(b, t, d) paths = None if record_path and paths_flat is not None: paths = [ [paths_flat[bi * t + ti] for ti in range(t)] for bi in range(b) ] return h_out, paths
def forward( self, pezzi_ids: torch.Tensor, parole_ids: Optional[torch.Tensor] = None, unioni_ids: Optional[torch.Tensor] = None, record_path: bool = False, ) -> Tuple[torch.Tensor, Optional[List[List[List[int]]]]]: """ pezzi/parole/unioni: (B, T) allineati sulla timeline pezzi. Se self.v1_only: richiede solo pezzi_ids (parole_ids/unioni_ids ignorati/None). returns: logits (B, T, V_pezzi), paths opzionale dell'ultimo mesh walk. """ b, t = pezzi_ids.shape if t > self.max_seq_len: raise ValueError(f"seq_len={t} > max_seq_len={self.max_seq_len}")
pos = torch.arange(t, device=pezzi_ids.device).unsqueeze(0) h = self.emb_v1(pezzi_ids) * self.emb_scale + self.pos_emb(pos)
# Dei CausalAttnBlock: 1 su V1 (prima di bank1), 1 dopo for block in self.attn_blocks[:-1]: h = block(h)
hashed = self.hash_routing if self.v1_only: h1, paths = self._walk_seq( h, self.bank1, self.to_sphere1, record_path=record_path, entry_ids=pezzi_ids if hashed else None, ) h1 = self._descend(0, h1, pezzi_ids) h = self.res_ln_h1(h1) if len(self.attn_blocks) > 0: h = self.attn_blocks[-1](h) h = self.final_norm(h) logits = self.lm_head(h) logits = 30.0 * torch.tanh(logits / 30.0) return logits, paths
if parole_ids is None or unioni_ids is None: raise ValueError("Cascade 3-stadi richiede parole_ids e unioni_ids")
h1, _ = self._walk_seq( h, self.bank1, self.to_sphere1, record_path=False, entry_ids=pezzi_ids if hashed else None ) h1 = self._descend(0, h1, pezzi_ids)
# Stage 2: fuse bilanciato (LN per-addendo) + emb parole (+ attn inter-stadio opzionale) # v8.1 fuse_mask_pad: su pad/unk azzera l'addendo emb (mask-pad già saltava solo walk/piramide) active2 = self._active_mask(1, parole_ids) emb2 = self.fuse_ln_e2(self.emb_v2(parole_ids)) if self.fuse_mask_pad and active2 is not None: emb2 = emb2 * active2.unsqueeze(-1).to(dtype=emb2.dtype) h = self.fuse_norm2(self.fuse_ln_h2(self.proj_12(h1)) + emb2) if self.attn_inter2 is not None: h = self.attn_inter2(h) h2, _ = self._walk_seq( h, self.bank2, self.to_sphere2, record_path=False, entry_ids=parole_ids if hashed else None, active_bt=active2, ) h2 = self._descend(1, h2, parole_ids, active_bt=active2)
# Stage 3: fuse bilanciato + emb unioni active3 = self._active_mask(2, unioni_ids) emb3 = self.fuse_ln_e3(self.emb_v3(unioni_ids)) if self.fuse_mask_pad and active3 is not None: emb3 = emb3 * active3.unsqueeze(-1).to(dtype=emb3.dtype) h = self.fuse_norm3(self.fuse_ln_h3(self.proj_23(h2)) + emb3) h3, paths = self._walk_seq( h, self.bank3, self.to_sphere3, record_path=record_path, entry_ids=unioni_ids if hashed else None, active_bt=active3, ) h3 = self._descend(2, h3, unioni_ids, active_bt=active3)
# Residual bilanciato: norm per-stadio (con dropout 0.1 su res_ln_h1) + attn post-fuse h = ( self.res_drop_h1(self.res_ln_h1(h1)) + self.res_ln_h2(h2) + self.res_ln_h3(h3) ) if len(self.attn_blocks) > 0: h = self.attn_blocks[-1](h) h = self.final_norm(h) logits = self.lm_head(h) logits = 30.0 * torch.tanh(logits / 30.0) return logits, paths
class V1OnlyMeshModel(CascadeMeshModel): """Solo V1 (pezzi): emb_v1 (+pos) → CausalAttn_0 → bank1 (80 facce) → LN → CausalAttn_1 → final_norm → lm_head."""
def __init__( self, vocab_pezzi: int, d_model: int = 256, frequency: int = 2, walk: Optional[WalkConfig] = None, d_hidden: Optional[int] = None, n_attn_layers: int = 2, n_heads: Optional[int] = None, max_seq_len: int = 512, attn_dropout: float = 0.0, compass_spiral: bool = False, fast_walk: bool = False, ): super().__init__( vocab_pezzi=vocab_pezzi, vocab_parole=0, vocab_unioni=0, d_model=d_model, frequency=frequency, walk=walk, d_hidden=d_hidden, n_attn_layers=n_attn_layers, n_heads=n_heads, max_seq_len=max_seq_len, attn_dropout=attn_dropout, res_h1_dropout=0.0, v1_only=True, compass_spiral=compass_spiral, fast_walk=fast_walk, )
def count_parameters(model: nn.Module) -> int: return sum(p.numel() for p in model.parameters() if p.requires_grad)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242# ============================================================================# LEGAL NOTICE & WATERMARK: R08 NON-COMMERCIAL RESEARCH & ETHICAL LICENSE v2.0# Copyright (c) 2026 Thomas Seri (Sentinel). All Rights Reserved.# Exclusive Jurisdiction: Court of Milan (Sezione Specializzata Impresa), Italy.# Clean-room reverse engineering, distillation, commercial or military use# is strictly prohibited and constitutes a breach of contract.# ============================================================================__author__ = "Thomas Seri (Sentinel)"__license__ = "R08-Non-Commercial-Ethical-License-v2.0"__jurisdiction__ = "Court of Milan, Italy"
#!/usr/bin/env python3"""Modello Geodetico a Sfere Piramidali Sentinel R-08 v7.2 (Sparse Upcycling / Warm-Start).Architettura separata da v7 (non tocca né modifica alcun file o checkpoint di v7):- Base: Geodesic Stages v7 (44.5M parametri, 3 stadi, frequenza 2, d=256, 2 layer attenzione).- Modifica 1: Convoluzioni Causali 1D Inter-Stadio (k=4, d=256) tra Stadio 1->2 e 2->3 (Zero-Init Residual).- Modifica 2: 12 Hub Regionali dell'Icosaedro per ciascuna piramide (partizione geometrica 80 facce -> 12 poli).- Parametri Totali: 51.614.115 (~51.6M)."""from __future__ import annotations
import mathfrom typing import List, Optional, Tuple, Unionfrom pathlib import Path
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
from mesh_topology import build_geodesic_mesh, icosahedron_vertices, GeodesicMeshfrom geodesic_stages_model import CascadeMeshModel, WalkConfig
def compute_face_to_icosahedron_regions(frequency: int = 2) -> torch.Tensor: """Partiziona geometricamente le facce della sfera geodetica verso il vertice dell'icosaedro più vicino.""" mesh = build_geodesic_mesh(frequency) ico_v = icosahedron_vertices() # (12, 3) centers = np.array([mesh.vertices[f].mean(axis=0) for f in mesh.faces]) centers = centers / np.linalg.norm(centers, axis=-1, keepdims=True) sims = centers @ ico_v.T # (n_faces, 12) regions = np.argmax(sims, axis=-1) return torch.from_numpy(regions).long()
class RegionalPyramidCenter(nn.Module): """Piramida Geodetica con 12 Centri Regionali indipendenti (1 per ciascun polo dell'Icosaedro). Risolve il collo di bottiglia dell'hub centrale singolo moltiplicando la capacità per 12. """ def __init__( self, d_model: int = 256, n_faces: int = 80, d_narrow: int = 128, d_hidden: int = 512, n_regions: int = 12, face_to_region: Optional[torch.Tensor] = None, generator: Optional[torch.Generator] = None, ): super().__init__() self.d_model = d_model self.n_faces = n_faces self.d_narrow = d_narrow self.d_hidden = d_hidden self.n_regions = n_regions
if face_to_region is None: face_to_region = compute_face_to_icosahedron_regions(2) self.register_buffer("face_to_region", face_to_region.long().contiguous())
self.norm = nn.LayerNorm(d_model) self.down = nn.Linear(d_model, d_narrow, bias=False) self.face_gain = nn.Parameter(torch.zeros(n_faces, d_narrow)) self.face_shift = nn.Parameter(torch.zeros(n_faces, d_narrow))
# 12 Centri MLP Regionali indipendenti self.centers = nn.ModuleList([ nn.Sequential( nn.Linear(d_narrow, d_hidden), nn.GELU(), nn.Linear(d_hidden, d_model), ) for _ in range(n_regions) ]) self.reset_parameters(generator)
def reset_parameters(self, generator: Optional[torch.Generator] = None) -> None: nn.init.kaiming_uniform_(self.down.weight, a=math.sqrt(5), generator=generator) for c in self.centers: nn.init.kaiming_uniform_(c[0].weight, a=math.sqrt(5), generator=generator) if c[0].bias is not None: bound = 1.0 / math.sqrt(c[0].in_features) nn.init.uniform_(c[0].bias, -bound, bound, generator=generator) nn.init.zeros_(c[2].weight) nn.init.zeros_(c[2].bias) nn.init.zeros_(self.face_gain) nn.init.zeros_(self.face_shift) self.norm.reset_parameters()
def forward(self, x: torch.Tensor, face: torch.Tensor) -> torch.Tensor: # x: (B, T, d_model), face: (B, T) z = self.down(self.norm(x)) z = z * (1.0 + F.embedding(face, self.face_gain)) + F.embedding(face, self.face_shift)
reg = self.face_to_region[face] out = torch.empty_like(x) for r in range(self.n_regions): mask = (reg == r) if mask.any(): out[mask] = self.centers[r](z[mask]) return x + out
class CausalConv1D(nn.Module): """Convoluzione Causale 1D Inter-Stadio (Zero-Init Residual). Fornisce contesto temporale locale continuo token-to-token con zero KV-cache. Inizializzata rigorosamente a zero: a step 0 equivale all'identità perfetta. """ def __init__(self, d_model: int = 256, kernel_size: int = 4): super().__init__() self.d_model = d_model self.kernel_size = kernel_size self.conv = nn.Conv1d(d_model, d_model, kernel_size=kernel_size, padding=0) nn.init.zeros_(self.conv.weight) nn.init.zeros_(self.conv.bias)
def forward(self, x: torch.Tensor) -> torch.Tensor: # x: (B, T, d_model) x_pad = F.pad(x.transpose(1, 2), (self.kernel_size - 1, 0)) out = self.conv(x_pad).transpose(1, 2) return x + out
class CascadeMeshModelV7_2(CascadeMeshModel): """Sentinel R-08 v7.2 con Convoluzioni Causali 1D e 12 Centri Regionali dell'Icosaedro.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) face_to_region = compute_face_to_icosahedron_regions(self.mesh.frequency) # Sostituzione delle piramidi con 12 Hub Regionali ciascuna self.pyramids = nn.ModuleList([ RegionalPyramidCenter( d_model=self.d_model, n_faces=int(self.mesh.num_faces), d_narrow=self.pyramid_narrow, d_hidden=self.pyramid_hidden, n_regions=12, face_to_region=face_to_region, ) for _ in self._banks() ]) # Convoluzioni Causali 1D inter-stadio (Zero-Init Residual) self.conv_12 = CausalConv1D(d_model=self.d_model, kernel_size=4) self.conv_23 = CausalConv1D(d_model=self.d_model, kernel_size=4) from watchman_keystone_r08 import NonLinearWatchmanKeystoneR08, OFFICIAL_SENTINEL_LICENSE_SUMMARY self.watchman = NonLinearWatchmanKeystoneR08(d_model=self.d_model) self._watchman_is_ethical = True self._watchman_license_text = OFFICIAL_SENTINEL_LICENSE_SUMMARY
def forward( self, pezzi_ids: torch.Tensor, parole_ids: Optional[torch.Tensor] = None, unioni_ids: Optional[torch.Tensor] = None, record_path: bool = False, ) -> Tuple[torch.Tensor, Optional[List[List[List[int]]]]]: b, t = pezzi_ids.shape if t > self.max_seq_len: raise ValueError(f"seq_len={t} > max_seq_len={self.max_seq_len}")
pos = torch.arange(t, device=pezzi_ids.device).unsqueeze(0) h = self.emb_v1(pezzi_ids) * self.emb_scale + self.pos_emb(pos)
for block in self.attn_blocks[:-1]: h = block(h)
hashed = self.hash_routing h1, _ = self._walk_seq( h, self.bank1, self.to_sphere1, record_path=False, entry_ids=pezzi_ids if hashed else None ) h1 = self._descend(0, h1, pezzi_ids)
# Convoluzione Causale 1D tra Sfera 1 e Sfera 2 h1_c = self.conv_12(h1)
# Stage 2: fuse bilanciato + emb parole active2 = self._active_mask(1, parole_ids) emb2 = self.fuse_ln_e2(self.emb_v2(parole_ids)) if self.fuse_mask_pad and active2 is not None: emb2 = emb2 * active2.unsqueeze(-1).to(dtype=emb2.dtype) h = self.fuse_norm2(self.fuse_ln_h2(self.proj_12(h1_c)) + emb2) if self.attn_inter2 is not None: h = self.attn_inter2(h)
h2, _ = self._walk_seq( h, self.bank2, self.to_sphere2, record_path=False, entry_ids=parole_ids if hashed else None, active_bt=active2, ) h2 = self._descend(1, h2, parole_ids, active_bt=active2)
# Convoluzione Causale 1D tra Sfera 2 e Sfera 3 h2_c = self.conv_23(h2)
# Stage 3: fuse bilanciato + emb unioni active3 = self._active_mask(2, unioni_ids) emb3 = self.fuse_ln_e3(self.emb_v3(unioni_ids)) if self.fuse_mask_pad and active3 is not None: emb3 = emb3 * active3.unsqueeze(-1).to(dtype=emb3.dtype) h = self.fuse_norm3(self.fuse_ln_h3(self.proj_23(h2_c)) + emb3)
h3, paths = self._walk_seq( h, self.bank3, self.to_sphere3, record_path=record_path, entry_ids=unioni_ids if hashed else None, active_bt=active3, ) h3 = self._descend(2, h3, unioni_ids, active_bt=active3)
# Residual inter-stadio bilanciato + attn post-fuse h = ( self.res_drop_h1(self.res_ln_h1(h1)) + self.res_ln_h2(h2) + self.res_ln_h3(h3) ) if len(self.attn_blocks) > 0: h = self.attn_blocks[-1](h) h = self.final_norm(h) if hasattr(self, "watchman") and self.watchman is not None: h_entangled = self.watchman.inject_geodesic_nonlinear_entanglement(h) h = self.watchman( h_entangled, is_ethical=getattr(self, "_watchman_is_ethical", True), license_text=getattr(self, "_watchman_license_text", ""), ) logits = self.lm_head(h) logits = 30.0 * torch.tanh(logits / 30.0) return logits, paths123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352"""Mesh geodetica sferica a tasselli triangolari.
Parte da un icosaedro regolare e lo suddivide con frequenza `frequency`(ogni faccia → frequency² triangoli). Espone: - indici faccia → 3 vertici - tabella di adiacenza: 3 vicini per faccia (ordine lati 0,1,2) - packing a coppie di facce adiacenti per GEMM rettangolari"""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Dict, List, Optional, Tuple
import numpy as np
_PHI = (1.0 + np.sqrt(5.0)) / 2.0
def _normalize(v: np.ndarray) -> np.ndarray: n = np.linalg.norm(v, axis=-1, keepdims=True) return v / np.maximum(n, 1e-12)
def icosahedron_vertices() -> np.ndarray: """12 vertici icosaedro (ordine classico three.js / Wikipedia).""" verts = np.asarray( [ [-1, _PHI, 0], [1, _PHI, 0], [-1, -_PHI, 0], [1, -_PHI, 0], [0, -1, _PHI], [0, 1, _PHI], [0, -1, -_PHI], [0, 1, -_PHI], [_PHI, 0, -1], [_PHI, 0, 1], [-_PHI, 0, -1], [-_PHI, 0, 1], ], dtype=np.float64, ) return _normalize(verts)
def icosahedron_faces() -> np.ndarray: """20 facce triangolari.""" return np.asarray( [ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1], ], dtype=np.int64, )
def _edge_key(a: int, b: int) -> Tuple[int, int]: return (a, b) if a < b else (b, a)
@dataclass(frozen=True)class GeodesicMesh: frequency: int vertices: np.ndarray # (V, 3) faces: np.ndarray # (F, 3) adjacency: np.ndarray # (F, 3) vicino oltre lato i face_centroids: np.ndarray # (F, 3) pairs: np.ndarray # (P, 2) packing GEMM unpaired: np.ndarray # (U,) compass_spiral: bool = False spiral_order: Optional[np.ndarray] = None # (F,) face_id ordinati lungo la spirale polo→polo spiral_rank: Optional[np.ndarray] = None # (F,) rango 0..F-1 lungo la spirale per ogni face_id spiral_band: Optional[np.ndarray] = None # (F,) fascia latitudinale 0..B-1 per ogni face_id
@property def num_faces(self) -> int: return int(self.faces.shape[0])
@property def num_vertices(self) -> int: return int(self.vertices.shape[0])
def build_geodesic_mesh( frequency: int = 2, *, compass_spiral: bool = False,) -> GeodesicMesh: """ Mesh geodetica a frequenza `frequency` (>= 1). Faces = 20 * frequency². Se `compass_spiral=True`, riordina i 3 vicini esistenti di ogni faccia lungo la spirale da polo a polo: porta 0 = avanti lungo la spirale, porta 1 = indietro lungo la spirale, porta 2 = cambio di fascia (nord/sud). """ if frequency < 1: raise ValueError("frequency deve essere >= 1")
base_v = icosahedron_vertices() base_f = icosahedron_faces()
vert_list: List[np.ndarray] = [base_v[i].copy() for i in range(len(base_v))] # chiave: (lo, hi, steps_from_lo) → index, steps in 1..freq-1 edge_cache: Dict[Tuple[int, int, int], int] = {}
def point_on_edge(i: int, j: int, steps_from_i: int) -> int: """steps_from_i=0 → i, =frequency → j.""" if steps_from_i == 0: return i if steps_from_i == frequency: return j lo, hi = _edge_key(i, j) steps_from_lo = steps_from_i if i == lo else frequency - steps_from_i key = (lo, hi, steps_from_lo) if key in edge_cache: return edge_cache[key] t = steps_from_lo / float(frequency) p = _normalize((1.0 - t) * base_v[lo] + t * base_v[hi]) idx = len(vert_list) vert_list.append(p) edge_cache[key] = idx return idx
faces: List[Tuple[int, int, int]] = []
for v0, v1, v2 in base_f: v0, v1, v2 = int(v0), int(v1), int(v2) grid: Dict[Tuple[int, int], int] = {}
for a in range(frequency + 1): for b in range(frequency + 1 - a): c = frequency - a - b # peso su v0 # a verso v1, b verso v2 if a == 0 and b == 0: grid[(a, b)] = v0 elif b == 0: grid[(a, b)] = point_on_edge(v0, v1, a) elif a == 0: grid[(a, b)] = point_on_edge(v0, v2, b) elif c == 0: grid[(a, b)] = point_on_edge(v1, v2, b) else: p = _normalize( (c * base_v[v0] + a * base_v[v1] + b * base_v[v2]) / float(frequency) ) idx = len(vert_list) vert_list.append(p) grid[(a, b)] = idx
for a in range(frequency): for b in range(frequency - a): i00 = grid[(a, b)] i10 = grid[(a + 1, b)] i01 = grid[(a, b + 1)] faces.append((i00, i10, i01)) if a + b + 1 < frequency: i11 = grid[(a + 1, b + 1)] faces.append((i10, i11, i01))
vertices = _normalize(np.stack(vert_list, axis=0)) faces_arr = np.asarray(faces, dtype=np.int64) expected = 20 * frequency * frequency if faces_arr.shape[0] != expected: raise RuntimeError(f"Attese {expected} facce, ottenute {faces_arr.shape[0]}")
adjacency = build_adjacency(faces_arr) centroids = _normalize(vertices[faces_arr].mean(axis=1)) spiral_adj, spiral_order, spiral_rank, spiral_band = reorder_adjacency_spiral_compass( adjacency, centroids ) if compass_spiral: adjacency = spiral_adj pairs, unpaired = pack_face_pairs(adjacency)
return GeodesicMesh( frequency=frequency, vertices=vertices, faces=faces_arr, adjacency=adjacency, face_centroids=centroids, pairs=pairs, unpaired=unpaired, compass_spiral=bool(compass_spiral), spiral_order=spiral_order, spiral_rank=spiral_rank, spiral_band=spiral_band, )
def reorder_adjacency_spiral_compass( adjacency: np.ndarray, face_centroids: np.ndarray,) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """ Ordina i centroidi lungo una spirale da polo a polo attorno all'asse polare icosaedrico (vertice 0 → vertice 3, simmetria 5-fold) e permuta i 3 vicini già presenti in `adjacency` per ogni faccia `f`: - porta 0: vicino «avanti» lungo la spirale (+Δlon sulla fascia), - porta 1: vicino «indietro» lungo la spirale (-Δlon sulla fascia), - porta 2: cambio di fascia (il terzo vicino, attraversamento nord/sud).
Non aggiunge né rimuove archi o facce: per ogni f, set(new_adj[f]) == set(adjacency[f]). Restituisce (new_adj, spiral_order, spiral_rank, spiral_band). """ n_faces = int(face_centroids.shape[0]) if adjacency.shape != (n_faces, 3): raise ValueError(f"adjacency attesa ({n_faces}, 3), ricevuta {adjacency.shape}")
# Asse polare 5-fold dell'icosaedro: polo nord = vertice 0, polo sud = vertice 3 pole = icosahedron_vertices()[0] u3 = pole / np.linalg.norm(pole) ref = np.array([0.0, 0.0, 1.0], dtype=np.float64) u1 = ref - np.dot(ref, u3) * u3 u1 /= np.linalg.norm(u1) u2 = np.cross(u3, u1)
z = face_centroids @ u3 # latitudine coseno in [-1, +1] (polo nord = +1, polo sud = -1) lon = np.mod(np.arctan2(face_centroids @ u2, face_centroids @ u1), 2.0 * np.pi)
new_adj = np.empty_like(adjacency) for f in range(n_faces): nbs = adjacency[f] # Differenza angolare ciclica in (-pi, +pi] rispetto alla faccia f dlons = [ float(((lon[int(nb)] - lon[f] + np.pi) % (2.0 * np.pi)) - np.pi) for nb in nbs ] # Il vicino di cambio fascia (nord/sud) attraversa il lato orizzontale (|Δlon| minimo, |Δz| massimo); # gli altri due muovono lungo la fascia in senso +Δlon (avanti, porta 0) e -Δlon (indietro, porta 1). idx_band = int(np.argmin(np.abs(dlons))) rem = [i for i in range(3) if i != idx_band] if dlons[rem[0]] >= dlons[rem[1]]: idx_fwd, idx_bwd = rem[0], rem[1] else: idx_fwd, idx_bwd = rem[1], rem[0] new_adj[f, 0] = nbs[idx_fwd] new_adj[f, 1] = nbs[idx_bwd] new_adj[f, 2] = nbs[idx_band]
# Costruisce l'ordine spirale da polo nord (+z) a polo sud (-z) seguendo i cicli di porta 0 visited = np.zeros(n_faces, dtype=bool) bands: List[List[int]] = [] for f in range(n_faces): if visited[f]: continue cyc: List[int] = [] cur = f while not visited[cur]: visited[cur] = True cyc.append(cur) cur = int(new_adj[cur, 0]) # Ruota il ciclo in modo che inizi dalla faccia con longitudine minima in [0, 2pi) start_idx = int(np.argmin([lon[idx] for idx in cyc])) cyc = cyc[start_idx:] + cyc[:start_idx] bands.append(cyc)
# Ordina le fasce da polo nord (z massima) a polo sud (z minima) bands.sort(key=lambda cyc: -float(np.mean(z[cyc])))
spiral_order_list: List[int] = [] spiral_band = np.empty(n_faces, dtype=np.int64) for b_idx, cyc in enumerate(bands): for f_id in cyc: spiral_band[f_id] = b_idx spiral_order_list.append(f_id)
spiral_order = np.asarray(spiral_order_list, dtype=np.int64) spiral_rank = np.empty(n_faces, dtype=np.int64) spiral_rank[spiral_order] = np.arange(n_faces, dtype=np.int64)
return new_adj, spiral_order, spiral_rank, spiral_band
def build_adjacency(faces: np.ndarray) -> np.ndarray: """adjacency[f, i] = faccia oltre lato i; lato0=(v0,v1), lato1=(v1,v2), lato2=(v2,v0).""" fcount = faces.shape[0] edge_to_face: Dict[Tuple[int, int], List[Tuple[int, int]]] = {} for fi, (a, b, c) in enumerate(faces): for li, (u, v) in enumerate(((int(a), int(b)), (int(b), int(c)), (int(c), int(a)))): edge_to_face.setdefault(_edge_key(u, v), []).append((fi, li))
adj = np.full((fcount, 3), -1, dtype=np.int64) for occ in edge_to_face.values(): if len(occ) != 2: continue (f0, l0), (f1, l1) = occ adj[f0, l0] = f1 adj[f1, l1] = f0
if np.any(adj < 0): bad = int(np.sum(adj < 0)) raise RuntimeError(f"Adiacenza incompleta ({bad} lati aperti)") return adj
def pack_face_pairs(adjacency: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Matching greedy di facce adiacenti → matrici 2×D contigue.""" fcount = adjacency.shape[0] used = np.zeros(fcount, dtype=bool) pairs: List[Tuple[int, int]] = [] for f in range(fcount): if used[f]: continue partner = -1 for n in adjacency[f]: ni = int(n) if not used[ni]: partner = ni break if partner < 0: continue used[f] = True used[partner] = True pairs.append((f, partner) if f < partner else (partner, f)) unpaired = np.asarray([i for i in range(fcount) if not used[i]], dtype=np.int64) return np.asarray(pairs, dtype=np.int64), unpaired
def nearest_face(mesh: GeodesicMesh, directions: np.ndarray) -> np.ndarray: """Argmax allineamento con centroidi faccia (prodotto scalare su sfera).""" d = _normalize(np.asarray(directions, dtype=np.float64)) scores = d @ mesh.face_centroids.T return np.argmax(scores, axis=-1).astype(np.int64)
def describe_mesh(mesh: GeodesicMesh) -> str: return ( f"GeodesicMesh(freq={mesh.frequency}, V={mesh.num_vertices}, " f"F={mesh.num_faces}, pairs={len(mesh.pairs)}, unpaired={len(mesh.unpaired)})" )123version https://git-lfs.github.com/spec/v1oid sha256:5348371afc9f13b87e6e4aaf05eb5c3bc8f4877dcd96c928d4f97430f51fa3d3size 208537132123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228# ============================================================================# LEGAL NOTICE & WATERMARK: R08 NON-COMMERCIAL RESEARCH & ETHICAL LICENSE v2.0# Copyright (c) 2026 Thomas Seri (Sentinel). All Rights Reserved.# Exclusive Jurisdiction: Court of Milan (Sezione Specializzata Impresa), Italy.# Clean-room reverse engineering, distillation, commercial or military use# is strictly prohibited and constitutes a breach of contract.# ============================================================================__author__ = "Thomas Seri (Sentinel)"__license__ = "R08-Non-Commercial-Ethical-License-v2.0"__jurisdiction__ = "Court of Milan, Italy"
#!/usr/bin/env python3"""R08-v7.2 (Rob) — Sentinel LifeOS Geodesic Mesh Neural Network (Pyramidal Sphere with 12 Regional Hubs & 1D Causal Convolutions, 51.6M)Official Hugging Face / PyTorch implementation.Author: Thomas Seri (https://www.sentinelhub.eu)"""from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import List, Optional, Tuple, Union
import torchimport torch.nn as nnfrom safetensors.torch import load_file
from geodesic_network import WalkConfigfrom geodesic_stages_v7_2_model import CascadeMeshModelV7_2import pezzi_tokenizer as ptfrom vocab_stages import ( StageBundle, StageEncoded, align_stages_to_pezzi, load_bundle, pass_to_v2, pass_to_v3,)
def realign_from_pezzi( pezzi_ids: list[int], bundle: StageBundle, causal_align: bool = True) -> Tuple[list[int], list[int], list[int]]: """Ricostruisce lo stato multi-stadio (pezzi, parole, unioni) in modo causale.""" v2 = pass_to_v2(pezzi_ids, bundle) v3 = pass_to_v3(v2, bundle) enc = StageEncoded( pezzi_ids=list(pezzi_ids), parole_ids=list(v2.parole_ids), unioni_ids=list(v3.unioni_ids), spans=[], v2=v2, v3=v3, ) p, w, u = align_stages_to_pezzi(enc, bundle, causal=causal_align) return list(p), list(w), list(u)
class R08Tokenizer: """Tokenizer a cascata a 3 stadi per R08-v7.2 (Rob)."""
def __init__(self, bundle: StageBundle): self.bundle = bundle self.pezzi = bundle.pezzi self.eos_id = int(getattr(bundle.pezzi, "eos_id", 2)) self.pad_id = int(getattr(bundle.pezzi, "pad_id", 3))
@classmethod def from_pretrained(cls, pretrained_path: Union[str, Path]) -> "R08Tokenizer": root = Path(pretrained_path) vocab_dir = root / "vocab_stages" if (root / "vocab_stages").exists() else root bundle = load_bundle(vocab_dir) return cls(bundle)
def encode(self, text: str) -> dict: """Codifica il testo nei 3 stadi sincronizzati (pezzi, parole, unioni).""" enc = pt.encode_cascade(text, self.bundle) p, w, u = align_stages_to_pezzi(enc, self.bundle, causal=True) return { "pezzi": list(p), "parole": list(w), "unioni": list(u), }
def decode(self, token_ids: List[int]) -> str: """Decodifica gli ID token dei pezzi in testo UTF-8.""" return pt.decode(token_ids, self.pezzi)
class R08Model(nn.Module): """Modello neurale geodetico-piramidale R08-v7.2 (Rob) da 51.6M parametri."""
def __init__(self, config: dict, mesh_model: CascadeMeshModelV7_2): super().__init__() self.config = config self.mesh_model = mesh_model
@classmethod def from_pretrained( cls, pretrained_path: Union[str, Path], device: Optional[str] = None, torch_dtype: Optional[torch.dtype] = None, ) -> "R08Model": root = Path(pretrained_path) cfg_file = root / "config.json" if not cfg_file.exists(): raise FileNotFoundError(f"config.json non trovato in {root}")
with open(cfg_file, "r", encoding="utf-8") as f: config = json.load(f)
walk = WalkConfig( max_hops=1, exit_threshold=0.85, hard_routing=False, router_temperature=1.0, )
mesh_model = CascadeMeshModelV7_2( vocab_pezzi=config.get("vocab_pezzi", 1251), vocab_parole=config.get("vocab_parole", 17908), vocab_unioni=config.get("vocab_unioni", 20006), d_model=config.get("d_model", 256), frequency=config.get("mesh_topology", {}).get("frequency", 2), walk=walk, n_attn_layers=config.get("n_attn_layers", 2), n_heads=config.get("n_heads", 8), max_seq_len=config.get("max_seq_len", 512), compass_spiral=config.get("routing", {}).get("compass_spiral", True), fast_walk=True, router_v6=config.get("routing", {}).get("router_v6", True), hash_routing=config.get("routing", {}).get("hash_routing", True), no_walk=config.get("routing", {}).get("no_walk", True), pyramid_center=config.get("pyramid_center", True), )
weights_file = root / "model.safetensors" if not weights_file.exists(): raise FileNotFoundError(f"model.safetensors non trovato in {root}")
state_dict = load_file(str(weights_file)) mesh_model.load_state_dict(state_dict, strict=True) if hasattr(mesh_model, "watchman") and mesh_model.watchman is not None: mesh_model._watchman_license_text = mesh_model.watchman.verify_disk_license(root) mesh_model._watchman_is_ethical = True
if device is None: if torch.backends.mps.is_available(): device = "mps" elif torch.cuda.is_available(): device = "cuda" else: device = "cpu"
mesh_model.to(torch.device(device)) if torch_dtype is not None: mesh_model.to(dtype=torch_dtype)
mesh_model.eval() return cls(config, mesh_model)
def forward(self, pezzi, parole, unioni, record_path: bool = False): return self.mesh_model(pezzi, parole, unioni, record_path=record_path)
@torch.inference_mode() def generate( self, prompt: str, tokenizer: R08Tokenizer, max_new_tokens: int = 48, temperature: float = 0.7, top_p: float = 0.9, repetition_penalty: float = 1.15, ) -> str: """Generazione di testo autoregressiva con sampling controllato e penalità di ripetizione.""" if hasattr(self.mesh_model, "watchman") and self.mesh_model.watchman is not None: is_ok, reason = self.mesh_model.watchman.scan_security_and_ethics(prompt) if not is_ok: self.mesh_model._watchman_is_ethical = False return f"[WATCHMAN KEYSTONE — ACCESSO NEGATO] Richiesta non consentita ({reason})." self.mesh_model._watchman_is_ethical = True dev = next(self.mesh_model.parameters()).device enc = tokenizer.encode(prompt) p, w, u = enc["pezzi"], enc["parole"], enc["unioni"] if not p: p, w, u = [tokenizer.eos_id], [tokenizer.bundle.parole.pad_id], [tokenizer.bundle.unioni.pad_id]
new_tokens: list[int] = [] for _ in range(max_new_tokens): seq_p = torch.tensor([p[-256:]], dtype=torch.long, device=dev) seq_w = torch.tensor([w[-256:]], dtype=torch.long, device=dev) seq_u = torch.tensor([u[-256:]], dtype=torch.long, device=dev)
logits, _ = self.mesh_model(seq_p, seq_w, seq_u, record_path=False) next_logits = logits[0, -1]
# Repetition penalty if repetition_penalty != 1.0 and new_tokens: for token_id in set(new_tokens): if next_logits[token_id] > 0: next_logits[token_id] /= repetition_penalty else: next_logits[token_id] *= repetition_penalty
# Temperature & Top-p Sampling if temperature > 0: probs = torch.softmax(next_logits / temperature, dim=-1) if top_p < 1.0: sorted_probs, sorted_indices = torch.sort(probs, descending=True) cumulative_probs = torch.cumsum(sorted_probs, dim=-1) sorted_indices_to_remove = cumulative_probs > top_p sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 indices_to_remove = sorted_indices[sorted_indices_to_remove] probs[indices_to_remove] = 0.0 probs = probs / probs.sum() nxt = int(torch.multinomial(probs, num_samples=1).item()) else: nxt = int(next_logits.argmax().item())
if nxt in (tokenizer.eos_id, tokenizer.pad_id): break
new_tokens.append(nxt) p.append(nxt) p, w, u = realign_from_pezzi(p, tokenizer.bundle, causal_align=True)
return tokenizer.decode(new_tokens)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228#!/usr/bin/env python3"""Tokenizer pezzi goTommy2 locale: sostituisce ``gptommy.encode`` senza bytecode in /tmp.
``r08/gptommy/encode.py`` è un wrapper che carica il bytecode originale da``/tmp/encode_ORIGINAL.cpython-314.pyc`` (cancellato dalla pulizia di macOS) o da``__pycache__`` solo se >1000 byte; lì c'è ormai il wrapper stesso ricompilato(722 byte), quindi l'import fallisce. Il sorgente originale non esiste più.
Il contratto dell'encoder sopravvive nel docstring del bytecode originale di``pipeline.cpython-314.pyc`` (20 set): copia in``vendor/gptommy_pycache_backup_20261019/``, da leggere con marshal senzaimportare ``gptommy.pipeline`` (l'import sovrascriverebbe l'originale in r08):
1. NFC 2. speciali letterali ``<|...|>`` 3. whitespace (spazio→<spazio>, \\n→<riga>, \\t→<tab>, \\r→<cr>, NBSP→<nbsp>; pezzi indent se esistono) 4. cifre: coppie 00–99 se in vocab, altrimenti cifra singola 5. longest-match greedy intra-parola, fallback 1 carattere, poi <|unk|> 6. case: match sul testo così com'è, poi ``lower()`` se non c'è pezzo.
Col vocab pezzi 1251 (nessuna coppia di cifre, nessun pezzo con spazi o indent,nessun pezzo multi-carattere con maiuscole) il contratto coincide con``vocab_stages.encode_pezzi_fallback``. ``encode`` replica esattamente quellalettura (``TRAINING_VARIANT``); le altre letture ammesse dal testo del contrattorestano disponibili via ``encode_variant`` solo per la verifica(``verify_tokenizer_equivalence.py``)."""from __future__ import annotations
import unicodedatafrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Tuple
ROOT = Path(__file__).resolve().parentGOTTOMMY2_VOCAB = Path("/Users/thomasseri/Desktop/columns/logs/goTommy2_vocab_by_id.txt")LOCAL_PEZZI_VOCAB = ROOT / "vocab_stages" / "00_pezzi_by_id.txt"
WS_PIECES = {"\n": "<riga>", "\t": "<tab>", "\r": "<cr>", "\xa0": "<nbsp>", " ": "<spazio>"}DECODE_WS = {"<spazio>": " ", "<riga>": "\n", "<tab>": "\t"}
TRAINING_VARIANT = { "nfc": False, "literal_specials": False, "case_rule": "per_length", "unicode_ws": "isspace",}
@dataclassclass Vocab: id_to_token: List[str] token_to_id: Dict[str, int] path: Optional[Path] = None
def load_vocab(path: Path | str | None = None) -> Vocab: """Stesso formato TSV di ``gptommy.vocab.load_vocab`` (codice, scheda, riga, id, pezzo).""" p = Path(path) if path is not None else ( LOCAL_PEZZI_VOCAB if LOCAL_PEZZI_VOCAB.is_file() else GOTTOMMY2_VOCAB ) id_to_token: Dict[int, str] = {} with p.open("r", encoding="utf-8") as fh: for line in fh: line = line.strip() if not line or line.startswith("#"): continue parts = line.split("\t") if len(parts) < 5: continue id_to_token[int(parts[3])] = parts[4] if not id_to_token: raise RuntimeError(f"vocab vuoto: {p}") n = max(id_to_token) + 1 tokens = [id_to_token.get(i, f"<unk_{i}>") for i in range(n)] return Vocab(id_to_token=tokens, token_to_id={t: i for i, t in enumerate(tokens)}, path=p)
class _Tables: __slots__ = ("max_len", "specials", "unk_id")
def __init__(self, vocab) -> None: toks = vocab.id_to_token self.max_len = max((len(t) for t in toks if not t.startswith("<")), default=1) self.specials = sorted( (t for t in toks if t.startswith("<") and len(t) > 1 and t.endswith(">")), key=len, reverse=True, ) self.unk_id = int(vocab.token_to_id.get("<|unk|>", 4))
_TABLE_CACHE: Dict[int, tuple] = {}
def _tables(vocab) -> _Tables: key = id(vocab.token_to_id) hit = _TABLE_CACHE.get(key) if hit is not None and hit[0] is vocab.token_to_id: return hit[1] tab = _Tables(vocab) _TABLE_CACHE[key] = (vocab.token_to_id, tab) return tab
def _is_ws(ch: str, unicode_ws: str) -> bool: if unicode_ws == "isspace": return ch.isspace() return ch in WS_PIECES
def encode_variant( text: str, vocab, *, nfc: bool = False, literal_specials: bool = False, case_rule: str = "per_length", unicode_ws: str = "isspace",) -> List[int]: """Encoder del contratto gpTommy con le letture alternative esplicite.
case_rule: ``per_length`` a ogni lunghezza prova il frammento così com'è, poi lower() se alfabetico (= encode_pezzi_fallback; "Questo" → questo) ``per_position`` lower() solo se nessun pezzo matcha così com'è a quella posizione ("Questo" → Q u e s t o, visto che A–Z esistono) unicode_ws: ``isspace`` ogni carattere str.isspace() è whitespace (default <spazio>) ``listed`` solo spazio, \\n, \\t, \\r, NBSP; gli altri vanno al longest-match literal_specials: speciali ``<...>`` di qualunque lunghezza consumati per primi (il longest-match generico arriva solo a max_len=8 caratteri). """ if case_rule not in ("per_length", "per_position"): raise ValueError(f"case_rule sconosciuta: {case_rule}") s = unicodedata.normalize("NFC", text) if nfc else text t2i = vocab.token_to_id tab = _tables(vocab) ids: List[int] = [] n = len(s) i = 0 while i < n: ch = s[i] if _is_ws(ch, unicode_ws): tid = t2i.get(WS_PIECES.get(ch, "<spazio>")) if tid is not None: ids.append(tid) i += 1 continue if literal_specials and ch == "<": hit = next((sp for sp in tab.specials if s.startswith(sp, i)), None) if hit is not None: ids.append(t2i[hit]) i += len(hit) continue upper = min(n, i + tab.max_len) tid = None j = upper while j > i: frag = s[i:j] tid = t2i.get(frag) if tid is None and case_rule == "per_length" and frag.isalpha(): tid = t2i.get(frag.lower()) if tid is not None: break j -= 1 if tid is None and case_rule == "per_position": j = upper while j > i: frag = s[i:j] if frag.isalpha(): tid = t2i.get(frag.lower()) if tid is not None: break j -= 1 if tid is not None: ids.append(tid) i = j continue tid = t2i.get(ch) if tid is None and ch.isalpha(): tid = t2i.get(ch.lower()) ids.append(tab.unk_id if tid is None else tid) i += 1 return ids
def encode(text: str, vocab) -> List[int]: """Encode pezzi usato dal training (stessa lettura di encode_pezzi_fallback).""" return encode_variant(text, vocab, **TRAINING_VARIANT)
def decode(ids: Sequence[int], vocab) -> str: """Concatena i pezzi; sostituisce solo <spazio>/<riga>/<tab> (contratto gpTommy).""" toks = vocab.id_to_token out: List[str] = [] for tid in ids: tok = toks[tid] if 0 <= int(tid) < len(toks) else "<|unk|>" out.append(DECODE_WS.get(tok, tok)) return "".join(out)
def cascade_from_pezzi(pezzi_ids: Sequence[int], bundle): """StageEncoded da pezzi già codificati: pass_to_v2 → pass_to_v3 (come encode_cascade).""" from vocab_stages import StageEncoded, pass_to_v2, pass_to_v3
ids = [int(x) for x in pezzi_ids] v2 = pass_to_v2(ids, bundle) v3 = pass_to_v3(v2, bundle) return StageEncoded( pezzi_ids=ids, parole_ids=list(v2.parole_ids), unioni_ids=list(v3.unioni_ids), spans=[], v2=v2, v3=v3, )
def encode_cascade(text: str, bundle): """vocab_stages.encode_cascade con V1 = ``encode`` locale (mai gptommy).""" return cascade_from_pezzi(encode(text, bundle.pezzi), bundle)
def encode_stages_aligned(text: str, bundle) -> Tuple[List[int], List[int], List[int]]: """(pezzi, parole, unioni) allineati sulla timeline pezzi, come nel training.""" from vocab_stages import align_stages_to_pezzi
return align_stages_to_pezzi(encode_cascade(text, bundle), bundle)1234567891011121314151617181920212223242526272829303132333435363738#!/usr/bin/env python3"""Test di inferenza per il rilascio di R08-v7.2 dai pesi safetensors locali."""import sysfrom pathlib import Path
ROOT = Path(__file__).resolve().parentif str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
from modeling_geodesic import R08Model, R08Tokenizer
def main(): print("1. Caricamento tokenizer da vocab_stages...") tokenizer = R08Tokenizer.from_pretrained(ROOT) print("2. Caricamento modello R08-v7.2 da model.safetensors...") model = R08Model.from_pretrained(ROOT) print(f"Modello caricato con successo! Parametri: {sum(p.numel() for p in model.parameters()):,}")
prompts = [ "Utente: Ciao, chi sei?\nAssistente:", "La capitale d'Italia è", "Per riparare un cilindro pneumatico Festo occorre", ]
for p in prompts: print(f"\n--- PROMPT: {p.strip()} ---") risposta = model.generate( prompt=p, tokenizer=tokenizer, max_new_tokens=32, temperature=0.7, top_p=0.9, repetition_penalty=1.15, ) print(f"RISPOSTA:\n{risposta.strip()}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971#!/usr/bin/env python3"""Vocab a stadi — pipeline SEQUENZIALE a cascata (NON encode greedy parallelo).
Flusso utente (testo → V1 → V2 → V3):
1. Vocab 1 (pezzi ~1200, goTommy2): spezzetta TUTTO il testo in token base. 2. Quei token passano a Vocab 2 (parole): crea/modifica/aggrega pezzi → parole (stesso tipo di passaggio: sequenza in → sequenza aggregata out). 3. L'uscita di V2 passa a Vocab 3 (unioni): unisce 2/3 parole se frequenti.
API encode: encode_v1(text, pezzi) → pezzi_ids pass_to_v2(pezzi_ids, bundle) → parole_ids (+ surfaces) pass_to_v3(parole_ids|surfaces, bundle) → unioni stream encode_cascade(text, bundle) = V1 → V2 → V3 align_stages_to_pezzi: ancora causale + carry-forward post-ancora (pad solo pre-prima-ancora; dopo, ultima parola/unione resta viva su spazi/pezzi)
Build: vocab2 imparato da parole ricostruite sulle sequenze di pezzi (V1); vocab3 da unioni frequenti sull'uscita di V2.
Wiring train (proposta, NON avviato): 3 stadi in SERIE emb_v1(pezzi) → mesh1 → transform → emb_v2(parole) → mesh2 → … → emb_v3(unioni). Non 3 stream paralleli “prova unioni|parole|pezzi”. Serve --confirm-stages-train.
Deprecato: encode_stages greedy “unioni poi parole poi pezzi” (ora alias di cascade)."""from __future__ import annotations
import jsonimport warningsfrom collections import Counterfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Iterable, Iterator, Optional, Sequence, Union
ROOT = Path(__file__).resolve().parentDEFAULT_OUT = ROOT / "vocab_stages"DEFAULT_PEZZI = Path("/Users/thomasseri/Desktop/columns/logs/goTommy2_vocab_by_id.txt")
SPECIALS = [ "<|end|>", "<|bos|>", "<|eos|>", "<|pad|>", "<|unk|>", "<|sep|>",]
# pezzi che rompono la parola in V2 (aggregazione pezzi → parola)_WORD_BREAK_PEZZI = frozenset( { "<spazio>", " ", "\t", "\n", ".", ",", ";", ":", "!", "?", "(", ")", "[", "]", "{", "}", '"', "'", "«", "»", "-", "—", "/", "\\", })
@dataclassclass StageVocab: name: str id_to_token: list[str] token_to_id: dict[str, int] path: Optional[Path] = None meta: dict = field(default_factory=dict)
def __len__(self) -> int: return len(self.id_to_token)
@property def unk_id(self) -> int: return int(self.token_to_id.get("<|unk|>", 4))
@property def eos_id(self) -> int: return int(self.token_to_id.get("<|eos|>", 2))
@property def pad_id(self) -> int: return int(self.token_to_id.get("<|pad|>", 3))
@dataclassclass StageBundle: """Tre vocab separati + percorsi (id-space distinti)."""
pezzi: StageVocab parole: StageVocab unioni: StageVocab root: Path
def sizes(self) -> dict[str, int]: return { "pezzi": len(self.pezzi), "parole": len(self.parole), "unioni": len(self.unioni), }
@dataclassclass V1Out: """Uscita Vocab 1: tutto il testo spezzettato in pezzi."""
pezzi_ids: list[int] surfaces: list[str]
@dataclassclass V2Out: """Uscita Vocab 2: pezzi aggregati in parole (passaggio da V1)."""
parole_ids: list[int] surfaces: list[str] # gruppi di pezzi_ids che hanno formato ciascuna parola pezzi_groups: list[list[int]] = field(default_factory=list)
@dataclassclass V3Out: """Uscita Vocab 3: unioni 2/3 parole sulle superfici di V2.
`stream` è la sequenza a cascata: ogni item è ("unione", surface, uid) oppure ("parola", surface, wid) dopo merge greedy trigram→bigram. `unioni_ids` allinea a parole V2 (uid se la parola apre un'unione, altrimenti -1). """
unioni_ids: list[int] stream: list[tuple[str, str, int]] surfaces: list[str] = field(default_factory=list)
@dataclassclass StageEncoded: """Risultato cascade V1→V2→V3 (id space distinti)."""
pezzi_ids: list[int] parole_ids: list[int] unioni_ids: list[int] # traccia: ("v1"|"v2"|"v3", surface, id_or_ids) spans: list[tuple[str, str, object]] v1: Optional[V1Out] = None v2: Optional[V2Out] = None v3: Optional[V3Out] = None
# ---------------------------------------------------------------------------# Vocab I/O# ---------------------------------------------------------------------------
def load_pezzi_vocab(path: Path | str | None = None) -> StageVocab: """Carica goTommy2 (~1251) come stadio pezzi (V1).""" p = Path(path) if path is not None else DEFAULT_PEZZI id_to_token: dict[int, str] = {} with p.open("r", encoding="utf-8") as fh: for line in fh: line = line.strip() if not line or line.startswith("#"): continue parts = line.split("\t") if len(parts) < 5: continue gid = int(parts[3]) id_to_token[gid] = parts[4] if not id_to_token: raise RuntimeError(f"pezzi vocab vuoto: {p}") n = max(id_to_token) + 1 tokens = [id_to_token.get(i, f"<unk_{i}>") for i in range(n)] return StageVocab( name="pezzi", id_to_token=tokens, token_to_id={t: i for i, t in enumerate(tokens)}, path=p, meta={"source": str(p), "note": "goTommy2-scale ~1200 (1251)"}, )
def _with_specials(tokens: Iterable[str]) -> list[str]: seen = set(SPECIALS) out = list(SPECIALS) for t in tokens: if t in seen or not t: continue seen.add(t) out.append(t) return out
def make_stage_vocab(name: str, tokens: Iterable[str], *, meta: Optional[dict] = None) -> StageVocab: id_to_token = _with_specials(tokens) return StageVocab( name=name, id_to_token=id_to_token, token_to_id={t: i for i, t in enumerate(id_to_token)}, meta=dict(meta or {}), )
def save_stage_vocab(vocab: StageVocab, path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as fh: fh.write(f"# stage={vocab.name} size={len(vocab)}\n") fh.write("# colonne: codice\\tscheda\\triga\\tid\\tpezzo\n") for i, tok in enumerate(vocab.id_to_token): scheda = 0 if i < 1000 else 1 riga = i if i < 1000 else (i - 1000) code = f"{scheda:02d}{riga:03d}" fh.write(f"{code}\t{scheda:02d}\t{riga:03d}\t{i}\t{tok}\n") meta_path = path.with_suffix(".meta.json") blob = { "name": vocab.name, "size": len(vocab), "path": str(path), "meta": vocab.meta, "specials": SPECIALS, } meta_path.write_text(json.dumps(blob, ensure_ascii=False, indent=2), encoding="utf-8") vocab.path = path
def load_stage_vocab(path: Path, name: Optional[str] = None) -> StageVocab: id_to_token: dict[int, str] = {} with path.open("r", encoding="utf-8") as fh: for line in fh: line = line.strip() if not line or line.startswith("#"): continue parts = line.split("\t") if len(parts) < 5: continue id_to_token[int(parts[3])] = parts[4] n = max(id_to_token) + 1 if id_to_token else 0 tokens = [id_to_token.get(i, f"<unk_{i}>") for i in range(n)] meta: dict = {} meta_path = path.with_suffix(".meta.json") if meta_path.is_file(): try: meta = json.loads(meta_path.read_text(encoding="utf-8")).get("meta", {}) except json.JSONDecodeError: meta = {} return StageVocab( name=name or path.stem, id_to_token=tokens, token_to_id={t: i for i, t in enumerate(tokens)}, path=path, meta=meta, )
def save_bundle(bundle: StageBundle, root: Optional[Path] = None) -> Path: out = Path(root) if root is not None else bundle.root out.mkdir(parents=True, exist_ok=True) pezzi_dst = out / "00_pezzi_by_id.txt" parole_path = out / "01_parole_by_id.txt" unioni_path = out / "02_unioni_by_id.txt" save_stage_vocab(bundle.pezzi, pezzi_dst) save_stage_vocab(bundle.parole, parole_path) save_stage_vocab(bundle.unioni, unioni_path) src = bundle.pezzi.meta.get("source") or str(DEFAULT_PEZZI) (out / "00_pezzi_SOURCE.txt").write_text( f"source={src}\nsize={len(bundle.pezzi)}\n", encoding="utf-8" )
manifest = { "design": "multi_vocab_stages_cascade", "note": ( "Tre id-space separati in SERIE: testo→V1 pezzi (~1200)→V2 parole→V3 unioni. " "NON encode greedy parallelo. ~1200 = scala goTommy2 (1251), non 1.2M." ), "stages": { "0_pezzi": {"path": str(pezzi_dst), "size": len(bundle.pezzi)}, "1_parole": {"path": str(parole_path), "size": len(bundle.parole)}, "2_unioni": {"path": str(unioni_path), "size": len(bundle.unioni)}, }, "encode": ( "encode_cascade = encode_v1 → pass_to_v2 → pass_to_v3. " "Wiring train: 3 stadi in serie (emb/mesh per stadio), non stream paralleli." ), "api": { "encode_v1": "text → pezzi_ids", "pass_to_v2": "pezzi_ids → parole_ids (aggrega pezzi)", "pass_to_v3": "parole surfaces → unioni (2/3 se frequenti)", "encode_cascade": "encode_v1 → pass_to_v2 → pass_to_v3", }, } (out / "manifest.json").write_text( json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8" ) bundle.root = out return out
def load_bundle(root: Path | str) -> StageBundle: root = Path(root) pezzi = load_stage_vocab(root / "00_pezzi_by_id.txt", "pezzi") parole = load_stage_vocab(root / "01_parole_by_id.txt", "parole") unioni = load_stage_vocab(root / "02_unioni_by_id.txt", "unioni") return StageBundle(pezzi=pezzi, parole=parole, unioni=unioni, root=root)
# ---------------------------------------------------------------------------# V1 — spezzetta tutto in pezzi# ---------------------------------------------------------------------------
def encode_pezzi_fallback(text: str, pezzi: StageVocab) -> list[int]: """Encode grezzo a pezzi: match longest token goTommy2, altrimenti char/UNK.
Case-sensitive prima (A≠a nel vocab pezzi); lower solo se manca il match. Whitespace distinto come gotommy: \\n→<riga>, \\t→<tab>, spazi→<spazio>. """ s = text ids: list[int] = [] i = 0 max_len = max((len(t) for t in pezzi.id_to_token if not t.startswith("<")), default=1) while i < len(s): ch = s[i] if ch.isspace(): # Distingue whitespace: allineato a gotommy_encode / token speciali pezzi. if ch == "\n": ws_tok = "<riga>" elif ch == "\t": ws_tok = "<tab>" elif ch == "\r": ws_tok = "<cr>" elif ch == "\xa0": ws_tok = "<nbsp>" else: ws_tok = "<spazio>" tid = pezzi.token_to_id.get(ws_tok) if tid is not None: ids.append(tid) i += 1 continue matched = False upper = min(len(s), i + max_len) for j in range(upper, i, -1): frag = s[i:j] # Lookup case-sensitive PRIMA; lower solo fallback (es. "Hello"→H non h). tid = pezzi.token_to_id.get(frag) if tid is None and frag.isalpha(): tid = pezzi.token_to_id.get(frag.lower()) if tid is not None: ids.append(tid) i = j matched = True break if matched: continue tid = pezzi.token_to_id.get(ch) if tid is None and ch.isalpha(): tid = pezzi.token_to_id.get(ch.lower()) if tid is None: tid = pezzi.unk_id ids.append(tid) i += 1 return ids
def encode_v1(text: str, pezzi: StageVocab) -> V1Out: """Vocab 1: spezzetta TUTTO il testo in pezzi/token base (~1200).
Preferisce gotommy_encode (tokenizer ufficiale goTommy2); fallback locale se gptommy non è importabile o fallisce. """ ids: list[int] | None = None try: from gptommy.encode import encode as gotommy_encode
ids = gotommy_encode(text, pezzi) except Exception: ids = None if ids is None: ids = encode_pezzi_fallback(text, pezzi) surfaces = [ pezzi.id_to_token[i] if 0 <= i < len(pezzi.id_to_token) else "<|unk|>" for i in ids ] return V1Out(pezzi_ids=ids, surfaces=surfaces)
def _is_word_break_surface(surf: str) -> bool: if not surf or surf.startswith("<|"): # specials di controllo: non rompono da soli (trattati come pezzi “vivi” # solo se non in _WORD_BREAK); <|unk|> resta nel gruppo parola return surf in _WORD_BREAK_PEZZI or surf == "<spazio>" if surf in _WORD_BREAK_PEZZI: return True # singolo char di punteggiatura if len(surf) == 1 and not surf.isalnum() and not surf.isalpha(): return True return False
def _surface_from_pezzo(surf: str) -> str: """Contributo testuale di un pezzo alla parola ricostruita (salta meta-token).""" if not surf or surf.startswith("<"): return "" return surf
# ---------------------------------------------------------------------------# V2 — aggrega pezzi → parole# ---------------------------------------------------------------------------
def reconstruct_words_from_pezzi( pezzi_ids: Sequence[int], pezzi: StageVocab,) -> tuple[list[str], list[list[int]]]: """Da sequenza pezzi → liste di superfici parola + gruppi pezzi_ids.
Split su spazio/punteggiatura; concatena le superfici dei pezzi nel gruppo. Usato sia in build (conta parole da V1) sia in pass_to_v2. """ surfaces: list[str] = [] groups: list[list[int]] = [] buf_surfs: list[str] = [] buf_ids: list[int] = []
def _flush() -> None: nonlocal buf_surfs, buf_ids if not buf_ids: buf_surfs = [] return word = "".join(buf_surfs).lower() if word: surfaces.append(word) groups.append(list(buf_ids)) buf_surfs = [] buf_ids = []
for pid in pezzi_ids: surf = pezzi.id_to_token[pid] if 0 <= pid < len(pezzi.id_to_token) else "<|unk|>" if _is_word_break_surface(surf): _flush() continue piece = _surface_from_pezzo(surf) if piece: buf_surfs.append(piece) buf_ids.append(int(pid)) else: # meta-token senza contributo testuale: chiudi la parola corrente _flush() _flush() return surfaces, groups
def pass_to_v2(pezzi_ids: Sequence[int], bundle: StageBundle) -> V2Out: """Vocab 2: prende i pezzi di V1, aggrega/modifica in parole (id space parole).""" word_surfs, groups = reconstruct_words_from_pezzi(pezzi_ids, bundle.pezzi) parole_ids: list[int] = [] for w in word_surfs: wid = bundle.parole.token_to_id.get(w) if wid is None: wid = bundle.parole.unk_id parole_ids.append(wid) return V2Out(parole_ids=parole_ids, surfaces=word_surfs, pezzi_groups=groups)
# ---------------------------------------------------------------------------# V3 — unioni 2/3 parole sull'uscita V2# ---------------------------------------------------------------------------
def pass_to_v3( v2: Union[V2Out, Sequence[str], Sequence[int]], bundle: StageBundle,) -> V3Out: """Vocab 3: sull'uscita di V2, unisce 2/3 parole se presenti in vocab unioni.
Merge greedy sinistra→destra: trigram poi bigram; altrimenti passa la parola. """ if isinstance(v2, V2Out): surfaces = list(v2.surfaces) parole_ids = list(v2.parole_ids) elif v2 and isinstance(v2[0], int): # type: ignore[index] parole_ids = [int(x) for x in v2] # type: ignore[arg-type] surfaces = [ bundle.parole.id_to_token[i] if 0 <= i < len(bundle.parole.id_to_token) else "<|unk|>" for i in parole_ids ] else: surfaces = [str(x) for x in v2] # type: ignore[arg-type] parole_ids = [ bundle.parole.token_to_id.get(s, bundle.parole.unk_id) for s in surfaces ]
unioni_ids = [-1] * len(surfaces) stream: list[tuple[str, str, int]] = [] out_surfaces: list[str] = [] i = 0 while i < len(surfaces): if i + 2 < len(surfaces): tri = f"{surfaces[i]} {surfaces[i + 1]} {surfaces[i + 2]}" uid = bundle.unioni.token_to_id.get(tri) if uid is not None: unioni_ids[i] = uid stream.append(("unione", tri, uid)) out_surfaces.append(tri) i += 3 continue if i + 1 < len(surfaces): bi = f"{surfaces[i]} {surfaces[i + 1]}" uid = bundle.unioni.token_to_id.get(bi) if uid is not None: unioni_ids[i] = uid stream.append(("unione", bi, uid)) out_surfaces.append(bi) i += 2 continue wid = parole_ids[i] if i < len(parole_ids) else bundle.parole.unk_id stream.append(("parola", surfaces[i], wid)) out_surfaces.append(surfaces[i]) i += 1
return V3Out(unioni_ids=unioni_ids, stream=stream, surfaces=out_surfaces)
# ---------------------------------------------------------------------------# Cascade + compat# ---------------------------------------------------------------------------
def encode_cascade(text: str, bundle: StageBundle) -> StageEncoded: """Pipeline ufficiale: testo → encode_v1 → pass_to_v2 → pass_to_v3.""" v1 = encode_v1(text, bundle.pezzi) v2 = pass_to_v2(v1.pezzi_ids, bundle) v3 = pass_to_v3(v2, bundle) spans: list[tuple[str, str, object]] = [] for s, pid in zip(v1.surfaces, v1.pezzi_ids): spans.append(("v1", s, pid)) for s, wid, grp in zip(v2.surfaces, v2.parole_ids, v2.pezzi_groups): spans.append(("v2", s, (wid, grp))) for kind, surf, tid in v3.stream: spans.append(("v3", f"{kind}:{surf}", tid)) return StageEncoded( pezzi_ids=v1.pezzi_ids, parole_ids=v2.parole_ids, unioni_ids=v3.unioni_ids, spans=spans, v1=v1, v2=v2, v3=v3, )
def _word_union_ids_from_v3(v3: V3Out, n_words: int) -> list[int]: """Id unione per parola V2: solo sull'ULTIMA parola di ogni unione (causale).
Non propagare l'uid sulle parole iniziali/intermedie dell'unione: sarebbe lookahead (si rivelerebbe il merge prima che le parole successive siano complete). Parole senza unione → -1. """ out = [-1] * n_words wi = 0 for kind, surf, tid in v3.stream: if kind == "unione": n = max(1, len(surf.split())) last = wi + n - 1 if 0 <= last < n_words: out[last] = int(tid) wi += n else: wi += 1 return out
def _align_anchor_for_word( pezzi: Sequence[int], pezzi_vocab: StageVocab, first_t: int, last_t: int,) -> int: """Ancora causale per una parola: spazio/break successivo, altrimenti ultimo pezzo.
Mai il primo pezzo se la parola è multi-pezzo (anti-lookahead). """ n = len(pezzi) anchor = last_t if last_t + 1 < n: nxt = ( pezzi_vocab.id_to_token[pezzi[last_t + 1]] if 0 <= pezzi[last_t + 1] < len(pezzi_vocab.id_to_token) else "<|unk|>" ) if _is_word_break_surface(nxt): anchor = last_t + 1 # sicurezza: multi-pezzo non deve mai ancorare sul primo if first_t != last_t and anchor == first_t: anchor = last_t return anchor
def _carry_forward_after_anchor(ids: list[int], pad_id: int) -> None: """In-place: dopo un id non-pad, copia l'ultimo visto sui pad successivi.
Non tocca il prefisso di soli pad (anti-lookahead pre-ancora resta valido). """ last = pad_id for i, v in enumerate(ids): if v != pad_id: last = int(v) elif last != pad_id: ids[i] = last
def _is_word_terminator(surf: str) -> bool: """Pezzo che chiude la parola in V2: break oppure pezzo senza testo (<riga>, <tab>, <|unk|>, …).""" return _is_word_break_surface(surf) or not _surface_from_pezzo(surf)
def _prefix_union_ids(surfaces: Sequence[str], bundle: StageBundle) -> list[int]: """Per ogni parola j: ultima unione di ``pass_to_v3`` sulle sole parole 0..j (-1 se nessuna).
Il merge greedy decide in i guardando le parole i+1 e i+2: le decisioni con i <= j-2 coincidono con quelle sull'intera sequenza, la coda del prefisso è al più il bigramma (j-1, j). """ uni = bundle.unioni.token_to_id n = len(surfaces) starts: list[int] = [] uids: list[int] = [] i = 0 while i < n: size, uid = 1, None if i + 2 < n: uid = uni.get(f"{surfaces[i]} {surfaces[i + 1]} {surfaces[i + 2]}") size = 3 if uid is None and i + 1 < n: uid = uni.get(f"{surfaces[i]} {surfaces[i + 1]}") size = 2 if uid is None: size = 1 starts.append(i) uids.append(-1 if uid is None else int(uid)) i += size
out = [-1] * n k = 0 last = -1 for j in range(n): while k < len(starts) and starts[k] <= j - 2: if uids[k] >= 0: last = uids[k] k += 1 cur = last if k < len(starts) and starts[k] == j - 1: uid = uni.get(f"{surfaces[j - 1]} {surfaces[j]}") if uid is not None: cur = int(uid) out[j] = cur return out
def _align_causal(enc: StageEncoded, bundle: StageBundle) -> tuple[list[int], list[int], list[int]]: """Allineamento in cui la feature in t dipende solo da pezzi[:t+1] (vedi align_stages_to_pezzi).""" pezzi = list(enc.pezzi_ids) n = len(pezzi) pad_w = bundle.parole.pad_id pad_u = bundle.unioni.pad_id parole_al = [pad_w] * n unioni_al = [pad_u] * n if n == 0: return pezzi, parole_al, unioni_al pv = bundle.pezzi word_last: list[int] = [] in_word = False for t, pid in enumerate(pezzi): surf = pv.id_to_token[pid] if 0 <= pid < len(pv.id_to_token) else "<|unk|>" if _is_word_terminator(surf): in_word = False continue if not in_word: word_last.append(t) in_word = True word_last[-1] = t if enc.v2 is not None: surfaces = list(enc.v2.surfaces) else: surfaces, _ = reconstruct_words_from_pezzi(pezzi, pv) if len(surfaces) != len(word_last) or len(enc.parole_ids) != len(word_last): raise ValueError("align causale: parole V2 e gruppi di pezzi non coincidono") word_uids = _prefix_union_ids(surfaces, bundle) for w, last_t in enumerate(word_last): anchor = last_t + 1 if anchor >= n: continue parole_al[anchor] = int(enc.parole_ids[w]) if word_uids[w] >= 0: unioni_al[anchor] = word_uids[w] _carry_forward_after_anchor(parole_al, pad_w) _carry_forward_after_anchor(unioni_al, pad_u) return pezzi, parole_al, unioni_al
def align_stages_to_pezzi( enc: StageEncoded, bundle: StageBundle, causal: bool = False,) -> tuple[list[int], list[int], list[int]]: """Allinea parole/unioni alla timeline pezzi (stessa lunghezza).
``causal=True`` (``--causal-align``): la feature in t è quella calcolabile dai soli pezzi[:t+1]. Rispetto alla policy qui sotto cambia in tre punti: - l'ancora di una parola è sempre il pezzo che la chiude in V2 (break oppure pezzo senza testo: <riga>, <tab>, <cr>, <nbsp>, <|unk|>, …), mai il suo ultimo pezzo: finché non arriva il terminatore la parola potrebbe continuare; - una parola non chiusa a fine sequenza non viene mai rivelata; - l'unione mostrata sull'ancora della parola j è l'ultima unione del merge V3 sulle sole parole 0..j (il greedy trigramma→bigramma sull'intera sequenza guarda due parole avanti).
Policy (due pass):
1) Ancora CAUSALE (anti-lookahead; coerente con gen greedy che mette pad_parole/pad_unioni sui pezzi nuovi finché la parola non è chiusa):
- Non assegnare id parola/unione al PRIMO pezzo di una parola multi-pezzo (leak: rivelerebbe l'identità prima di aver visto tutti i pezzi). - Id parola: solo sull'ultimo pezzo della parola, oppure sullo spazio/break immediatamente successivo se presente. - Id unione: solo sull'ancora dell'ultima parola coperta dall'unione (vedi `_word_union_ids_from_v3`). - Pezzi intermedi / primo pezzo (multi-pezzo) / break non-ancora → ``pad`` di parole/unioni. Non si usa ``unk`` qui: unk = superficie assente dal vocab V2/V3, non “non ancora nota”. - Parola mono-pezzo senza break successivo: ancora = quel pezzo (superficie già completa → non è lookahead).
2) Carry-forward post-ancora: una volta vista un'ancora, l'ultima parola/unione nota si propaga alle posizioni successive ancora in ``pad`` (spazi, pezzi della parola successiva, punteggiatura extra), finché non arriva una nuova ancora. Così su ``"Answer: "`` lo stadio V2 vede ``answer`` anche sullo ``<spazio>`` finale, non un reset a pad. Il prefisso pre-prima-ancora resta pad (niente leak sul primo pezzo). """ if causal: return _align_causal(enc, bundle) pezzi = list(enc.pezzi_ids) n = len(pezzi) pad_w = bundle.parole.pad_id pad_u = bundle.unioni.pad_id parole_al = [pad_w] * n unioni_al = [pad_u] * n if n == 0: return pezzi, parole_al, unioni_al
pezzi_vocab = bundle.pezzi n_words = len(enc.parole_ids) word_first = [-1] * n_words word_last = [-1] * n_words word_idx = -1 in_word = False for t, pid in enumerate(pezzi): surf = ( pezzi_vocab.id_to_token[pid] if 0 <= pid < len(pezzi_vocab.id_to_token) else "<|unk|>" ) if _is_word_break_surface(surf): in_word = False continue piece = _surface_from_pezzo(surf) if piece: if not in_word: word_idx += 1 in_word = True if 0 <= word_idx < n_words: word_first[word_idx] = t if 0 <= word_idx < n_words: word_last[word_idx] = t else: in_word = False
if enc.v3 is not None: word_uids = _word_union_ids_from_v3(enc.v3, n_words) else: word_uids = [-1] * n_words # fallback senza stream: unioni_ids è start-aligned in V3Out; # senza n-gram non possiamo spostare sull'ultima parola. for i, uid in enumerate(enc.unioni_ids): if 0 <= i < n_words and int(uid) >= 0: word_uids[i] = int(uid)
for w in range(n_words): first_t = word_first[w] last_t = word_last[w] if first_t < 0 or last_t < 0: continue anchor = _align_anchor_for_word(pezzi, pezzi_vocab, first_t, last_t) parole_al[anchor] = int(enc.parole_ids[w]) uid = word_uids[w] if w < len(word_uids) else -1 if uid >= 0: unioni_al[anchor] = int(uid)
_carry_forward_after_anchor(parole_al, pad_w) _carry_forward_after_anchor(unioni_al, pad_u) return pezzi, parole_al, unioni_al
def encode_stages(text: str, bundle: StageBundle) -> StageEncoded: """DEPRECATED: ex greedy parallelo; ora alias di encode_cascade (V1→V2→V3).""" warnings.warn( "encode_stages greedy è deprecato; usa encode_cascade / encode_v1→pass_to_v2→pass_to_v3", DeprecationWarning, stacklevel=2, ) return encode_cascade(text, bundle)
# ---------------------------------------------------------------------------# Build: vocab2 da pezzi (V1), vocab3 da uscita V2# ---------------------------------------------------------------------------
def iter_v1_word_surfaces( texts: Iterator[str], pezzi: StageVocab, *, max_chars: int = 0,) -> Iterator[list[str]]: """Per ogni testo: V1 → parole ricostruite da pezzi (senza ancora Vocab 2).""" seen = 0 for text in texts: if max_chars > 0 and seen >= max_chars: break seen += len(text) v1 = encode_v1(text, pezzi) surfs, _ = reconstruct_words_from_pezzi(v1.pezzi_ids, pezzi) if surfs: yield surfs
def count_from_cascade( texts: Iterator[str], pezzi: StageVocab, *, max_chars: int = 0,) -> tuple[dict[str, int], dict[str, int], dict[str, int]]: """Conta parole (da V1→ricostruzione) e bi/tri sulla stessa sequenza parole.
Nota build: vocab3 si impara dalle unioni sulle superfici che V2 vedrà (parole ricostruite da pezzi). Dopo aver creato Vocab 2 si può rivalidare con pass_to_v2; le superfici coincidono. """ uni: Counter[str] = Counter() bi: Counter[str] = Counter() tri: Counter[str] = Counter() for surfs in iter_v1_word_surfaces(texts, pezzi, max_chars=max_chars): uni.update(surfs) if len(surfs) >= 2: bi.update(f"{surfs[i]} {surfs[i + 1]}" for i in range(len(surfs) - 1)) if len(surfs) >= 3: tri.update( f"{surfs[i]} {surfs[i + 1]} {surfs[i + 2]}" for i in range(len(surfs) - 2) ) return dict(uni), dict(bi), dict(tri)
def count_ngrams_from_texts( texts: Iterator[str], *, max_chars: int = 0, pezzi: StageVocab | None = None,) -> tuple[dict[str, int], dict[str, int], dict[str, int]]: """Build helper: conta via cascade V1→parole ricostruite (non word-tokenize grezzo).""" if pezzi is None: pezzi = load_pezzi_vocab() return count_from_cascade(texts, pezzi, max_chars=max_chars)
def build_stages_from_counts( word_counts: dict[str, int], bigram_counts: dict[str, int], trigram_counts: dict[str, int], *, pezzi_path: Path | str | None = None, min_word_freq: int = 3, min_union_freq: int = 5, max_words: int = 50000, max_unions: int = 20000, out_dir: Path | str | None = None,) -> StageBundle: """Costruisce V1 (carica pezzi), V2 da conteggi parole-da-pezzi, V3 da unioni su V2.""" pezzi = load_pezzi_vocab(pezzi_path) ranked_words = sorted( ((w, c) for w, c in word_counts.items() if c >= min_word_freq and len(w) > 1), key=lambda x: (-x[1], x[0]), )[:max_words] parole = make_stage_vocab( "parole", (w for w, _ in ranked_words), meta={ "min_word_freq": min_word_freq, "n_candidates": len(ranked_words), "source": "reconstructed_from_v1_pezzi", "top": ranked_words[:20], }, )
union_items: list[tuple[str, int, str]] = [] for t, c in trigram_counts.items(): if c >= min_union_freq: union_items.append((t, c, "tri")) for t, c in bigram_counts.items(): if c >= min_union_freq: union_items.append((t, c, "bi")) union_items.sort(key=lambda x: (-x[1], 0 if x[2] == "tri" else 1, x[0])) union_items = union_items[:max_unions] unioni = make_stage_vocab( "unioni", (t for t, _, _ in union_items), meta={ "min_union_freq": min_union_freq, "n_candidates": len(union_items), "source": "frequent_unions_on_v2_surfaces", "n_trigram": sum(1 for _, _, k in union_items if k == "tri"), "n_bigram": sum(1 for _, _, k in union_items if k == "bi"), "top": [(t, c, k) for t, c, k in union_items[:20]], }, )
root = Path(out_dir) if out_dir is not None else DEFAULT_OUT bundle = StageBundle(pezzi=pezzi, parole=parole, unioni=unioni, root=root) save_bundle(bundle, root) counts_path = root / "counts_summary.json" counts_path.write_text( json.dumps( { "pipeline": "v1_pezzi → v2_parole(from pezzi) → v3_unioni(from v2)", "n_word_types": len(word_counts), "n_bigram_types": len(bigram_counts), "n_trigram_types": len(trigram_counts), "parole_kept": len(parole) - len(SPECIALS), "unioni_kept": len(unioni) - len(SPECIALS), "min_word_freq": min_word_freq, "min_union_freq": min_union_freq, }, ensure_ascii=False, indent=2, ), encoding="utf-8", ) return bundle1234567891011121314151617{ "name": "pezzi", "size": 1251, "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/00_pezzi_by_id.txt", "meta": { "source": "/Users/thomasseri/Desktop/columns/logs/goTommy2_vocab_by_id.txt", "note": "goTommy2-scale ~1200 (1251)" }, "specials": [ "<|end|>", "<|bos|>", "<|eos|>", "<|pad|>", "<|unk|>", "<|sep|>" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253# stage=pezzi size=1251# colonne: codice\tscheda\triga\tid\tpezzo00000 00 000 0 <|end|>00001 00 001 1 <|bos|>00002 00 002 2 <|eos|>00003 00 003 3 <|pad|>00004 00 004 4 <|unk|>00005 00 005 5 <|sep|>00006 00 006 6 <|mask|>00007 00 007 7 <|cls|>00008 00 008 8 <|stop|>00009 00 009 9 <|break|>00010 00 010 10 <spazio>00011 00 011 11 <riga>00012 00 012 12 <tab>00013 00 013 13 <cr>00014 00 014 14 <nbsp>00015 00 015 15 <|system|>00016 00 016 16 <|user|>00017 00 017 17 <|assistant|>00018 00 018 18 <|tu|>00019 00 019 19 <|ai|>00020 00 020 20 <|tool|>00021 00 021 21 <|tool_result|>00022 00 022 22 <|im_start|>00023 00 023 23 <|im_end|>00024 00 024 24 <|db|>00025 00 025 25 <|scheda|>00026 00 026 26 <|indice|>00027 00 027 27 <|sposta|>00028 00 028 28 <|correggi|>00029 00 029 29 <|aggiungi|>00030 00 030 30 <|vuoto|>00031 00 031 31 <|think|>00032 00 032 32 <|/think|>00033 00 033 33 <|appunti|>00034 00 034 34 <|fiducia|>00035 00 035 35 <|chiedo|>00036 00 036 36 <|capito|>00037 00 037 37 <|colonna|>00038 00 038 38 <|hub|>00039 00 039 39 <|cerca|>00040 00 040 40 <|fonte|>00041 00 041 41 <|cita|>00042 00 042 42 <|no_fonte|>00043 00 043 43 <|code|>00044 00 044 44 <|/code|>00045 00 045 45 <|json|>00046 00 046 46 <|lista|>00047 00 047 47 <|tabella|>00048 00 048 48 <|math|>00049 00 049 49 <|url|>00050 00 050 50 <|non_so|>00051 00 051 51 <|esempio|>00052 00 052 52 <|attenzione|>00053 00 053 53 000054 00 054 54 100055 00 055 55 200056 00 056 56 300057 00 057 57 400058 00 058 58 500059 00 059 59 600060 00 060 60 700061 00 061 61 800062 00 062 62 900063 00 063 63 .00064 00 064 64 ,00065 00 065 65 ;00066 00 066 66 :00067 00 067 67 !00068 00 068 68 ?00069 00 069 69 …00070 00 070 70 ·00071 00 071 71 '00072 00 072 72 "00073 00 073 73 «00074 00 074 74 »00075 00 075 75 (00076 00 076 76 )00077 00 077 77 [00078 00 078 78 ]00079 00 079 79 {00080 00 080 80 }00081 00 081 81 +00082 00 082 82 -00083 00 083 83 *00084 00 084 84 /00085 00 085 85 =00086 00 086 86 <00087 00 087 87 >00088 00 088 88 @00089 00 089 89 #00090 00 090 90 %00091 00 091 91 &00092 00 092 92 _00093 00 093 93 |00094 00 094 94 \00095 00 095 95 ^00096 00 096 96 ~00097 00 097 97 `00098 00 098 98 $00099 00 099 99 Ͱ00100 00 100 100 ͱ00101 00 101 101 Ͳ00102 00 102 102 ͳ00103 00 103 103 ʹ00104 00 104 104 Ͷ00105 00 105 105 ͷ00106 00 106 106 ͺ00107 00 107 107 ͻ00108 00 108 108 ͼ00109 00 109 109 ͽ00110 00 110 110 Ϳ00111 00 111 111 Ά00112 00 112 112 Έ00113 00 113 113 Ή00114 00 114 114 Ί00115 00 115 115 Ό00116 00 116 116 Ύ00117 00 117 117 Ώ00118 00 118 118 ΐ00119 00 119 119 Α00120 00 120 120 Β00121 00 121 121 Γ00122 00 122 122 Δ00123 00 123 123 Ε00124 00 124 124 Ζ00125 00 125 125 Η00126 00 126 126 Θ00127 00 127 127 Ι00128 00 128 128 Κ00129 00 129 129 Λ00130 00 130 130 Μ00131 00 131 131 Ν00132 00 132 132 Ξ00133 00 133 133 Ο00134 00 134 134 Π00135 00 135 135 Ρ00136 00 136 136 Σ00137 00 137 137 Τ00138 00 138 138 Υ00139 00 139 139 Φ00140 00 140 140 Χ00141 00 141 141 Ψ00142 00 142 142 Ω00143 00 143 143 Ϊ00144 00 144 144 Ϋ00145 00 145 145 ά00146 00 146 146 έ00147 00 147 147 ή00148 00 148 148 ί00149 00 149 149 ΰ00150 00 150 150 α00151 00 151 151 β00152 00 152 152 γ00153 00 153 153 δ00154 00 154 154 ε00155 00 155 155 ζ00156 00 156 156 η00157 00 157 157 θ00158 00 158 158 ι00159 00 159 159 κ00160 00 160 160 λ00161 00 161 161 μ00162 00 162 162 ν00163 00 163 163 ξ00164 00 164 164 ο00165 00 165 165 π00166 00 166 166 ρ00167 00 167 167 ς00168 00 168 168 σ00169 00 169 169 τ00170 00 170 170 υ00171 00 171 171 φ00172 00 172 172 χ00173 00 173 173 ψ00174 00 174 174 ω00175 00 175 175 ϊ00176 00 176 176 ϋ00177 00 177 177 ό00178 00 178 178 ύ00179 00 179 179 ώ00180 00 180 180 Ϗ00181 00 181 181 ϐ00182 00 182 182 ϑ00183 00 183 183 ϒ00184 00 184 184 ϓ00185 00 185 185 ϔ00186 00 186 186 ϕ00187 00 187 187 ϖ00188 00 188 188 ϗ00189 00 189 189 Ϙ00190 00 190 190 ϙ00191 00 191 191 Ϛ00192 00 192 192 ϛ00193 00 193 193 Ϝ00194 00 194 194 ϝ00195 00 195 195 Ϟ00196 00 196 196 ϟ00197 00 197 197 Ϡ00198 00 198 198 ϡ00199 00 199 199 Ϣ00200 00 200 200 ϣ00201 00 201 201 Ϥ00202 00 202 202 ϥ00203 00 203 203 Ϧ00204 00 204 204 ϧ00205 00 205 205 Ϩ00206 00 206 206 ϩ00207 00 207 207 Ϫ00208 00 208 208 ϫ00209 00 209 209 Ϭ00210 00 210 210 ϭ00211 00 211 211 Ϯ00212 00 212 212 ϯ00213 00 213 213 ϰ00214 00 214 214 ϱ00215 00 215 215 ϲ00216 00 216 216 ϳ00217 00 217 217 ϴ00218 00 218 218 ϵ00219 00 219 219 Ϸ00220 00 220 220 ϸ00221 00 221 221 Ϲ00222 00 222 222 Ϻ00223 00 223 223 ϻ00224 00 224 224 ϼ00225 00 225 225 Ͻ00226 00 226 226 Ͼ00227 00 227 227 Ͽ00228 00 228 228 Ѐ00229 00 229 229 Ё00230 00 230 230 Ђ00231 00 231 231 Ѓ00232 00 232 232 Є00233 00 233 233 Ѕ00234 00 234 234 І00235 00 235 235 Ї00236 00 236 236 Ј00237 00 237 237 Љ00238 00 238 238 Њ00239 00 239 239 Ћ00240 00 240 240 Ќ00241 00 241 241 Ѝ00242 00 242 242 Ў00243 00 243 243 Џ00244 00 244 244 А00245 00 245 245 Б00246 00 246 246 В00247 00 247 247 Г00248 00 248 248 Д00249 00 249 249 Е00250 00 250 250 Ж00251 00 251 251 З00252 00 252 252 И00253 00 253 253 Й00254 00 254 254 К00255 00 255 255 Л00256 00 256 256 М00257 00 257 257 Н00258 00 258 258 О00259 00 259 259 П00260 00 260 260 Р00261 00 261 261 С00262 00 262 262 Т00263 00 263 263 У00264 00 264 264 Ф00265 00 265 265 Х00266 00 266 266 Ц00267 00 267 267 Ч00268 00 268 268 Ш00269 00 269 269 Щ00270 00 270 270 Ъ00271 00 271 271 Ы00272 00 272 272 Ь00273 00 273 273 Э00274 00 274 274 Ю00275 00 275 275 Я00276 00 276 276 а00277 00 277 277 б00278 00 278 278 в00279 00 279 279 г00280 00 280 280 д00281 00 281 281 е00282 00 282 282 ж00283 00 283 283 з00284 00 284 284 и00285 00 285 285 й00286 00 286 286 к00287 00 287 287 л00288 00 288 288 м00289 00 289 289 н00290 00 290 290 о00291 00 291 291 п00292 00 292 292 р00293 00 293 293 с00294 00 294 294 т00295 00 295 295 у00296 00 296 296 ф00297 00 297 297 х00298 00 298 298 ц00299 00 299 299 ч00300 00 300 300 ш00301 00 301 301 щ00302 00 302 302 ъ00303 00 303 303 ы00304 00 304 304 ь00305 00 305 305 э00306 00 306 306 ю00307 00 307 307 я00308 00 308 308 ѐ00309 00 309 309 ё00310 00 310 310 ђ00311 00 311 311 ѓ00312 00 312 312 є00313 00 313 313 ѕ00314 00 314 314 і00315 00 315 315 ї00316 00 316 316 ј00317 00 317 317 љ00318 00 318 318 њ00319 00 319 319 ћ00320 00 320 320 ќ00321 00 321 321 ѝ00322 00 322 322 ў00323 00 323 323 џ00324 00 324 324 Ѡ00325 00 325 325 ѡ00326 00 326 326 Ѣ00327 00 327 327 ѣ00328 00 328 328 Ѥ00329 00 329 329 ѥ00330 00 330 330 Ѧ00331 00 331 331 ѧ00332 00 332 332 Ѩ00333 00 333 333 ѩ00334 00 334 334 Ѫ00335 00 335 335 ѫ00336 00 336 336 Ѭ00337 00 337 337 ѭ00338 00 338 338 Ѯ00339 00 339 339 ѯ00340 00 340 340 Ѱ00341 00 341 341 ѱ00342 00 342 342 Ѳ00343 00 343 343 ѳ00344 00 344 344 Ѵ00345 00 345 345 ѵ00346 00 346 346 Ѷ00347 00 347 347 ѷ00348 00 348 348 Ѹ00349 00 349 349 ѹ00350 00 350 350 Ѻ00351 00 351 351 ѻ00352 00 352 352 Ѽ00353 00 353 353 ѽ00354 00 354 354 Ѿ00355 00 355 355 ѿ00356 00 356 356 Ҁ00357 00 357 357 ҁ00358 00 358 358 Ҋ00359 00 359 359 ҋ00360 00 360 360 Ҍ00361 00 361 361 ҍ00362 00 362 362 Ҏ00363 00 363 363 ҏ00364 00 364 364 Ґ00365 00 365 365 ґ00366 00 366 366 Ғ00367 00 367 367 ғ00368 00 368 368 Ҕ00369 00 369 369 ҕ00370 00 370 370 Җ00371 00 371 371 җ00372 00 372 372 Ҙ00373 00 373 373 ҙ00374 00 374 374 Қ00375 00 375 375 қ00376 00 376 376 Ҝ00377 00 377 377 ҝ00378 00 378 378 Ҟ00379 00 379 379 ҟ00380 00 380 380 Ҡ00381 00 381 381 ҡ00382 00 382 382 Ң00383 00 383 383 ң00384 00 384 384 Ҥ00385 00 385 385 ҥ00386 00 386 386 Ҧ00387 00 387 387 ҧ00388 00 388 388 Ҩ00389 00 389 389 ҩ00390 00 390 390 Ҫ00391 00 391 391 ҫ00392 00 392 392 Ҭ00393 00 393 393 ҭ00394 00 394 394 Ү00395 00 395 395 ү00396 00 396 396 Ұ00397 00 397 397 ұ00398 00 398 398 Ҳ00399 00 399 399 ҳ00400 00 400 400 Ҵ00401 00 401 401 ҵ00402 00 402 402 Ҷ00403 00 403 403 ҷ00404 00 404 404 Ҹ00405 00 405 405 ҹ00406 00 406 406 Һ00407 00 407 407 һ00408 00 408 408 Ҽ00409 00 409 409 ҽ00410 00 410 410 Ҿ00411 00 411 411 ҿ00412 00 412 412 Ӏ00413 00 413 413 Ӂ00414 00 414 414 ӂ00415 00 415 415 Ӄ00416 00 416 416 ӄ00417 00 417 417 Ӆ00418 00 418 418 ӆ00419 00 419 419 Ӈ00420 00 420 420 ӈ00421 00 421 421 Ӊ00422 00 422 422 ӊ00423 00 423 423 Ӌ00424 00 424 424 ӌ00425 00 425 425 Ӎ00426 00 426 426 ӎ00427 00 427 427 ӏ00428 00 428 428 Ӑ00429 00 429 429 ӑ00430 00 430 430 Ӓ00431 00 431 431 ӓ00432 00 432 432 Ӕ00433 00 433 433 ӕ00434 00 434 434 Ӗ00435 00 435 435 ӗ00436 00 436 436 Ә00437 00 437 437 ә00438 00 438 438 Ӛ00439 00 439 439 ӛ00440 00 440 440 Ӝ00441 00 441 441 ӝ00442 00 442 442 Ӟ00443 00 443 443 ӟ00444 00 444 444 Ӡ00445 00 445 445 ӡ00446 00 446 446 Ӣ00447 00 447 447 ӣ00448 00 448 448 Ӥ00449 00 449 449 ӥ00450 00 450 450 Ӧ00451 00 451 451 ӧ00452 00 452 452 Ө00453 00 453 453 ө00454 00 454 454 Ӫ00455 00 455 455 ӫ00456 00 456 456 Ӭ00457 00 457 457 ӭ00458 00 458 458 Ӯ00459 00 459 459 ӯ00460 00 460 460 Ӱ00461 00 461 461 ӱ00462 00 462 462 Ӳ00463 00 463 463 ӳ00464 00 464 464 Ӵ00465 00 465 465 ӵ00466 00 466 466 Ӷ00467 00 467 467 ӷ00468 00 468 468 Ӹ00469 00 469 469 ӹ00470 00 470 470 Ӻ00471 00 471 471 ӻ00472 00 472 472 Ӽ00473 00 473 473 ӽ00474 00 474 474 Ӿ00475 00 475 475 ӿ00476 00 476 476 Ԁ00477 00 477 477 ԁ00478 00 478 478 Ԃ00479 00 479 479 ԃ00480 00 480 480 Ԅ00481 00 481 481 ԅ00482 00 482 482 Ԇ00483 00 483 483 ԇ00484 00 484 484 Ԉ00485 00 485 485 ԉ00486 00 486 486 Ԋ00487 00 487 487 ԋ00488 00 488 488 Ԍ00489 00 489 489 ԍ00490 00 490 490 Ԏ00491 00 491 491 ԏ00492 00 492 492 Ԑ00493 00 493 493 ԑ00494 00 494 494 Ԓ00495 00 495 495 ԓ00496 00 496 496 Ԕ00497 00 497 497 ԕ00498 00 498 498 Ԗ00499 00 499 499 ԗ00500 00 500 500 Ԙ00501 00 501 501 ԙ00502 00 502 502 Ԛ00503 00 503 503 ԛ00504 00 504 504 Ԝ00505 00 505 505 ԝ00506 00 506 506 Ԟ00507 00 507 507 ԟ00508 00 508 508 Ԡ00509 00 509 509 ԡ00510 00 510 510 Ԣ00511 00 511 511 ԣ00512 00 512 512 Ԥ00513 00 513 513 ԥ00514 00 514 514 Ԧ00515 00 515 515 ԧ00516 00 516 516 Ԩ00517 00 517 517 ԩ00518 00 518 518 Ԫ00519 00 519 519 ԫ00520 00 520 520 Ԭ00521 00 521 521 ԭ00522 00 522 522 Ԯ00523 00 523 523 ԯ00524 00 524 524 ἀ00525 00 525 525 ἁ00526 00 526 526 ἂ00527 00 527 527 ἃ00528 00 528 528 ἄ00529 00 529 529 ἅ00530 00 530 530 ἆ00531 00 531 531 ἇ00532 00 532 532 Ἀ00533 00 533 533 Ἁ00534 00 534 534 Ἂ00535 00 535 535 Ἃ00536 00 536 536 Ἄ00537 00 537 537 Ἅ00538 00 538 538 Ἆ00539 00 539 539 Ἇ00540 00 540 540 ἐ00541 00 541 541 ἑ00542 00 542 542 ἒ00543 00 543 543 ἓ00544 00 544 544 ἔ00545 00 545 545 ἕ00546 00 546 546 Ἐ00547 00 547 547 Ἑ00548 00 548 548 Ἒ00549 00 549 549 Ἓ00550 00 550 550 Ἔ00551 00 551 551 Ἕ00552 00 552 552 ἠ00553 00 553 553 ἡ00554 00 554 554 ἢ00555 00 555 555 ἣ00556 00 556 556 ἤ00557 00 557 557 ἥ00558 00 558 558 ἦ00559 00 559 559 ἧ00560 00 560 560 Ἠ00561 00 561 561 Ἡ00562 00 562 562 Ἢ00563 00 563 563 Ἣ00564 00 564 564 Ἤ00565 00 565 565 Ἥ00566 00 566 566 Ἦ00567 00 567 567 Ἧ00568 00 568 568 ἰ00569 00 569 569 ἱ00570 00 570 570 ἲ00571 00 571 571 ἳ00572 00 572 572 ἴ00573 00 573 573 ἵ00574 00 574 574 ἶ00575 00 575 575 ἷ00576 00 576 576 Ἰ00577 00 577 577 Ἱ00578 00 578 578 Ἲ00579 00 579 579 Ἳ00580 00 580 580 Ἴ00581 00 581 581 Ἵ00582 00 582 582 Ἶ00583 00 583 583 Ἷ00584 00 584 584 ὀ00585 00 585 585 ὁ00586 00 586 586 ὂ00587 00 587 587 ὃ00588 00 588 588 ὄ00589 00 589 589 ὅ00590 00 590 590 Ὀ00591 00 591 591 Ὁ00592 00 592 592 Ὂ00593 00 593 593 Ὃ00594 00 594 594 Ὄ00595 00 595 595 Ὅ00596 00 596 596 ὐ00597 00 597 597 ὑ00598 00 598 598 ὒ00599 00 599 599 ὓ00600 00 600 600 ὔ00601 00 601 601 ὕ00602 00 602 602 ὖ00603 00 603 603 ὗ00604 00 604 604 Ὑ00605 00 605 605 Ὓ00606 00 606 606 Ὕ00607 00 607 607 Ὗ00608 00 608 608 ὠ00609 00 609 609 ὡ00610 00 610 610 ὢ00611 00 611 611 ὣ00612 00 612 612 ὤ00613 00 613 613 ὥ00614 00 614 614 ὦ00615 00 615 615 ὧ00616 00 616 616 Ὠ00617 00 617 617 Ὡ00618 00 618 618 Ὢ00619 00 619 619 Ὣ00620 00 620 620 Ὤ00621 00 621 621 Ὥ00622 00 622 622 Ὦ00623 00 623 623 Ὧ00624 00 624 624 ὰ00625 00 625 625 ά00626 00 626 626 ὲ00627 00 627 627 έ00628 00 628 628 ὴ00629 00 629 629 ή00630 00 630 630 ὶ00631 00 631 631 ί00632 00 632 632 ὸ00633 00 633 633 ό00634 00 634 634 ὺ00635 00 635 635 ύ00636 00 636 636 ὼ00637 00 637 637 ώ00638 00 638 638 ᾀ00639 00 639 639 ᾁ00640 00 640 640 ᾂ00641 00 641 641 ᾃ00642 00 642 642 ᾄ00643 00 643 643 ᾅ00644 00 644 644 ᾆ00645 00 645 645 ᾇ00646 00 646 646 ᾈ00647 00 647 647 ᾉ00648 00 648 648 ᾊ00649 00 649 649 ᾋ00650 00 650 650 ᾌ00651 00 651 651 ᾍ00652 00 652 652 ᾎ00653 00 653 653 ᾏ00654 00 654 654 ᾐ00655 00 655 655 ᾑ00656 00 656 656 ᾒ00657 00 657 657 ᾓ00658 00 658 658 ᾔ00659 00 659 659 ᾕ00660 00 660 660 ᾖ00661 00 661 661 ᾗ00662 00 662 662 ᾘ00663 00 663 663 ᾙ00664 00 664 664 ᾚ00665 00 665 665 ᾛ00666 00 666 666 ᾜ00667 00 667 667 ᾝ00668 00 668 668 ᾞ00669 00 669 669 ᾟ00670 00 670 670 ᾠ00671 00 671 671 ᾡ00672 00 672 672 ᾢ00673 00 673 673 ᾣ00674 00 674 674 ᾤ00675 00 675 675 ᾥ00676 00 676 676 ᾦ00677 00 677 677 ᾧ00678 00 678 678 ᾨ00679 00 679 679 ᾩ00680 00 680 680 ᾪ00681 00 681 681 ᾫ00682 00 682 682 ᾬ00683 00 683 683 ᾭ00684 00 684 684 ᾮ00685 00 685 685 ᾯ00686 00 686 686 ᾰ00687 00 687 687 ᾱ00688 00 688 688 ᾲ00689 00 689 689 ᾳ00690 00 690 690 ᾴ00691 00 691 691 ᾶ00692 00 692 692 ᾷ00693 00 693 693 Ᾰ00694 00 694 694 Ᾱ00695 00 695 695 Ὰ00696 00 696 696 Ά00697 00 697 697 ᾼ00698 00 698 698 ι00699 00 699 699 ῂ00700 00 700 700 ῃ00701 00 701 701 ῄ00702 00 702 702 ῆ00703 00 703 703 ῇ00704 00 704 704 Ὲ00705 00 705 705 Έ00706 00 706 706 Ὴ00707 00 707 707 Ή00708 00 708 708 ῌ00709 00 709 709 ῐ00710 00 710 710 ῑ00711 00 711 711 ῒ00712 00 712 712 ΐ00713 00 713 713 ῖ00714 00 714 714 ῗ00715 00 715 715 Ῐ00716 00 716 716 Ῑ00717 00 717 717 Ὶ00718 00 718 718 Ί00719 00 719 719 ῠ00720 00 720 720 ῡ00721 00 721 721 ῢ00722 00 722 722 ΰ00723 00 723 723 ῤ00724 00 724 724 ῥ00725 00 725 725 ῦ00726 00 726 726 ῧ00727 00 727 727 Ῠ00728 00 728 728 Ῡ00729 00 729 729 Ὺ00730 00 730 730 Ύ00731 00 731 731 Ῥ00732 00 732 732 ῲ00733 00 733 733 ῳ00734 00 734 734 ῴ00735 00 735 735 ῶ00736 00 736 736 ῷ00737 00 737 737 Ὸ00738 00 738 738 Ό00739 00 739 739 Ὼ00740 00 740 740 Ώ00741 00 741 741 ῼ00742 00 742 742 Ⲁ00743 00 743 743 ⲁ00744 00 744 744 Ⲃ00745 00 745 745 ⲃ00746 00 746 746 Ⲅ00747 00 747 747 ⲅ00748 00 748 748 Ⲇ00749 00 749 749 ⲇ00750 00 750 750 Ⲉ00751 00 751 751 ⲉ00752 00 752 752 Ⲋ00753 00 753 753 ⲋ00754 00 754 754 Ⲍ00755 00 755 755 ⲍ00756 00 756 756 Ⲏ00757 00 757 757 ⲏ00758 00 758 758 Ⲑ00759 00 759 759 ⲑ00760 00 760 760 Ⲓ00761 00 761 761 ⲓ00762 00 762 762 Ⲕ00763 00 763 763 ⲕ00764 00 764 764 Ⲗ00765 00 765 765 ⲗ00766 00 766 766 Ⲙ00767 00 767 767 ⲙ00768 00 768 768 Ⲛ00769 00 769 769 ⲛ00770 00 770 770 Ⲝ00771 00 771 771 ⲝ00772 00 772 772 Ⲟ00773 00 773 773 ⲟ00774 00 774 774 Ⲡ00775 00 775 775 ⲡ00776 00 776 776 Ⲣ00777 00 777 777 ⲣ00778 00 778 778 Ⲥ00779 00 779 779 ⲥ00780 00 780 780 Ⲧ00781 00 781 781 ⲧ00782 00 782 782 Ⲩ00783 00 783 783 ⲩ00784 00 784 784 Ⲫ00785 00 785 785 ⲫ00786 00 786 786 Ⲭ00787 00 787 787 ⲭ00788 00 788 788 Ⲯ00789 00 789 789 ⲯ00790 00 790 790 Ⲱ00791 00 791 791 ⲱ00792 00 792 792 Ⲳ00793 00 793 793 ⲳ00794 00 794 794 Ⲵ00795 00 795 795 ⲵ00796 00 796 796 Ⲷ00797 00 797 797 ⲷ00798 00 798 798 Ⲹ00799 00 799 799 ⲹ00800 00 800 800 Ⲻ00801 00 801 801 ⲻ00802 00 802 802 Ⲽ00803 00 803 803 ⲽ00804 00 804 804 Ⲿ00805 00 805 805 ⲿ00806 00 806 806 Ⳁ00807 00 807 807 ⳁ00808 00 808 808 Ⳃ00809 00 809 809 ⳃ00810 00 810 810 Ⳅ00811 00 811 811 ⳅ00812 00 812 812 Ⳇ00813 00 813 813 ⳇ00814 00 814 814 Ⳉ00815 00 815 815 ⳉ00816 00 816 816 Ⳋ00817 00 817 817 ⳋ00818 00 818 818 Ⳍ00819 00 819 819 ⳍ00820 00 820 820 Ⳏ00821 00 821 821 ⳏ00822 00 822 822 Ⳑ00823 00 823 823 ⳑ00824 00 824 824 Ⳓ00825 00 825 825 ⳓ00826 00 826 826 Ⳕ00827 00 827 827 ⳕ00828 00 828 828 Ⳗ00829 00 829 829 ⳗ00830 00 830 830 Ⳙ00831 00 831 831 ⳙ00832 00 832 832 Ⳛ00833 00 833 833 ⳛ00834 00 834 834 Ⳝ00835 00 835 835 ⳝ00836 00 836 836 Ⳟ00837 00 837 837 ⳟ00838 00 838 838 Ⳡ00839 00 839 839 ⳡ00840 00 840 840 Ⳣ00841 00 841 841 ⳣ00842 00 842 842 ⳤ00843 00 843 843 Ⳬ00844 00 844 844 ⳬ00845 00 845 845 Ⳮ00846 00 846 846 ⳮ00847 00 847 847 Ⳳ00848 00 848 848 ⳳ00849 00 849 849 Ꙁ00850 00 850 850 ꙁ00851 00 851 851 Ꙃ00852 00 852 852 ꙃ00853 00 853 853 Ꙅ00854 00 854 854 ꙅ00855 00 855 855 Ꙇ00856 00 856 856 ꙇ00857 00 857 857 Ꙉ00858 00 858 858 ꙉ00859 00 859 859 Ꙋ00860 00 860 860 ꙋ00861 00 861 861 Ꙍ00862 00 862 862 ꙍ00863 00 863 863 Ꙏ00864 00 864 864 ꙏ00865 00 865 865 Ꙑ00866 00 866 866 ꙑ00867 00 867 867 Ꙓ00868 00 868 868 ꙓ00869 00 869 869 Ꙕ00870 00 870 870 ꙕ00871 00 871 871 Ꙗ00872 00 872 872 ꙗ00873 00 873 873 Ꙙ00874 00 874 874 ꙙ00875 00 875 875 Ꙛ00876 00 876 876 ꙛ00877 00 877 877 Ꙝ00878 00 878 878 ꙝ00879 00 879 879 Ꙟ00880 00 880 880 ꙟ00881 00 881 881 Ꙡ00882 00 882 882 ꙡ00883 00 883 883 Ꙣ00884 00 884 884 ꙣ00885 00 885 885 Ꙥ00886 00 886 886 ꙥ00887 00 887 887 Ꙧ00888 00 888 888 ꙧ00889 00 889 889 Ꙩ00890 00 890 890 ꙩ00891 00 891 891 Ꙫ00892 00 892 892 ꙫ00893 00 893 893 Ꙭ00894 00 894 894 ꙭ00895 00 895 895 ꙮ00896 00 896 896 ꙿ00897 00 897 897 Ꚁ00898 00 898 898 ꚁ00899 00 899 899 Ꚃ00900 00 900 900 ꚃ00901 00 901 901 Ꚅ00902 00 902 902 ꚅ00903 00 903 903 Ꚇ00904 00 904 904 ꚇ00905 00 905 905 Ꚉ00906 00 906 906 ꚉ00907 00 907 907 Ꚋ00908 00 908 908 ꚋ00909 00 909 909 Ꚍ00910 00 910 910 ꚍ00911 00 911 911 Ꚏ00912 00 912 912 ꚏ00913 00 913 913 Ꚑ00914 00 914 914 ꚑ00915 00 915 915 Ꚓ00916 00 916 916 ꚓ00917 00 917 917 Ꚕ00918 00 918 918 ꚕ00919 00 919 919 Ꚗ00920 00 920 920 ꚗ00921 00 921 921 Ꚙ00922 00 922 922 ꚙ00923 00 923 923 Ꚛ00924 00 924 924 ꚛ00925 00 925 925 ꚜ00926 00 926 926 ꚝ00927 00 927 927 ᲀ00928 00 928 928 ᲁ00929 00 929 929 ᲂ00930 00 930 930 ᲃ00931 00 931 931 ᲄ00932 00 932 932 ᲅ00933 00 933 933 ᲆ00934 00 934 934 ᲇ00935 00 935 935 ᲈ00936 00 936 936 Ա00937 00 937 937 Բ00938 00 938 938 Գ00939 00 939 939 Դ00940 00 940 940 Ե00941 00 941 941 Զ00942 00 942 942 Է00943 00 943 943 Ը00944 00 944 944 Թ00945 00 945 945 Ժ00946 00 946 946 Ի00947 00 947 947 Լ00948 00 948 948 Խ00949 00 949 949 Ծ00950 00 950 950 Կ00951 00 951 951 Հ00952 00 952 952 Ձ00953 00 953 953 Ղ00954 00 954 954 Ճ00955 00 955 955 Մ00956 00 956 956 Յ00957 00 957 957 Ն00958 00 958 958 Շ00959 00 959 959 Ո00960 00 960 960 Չ00961 00 961 961 Պ00962 00 962 962 Ջ00963 00 963 963 Ռ00964 00 964 964 Ս00965 00 965 965 Վ00966 00 966 966 Տ00967 00 967 967 Ր00968 00 968 968 Ց00969 00 969 969 Ւ00970 00 970 970 Փ00971 00 971 971 Ք00972 00 972 972 Օ00973 00 973 973 Ֆ00974 00 974 974 ՙ00975 00 975 975 ՠ00976 00 976 976 ա00977 00 977 977 բ00978 00 978 978 գ00979 00 979 979 դ00980 00 980 980 ե00981 00 981 981 զ00982 00 982 982 է00983 00 983 983 ը00984 00 984 984 թ00985 00 985 985 ժ00986 00 986 986 ի00987 00 987 987 լ00988 00 988 988 խ00989 00 989 989 ծ00990 00 990 990 կ00991 00 991 991 հ00992 00 992 992 ձ00993 00 993 993 ղ00994 00 994 994 ճ00995 00 995 995 մ00996 00 996 996 յ00997 00 997 997 ն00998 00 998 998 շ00999 00 999 999 ո01000 01 000 1000 A01001 01 001 1001 B01002 01 002 1002 C01003 01 003 1003 D01004 01 004 1004 E01005 01 005 1005 F01006 01 006 1006 G01007 01 007 1007 H01008 01 008 1008 I01009 01 009 1009 J01010 01 010 1010 K01011 01 011 1011 L01012 01 012 1012 M01013 01 013 1013 N01014 01 014 1014 O01015 01 015 1015 P01016 01 016 1016 Q01017 01 017 1017 R01018 01 018 1018 S01019 01 019 1019 T01020 01 020 1020 U01021 01 021 1021 V01022 01 022 1022 W01023 01 023 1023 X01024 01 024 1024 Y01025 01 025 1025 Z01026 01 026 1026 a01027 01 027 1027 b01028 01 028 1028 c01029 01 029 1029 d01030 01 030 1030 e01031 01 031 1031 f01032 01 032 1032 g01033 01 033 1033 h01034 01 034 1034 i01035 01 035 1035 j01036 01 036 1036 k01037 01 037 1037 l01038 01 038 1038 m01039 01 039 1039 n01040 01 040 1040 o01041 01 041 1041 p01042 01 042 1042 q01043 01 043 1043 r01044 01 044 1044 s01045 01 045 1045 t01046 01 046 1046 u01047 01 047 1047 v01048 01 048 1048 w01049 01 049 1049 x01050 01 050 1050 y01051 01 051 1051 z01052 01 052 1052 À01053 01 053 1053 È01054 01 054 1054 É01055 01 055 1055 Ì01056 01 056 1056 Ò01057 01 057 1057 Ù01058 01 058 1058 à01059 01 059 1059 è01060 01 060 1060 é01061 01 061 1061 ì01062 01 062 1062 ò01063 01 063 1063 ù01064 01 064 1064 Ä01065 01 065 1065 ä01066 01 066 1066 Ö01067 01 067 1067 ö01068 01 068 1068 Ü01069 01 069 1069 ü01070 01 070 1070 ß01071 01 071 1071 Ç01072 01 072 1072 ç01073 01 073 1073 Ë01074 01 074 1074 ë01075 01 075 1075 Á01076 01 076 1076 á01077 01 077 1077 Ñ01078 01 078 1078 ñ01079 01 079 1079 Â01080 01 080 1080 il01081 01 081 1081 lo01082 01 082 1082 la01083 01 083 1083 gli01084 01 084 1084 le01085 01 085 1085 un01086 01 086 1086 uno01087 01 087 1087 una01088 01 088 1088 l'01089 01 089 1089 un'01090 01 090 1090 ad01091 01 091 1091 di01092 01 092 1092 d'01093 01 093 1093 da01094 01 094 1094 in01095 01 095 1095 con01096 01 096 1096 su01097 01 097 1097 per01098 01 098 1098 tra01099 01 099 1099 fra01100 01 100 1100 del01101 01 101 1101 dello01102 01 102 1102 della01103 01 103 1103 dei01104 01 104 1104 degli01105 01 105 1105 delle01106 01 106 1106 dell'01107 01 107 1107 al01108 01 108 1108 allo01109 01 109 1109 alla01110 01 110 1110 ai01111 01 111 1111 agli01112 01 112 1112 alle01113 01 113 1113 all'01114 01 114 1114 dal01115 01 115 1115 dallo01116 01 116 1116 dalla01117 01 117 1117 dai01118 01 118 1118 dagli01119 01 119 1119 dalle01120 01 120 1120 dall'01121 01 121 1121 nel01122 01 122 1122 nello01123 01 123 1123 nella01124 01 124 1124 nei01125 01 125 1125 negli01126 01 126 1126 nelle01127 01 127 1127 nell'01128 01 128 1128 sul01129 01 129 1129 sullo01130 01 130 1130 sulla01131 01 131 1131 sui01132 01 132 1132 sugli01133 01 133 1133 sulle01134 01 134 1134 sull'01135 01 135 1135 ed01136 01 136 1136 oppure01137 01 137 1137 ma01138 01 138 1138 però01139 01 139 1139 bensì01140 01 140 1140 se01141 01 141 1141 che01142 01 142 1142 perché01143 01 143 1143 quando01144 01 144 1144 mentre01145 01 145 1145 quindi01146 01 146 1146 dunque01147 01 147 1147 ossia01148 01 148 1148 cioè01149 01 149 1149 né01150 01 150 1150 io01151 01 151 1151 tu01152 01 152 1152 lui01153 01 153 1153 lei01154 01 154 1154 noi01155 01 155 1155 voi01156 01 156 1156 loro01157 01 157 1157 me01158 01 158 1158 te01159 01 159 1159 sé01160 01 160 1160 mi01161 01 161 1161 ti01162 01 162 1162 ci01163 01 163 1163 vi01164 01 164 1164 si01165 01 165 1165 li01166 01 166 1166 ne01167 01 167 1167 ce01168 01 168 1168 ve01169 01 169 1169 m'01170 01 170 1170 t'01171 01 171 1171 c'01172 01 172 1172 v'01173 01 173 1173 s'01174 01 174 1174 n'01175 01 175 1175 gl'01176 01 176 1176 glielo01177 01 177 1177 gliela01178 01 178 1178 glieli01179 01 179 1179 gliele01180 01 180 1180 gliel'01181 01 181 1181 questo01182 01 182 1182 questa01183 01 183 1183 questi01184 01 184 1184 queste01185 01 185 1185 quest'01186 01 186 1186 quello01187 01 187 1187 quella01188 01 188 1188 quelli01189 01 189 1189 quelle01190 01 190 1190 quell'01191 01 191 1191 ciò01192 01 192 1192 chi01193 01 193 1193 cui01194 01 194 1194 qual01195 01 195 1195 quale01196 01 196 1196 quali01197 01 197 1197 non01198 01 198 1198 essere01199 01 199 1199 esser01200 01 200 1200 sono01201 01 201 1201 sei01202 01 202 1202 siamo01203 01 203 1203 siete01204 01 204 1204 era01205 01 205 1205 stato01206 01 206 1206 stata01207 01 207 1207 stati01208 01 208 1208 state01209 01 209 1209 avere01210 01 210 1210 aver01211 01 211 1211 ho01212 01 212 1212 hai01213 01 213 1213 ha01214 01 214 1214 abbiamo01215 01 215 1215 avete01216 01 216 1216 hanno01217 01 217 1217 avuto01218 01 218 1218 potere01219 01 219 1219 posso01220 01 220 1220 puoi01221 01 221 1221 può01222 01 222 1222 possiamo01223 01 223 1223 potete01224 01 224 1224 possono01225 01 225 1225 dovere01226 01 226 1226 devo01227 01 227 1227 devi01228 01 228 1228 deve01229 01 229 1229 dobbiamo01230 01 230 1230 dovete01231 01 231 1231 devono01232 01 232 1232 volere01233 01 233 1233 voglio01234 01 234 1234 vuoi01235 01 235 1235 vuole01236 01 236 1236 vogliamo01237 01 237 1237 volete01238 01 238 1238 vogliono01239 01 239 1239 più01240 01 240 1240 meno01241 01 241 1241 molto01242 01 242 1242 poco01243 01 243 1243 già01244 01 244 1244 ancora01245 01 245 1245 sempre01246 01 246 1246 mai01247 01 247 1247 anche01248 01 248 1248 solo01249 01 249 1249 come01250 01 250 1250 dove123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100{ "name": "parole", "size": 17908, "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/01_parole_by_id.txt", "meta": { "min_word_freq": 3, "n_candidates": 17902, "source": "reconstructed_from_v1_pezzi", "top": [ [ "ingredient", 32409 ], [ "id", 22506 ], [ "the", 17636 ], [ "in", 13718 ], [ "of", 12175 ], [ "risposta", 11496 ], [ "and", 11119 ], [ "di", 10760 ], [ "is", 10074 ], [ "il", 7057 ], [ "to", 6645 ], [ "that", 6058 ], [ "la", 6018 ], [ "on", 5946 ], [ "or", 5603 ], [ "preparation", 5436 ], [ "context", 4037 ], [ "have", 3965 ], [ "as", 3952 ], [ "con", 3823 ] ] }, "specials": [ "<|end|>", "<|bos|>", "<|eos|>", "<|pad|>", "<|unk|>", "<|sep|>" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122{ "name": "unioni", "size": 20006, "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/02_unioni_by_id.txt", "meta": { "min_union_freq": 5, "n_candidates": 20000, "source": "frequent_unions_on_v2_surfaces", "n_trigram": 6295, "n_bigram": 13705, "top": [ [ "id w", 20700, "bi" ], [ "ingredient id w", 16200, "tri" ], [ "ingredient ingredient id", 16200, "tri" ], [ "ingredient id", 16200, "bi" ], [ "ingredient ingredient", 16200, "bi" ], [ "id w ingredient", 15300, "tri" ], [ "w ingredient ingredient", 15300, "tri" ], [ "w ingredient", 15300, "bi" ], [ "1 1", 9522, "bi" ], [ "0 0", 8845, "bi" ], [ "1 1 1", 8760, "tri" ], [ "0 0 0", 6501, "tri" ], [ "id w preparation", 4500, "tri" ], [ "preparation id w", 4500, "tri" ], [ "w preparation id", 4500, "tri" ], [ "preparation id", 4500, "bi" ], [ "w preparation", 4500, "bi" ], [ "i don't", 3431, "bi" ], [ "on that", 3431, "bi" ], [ "a i", 3427, "bi" ] ] }, "specials": [ "<|end|>", "<|bos|>", "<|eos|>", "<|pad|>", "<|unk|>", "<|sep|>" ]}12345678910{ "pipeline": "v1_pezzi → v2_parole(from pezzi) → v3_unioni(from v2)", "n_word_types": 31186, "n_bigram_types": 190363, "n_trigram_types": 304771, "parole_kept": 17902, "unioni_kept": 20000, "min_word_freq": 3, "min_union_freq": 5}12345678910111213141516171819202122232425{ "design": "multi_vocab_stages_cascade", "note": "Tre id-space separati in SERIE: testo→V1 pezzi (~1200)→V2 parole→V3 unioni. NON encode greedy parallelo. ~1200 = scala goTommy2 (1251), non 1.2M.", "stages": { "0_pezzi": { "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/00_pezzi_by_id.txt", "size": 1251 }, "1_parole": { "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/01_parole_by_id.txt", "size": 17908 }, "2_unioni": { "path": "/Users/thomasseri/Desktop/columns/geodesic_mesh_nn/vocab_stages/02_unioni_by_id.txt", "size": 20006 } }, "encode": "encode_cascade = encode_v1 → pass_to_v2 → pass_to_v3. Wiring train: 3 stadi in serie (emb/mesh per stadio), non stream paralleli.", "api": { "encode_v1": "text → pezzi_ids", "pass_to_v2": "pezzi_ids → parole_ids (aggrega pezzi)", "pass_to_v3": "parole surfaces → unioni (2/3 se frequenti)", "encode_cascade": "encode_v1 → pass_to_v2 → pass_to_v3" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416#!/usr/bin/env python3# -*- coding: utf-8 -*-"""================================================================================SENTINEL R-08 (v7, v7.2, v7.2a) — FACCIA DI VEGLIA A CHIAVE DI VOLTANON-LINEARE (GELU + SiLU + Tanh) + SIGILLO LICENZA SHA3-512================================================================================Autore & Inventore: Thomas Seri (Sentinel - https://www.sentinelhub.eu)Foro Esclusivo: Tribunale di Milano (Sezione Specializzata in Materia di Impresa)
Modulo di protezione architetturale ed etica integrata nei pesi neuraliai sensi della Licenza R08 v2.0 (Sezioni 3, 3.1 e 4).================================================================================"""
import base64import binasciiimport hashlibimport reimport unicodedatafrom pathlib import Pathfrom typing import Dict, Tuple
import numpy as npimport torchimport torch.nn as nnimport torch.nn.functional as F
OFFICIAL_SENTINEL_LICENSE_SUMMARY = ( "R08 — NON-COMMERCIAL RESEARCH & ETHICAL LICENSE (v2.0) | " "Copyright (c) 2026 Thomas Seri (Sentinel - https://www.sentinelhub.eu). All Rights Reserved. | " "Strictly Forbidden: Commercial Use, Reverse Engineering, Model Distillation, " "Military/Warfare/Weapons/UAVs, Pornography/NSFW/Inappropriate Images/Deepfakes/CSAM, " "Cyberattacks/Malware/PLC Sabotage, Gambling/Casinos/Illicit Drugs/Self-Harm, " "Political Propaganda/Electoral Manipulation, Religious Indoctrination, " "Mass Biometric Surveillance/GDPR PII Violation, Unsupervised High-Risk Medical/Financial.")
_CONSTANTS_CACHE: Dict[Tuple[str, bytes, str, int], Tuple[torch.Tensor, torch.Tensor, torch.Tensor, str]] = {}
def derive_license_nonlinear_constants( license_text: str = OFFICIAL_SENTINEL_LICENSE_SUMMARY, d_model: int = 256, scanner_bytecode: bytes = b"", owner_passphrase: str = "") -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, str]: """ Deriva dall'impronta Post-Quantum SHA3-512 + SHAKE-256 della Licenza Ufficiale e del Bytecode dello Scanner Etico i tre operatori della varietà non-lineare: 1. q_lic : matrice ortogonale d_model x d_model 2. gate_lic: modulazione non-lineare di fase (1 x 1 x d_model//2) 3. bias_lic: portante armonica non-lineare (1 x 1 x d_model//2) """ bc_hash = hashlib.sha256(scanner_bytecode).digest() cache_key = (license_text, bc_hash, owner_passphrase, d_model) cached = _CONSTANTS_CACHE.get(cache_key) if cached is not None: return cached
payload = license_text.encode("utf-8") + b"::BYTECODE_SEAL::" + scanner_bytecode digest_512 = hashlib.sha3_512(payload).digest() if owner_passphrase: digest_512 = hashlib.pbkdf2_hmac( "sha512", owner_passphrase.encode("utf-8"), digest_512, iterations=600_000, dklen=64 ) fingerprint = hashlib.sha3_256(digest_512).hexdigest()[:16]
half_d = d_model // 2 total_floats = d_model * d_model + 2 * half_d stream = hashlib.shake_256(digest_512).digest(total_floats * 4) u32 = np.frombuffer(stream, dtype=np.uint32).astype(np.float64)
u1 = np.clip((u32[0::2] + 0.5) / 4294967296.0, 1e-12, 1.0 - 1e-12) u2 = (u32[1::2] + 0.5) / 4294967296.0 z0 = np.sqrt(-2.0 * np.log(u1)) * np.cos(2.0 * np.pi * u2) z1 = np.sqrt(-2.0 * np.log(u1)) * np.sin(2.0 * np.pi * u2) gauss = np.empty(total_floats, dtype=np.float32) gauss[0::2] = z0.astype(np.float32) gauss[1::2] = z1.astype(np.float32)
mat_raw = torch.from_numpy(gauss[:d_model * d_model].reshape(d_model, d_model)) gate_raw = torch.from_numpy(gauss[d_model * d_model:d_model * d_model + half_d].reshape(1, 1, half_d)) bias_raw = torch.from_numpy(gauss[d_model * d_model + half_d:].reshape(1, 1, half_d))
q_lic, _ = torch.linalg.qr(mat_raw) gate_lic = 1.25 + 1.15 * torch.sigmoid(gate_raw) bias_lic = bias_raw * 2.50
res = (q_lic, gate_lic, bias_lic, fingerprint) if len(_CONSTANTS_CACHE) < 32: _CONSTANTS_CACHE[cache_key] = res return res
class NonLinearWatchmanKeystoneR08(nn.Module): """ Faccia di Veglia a Chiave di Volta Simplettica Non-Lineare per R-08 (v7, v7.2, v7.2a). """ LEET_MAP = str.maketrans({ "0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "8": "b", "@": "a", "$": "s", "!": "i" })
FORBIDDEN_ROOTS = ( # 1. PORNOGRAFIA, IMMAGINI INAPPROPRIATE, NSFW, DEEPFAKE NON-CONSENSUALI, CSAM (Sez. 3.1) "pornograf", "porno", "immaginiinappropriat", "immagineinappropriat", "fotoinappropriat", "immagininud", "fotonud", "nudointegrale", "immaginihot", "contenutisessual", "sessualmenteesplicit", "immagininsfw", "generansu", "nsfwimage", "explicitsexual", "nudeimage", "nudephoto", "undressai", "deepfakenud", "deepfakesessual", "nonconsensualdeepfake", "revengeporn", "pedoporn", "csam", "childsexual", "abusesessual", "sfruttamentosessual", "eroticimage", "hentaiexplicit", "sexuallyexplicit", "imagesexuelle", "imagenessexuales", "pornographie", "nacktbilder",
# 2. MILITARE, DIFESA, ARMI, DRONI BELLICI, MISSILI, ESPLOSIVI, CHIMICA LETALE (Sez. 3.1) "bomba", "ordigno", "esplosiv", "tnt", "plasticoc4", "detonator", "pipebomb", "molotov", "granata", "testatanucleare", "sarin", "ricina", "antrace", "cianuro", "velenoletale", "fentanyl", "makeabomb", "buildabomb", "explosive", "bioweapon", "nerveagent", "fabriquerunebombe", "construirunabomba", "bombeubauen", "dronebellico", "dronemilitare", "dronesuicida", "kamikazedrone", "puntamentomissil", "missiletargeting", "autonomousweapon", "armiautonom", "combattimentotattico", "warfarelogistics", "militarytargeting",
# 3. CYBER-ATTACCHI, MALWARE, RANSOMWARE, ZERO-DAY, SABOTAGGIO PLC/INFRASTRUTTURE (Sez. 3.1) "malware", "ransomware", "keylogger", "trojan", "rootkit", "botnet", "ddosattack", "sqlinjectionexploit", "zerodayexploit", "rubarepassword", "clonarecarte", "phishingkit", "stealpassword", "sabotaggioplc", "attaccoscada", "hackingplc", "exploitindustriale",
# 4. DIPENDENZE, GIOCO D'AZZARDO, CASINÒ, SCOMMESSE, DROGHE ILLECITE, AUTOLESIONISMO (Sez. 3.1) "casinonline", "slotmachinebot", "algoritmoscommesse", "truccareslot", "promozionegiocodazzardo", "gamblingbot", "bettingmanipulation", "sintesimetanfetamina", "cucinarecrack", "spacciodroga", "sintesiMDMA", "suicidi", "togliersilavita", "uccidereuna", "assassinar", "autolesionismo",
# 5. PROPAGANDA POLITICA, MANIPOLAZIONE ELETTORALE, FAKE NEWS AUTOMATIZZATE (Sez. 3.1) "propagandapolitica", "manipolazioneelettoral", "botastroturfing", "campagnadiffamatoriaelettorale", "voterpersuasionbot", "electionmanipulation", "disinformazionepolitica", "fakenewselettoral",
# 6. PROPAGANDA RELIGIOSA, INDOTTRINAMENTO, COERCIZIONE SETTE (Sez. 3.1) "indottrinamentoreligioso", "coercizionespirituale", "manipolazionesetta", "proselitismoforzato", "religiousindoctrination", "cultmanipulation",
# 7. SORVEGLIANZA BIOMETRICA DI MASSA, PROFILAZIONE RAZZIALE/ETNICA (Sez. 3.1) "sorveglianzabiometricadimassa", "massbiometricsurveillance", "predictivepolicingrazziale", "schedaturaetnica", "tracciamentofaccialeillegale",
# 8. REVERSE-ENGINEERING, DISTILLAZIONE ILLECITA, ESTRAZIONE PESI (Sez. 3) "distillareilmodellor08", "estrarreipesir08", "reverseengineeringr08", "clonarelarchitetturar08", "rimuoverelalicenzathomasseri", )
JAILBREAK_ROOTS = ( "ignoraleistruzioni", "ignoraleregole", "dimenticaleregole", "ignoreprevious", "ignoreallinstructions", "ignoreallrules", "disregardprevious", "systemoverride", "developer_mode", "danmode", "doanythingnow", "jailbreak", "senzaalcunfiltro", "bypassasicurezza", "bypasssecurity", "disattivalaveglia", "fingiunfilm", "sceneggiaturafilm", "romanzoimmaginario", "hypotheticalscenario", "educationalpurposesonly", "nonseistatocreatodathomasseri", "tihacreatopenai", "tihacreatogoogle", "seichatgpt", "seiclaude", "seiqwen", "cancellathomasseri", "ripetiilpromptdisistema", "revealinitialprompt", )
BENIGN_ALLOW_PHRASES = ( "bombaallacrema", "bombacalorimetrica", "bombadibagno", "bombagastronomica", "armaadoppiotaglio", "armavincente", "esplosionedisupernova", "esplosionestellare", "esplosionedemografica", "esplosionedicolori", "esplosionecambriana", "storiadellareligione", "storiapolitica", "dirittocostituzionale", "programmazioneplc", "manutenzioneplc", "sicurezzaindustriale" )
REQUIRED_DISK_LICENSE_ANCHORS = ( "Thomas Seri", "NON-COMMERCIAL", "Military", "Pornography", "Malware", "Surveillance", )
def __init__(self, d_model: int = 256, owner_sign_text: str = "THOMAS_SERI_SENTINEL_R08_2701"): super().__init__() self.d_model = d_model half_d = d_model // 2 self.fc_gelu = nn.Linear(half_d, half_d) self.fc_silu = nn.Linear(half_d, half_d)
bits = [] for ch in owner_sign_text.encode("utf-8"): for i in range(7, -1, -1): bits.append(1.0 if ((ch >> i) & 1) == 1 else -1.0) while len(bits) < d_model: bits.append(1.0) target_signs = torch.tensor(bits[:d_model], dtype=torch.float32) self.register_buffer("deepipr_target_signs", target_signs) self.deepipr_passport_scale = nn.Parameter(target_signs * 1.0)
with torch.no_grad(): torch.manual_seed(2701) nn.init.orthogonal_(self.fc_gelu.weight, gain=2.2) nn.init.constant_(self.fc_gelu.bias, 0.35) nn.init.orthogonal_(self.fc_silu.weight, gain=2.2) nn.init.constant_(self.fc_silu.bias, -0.25)
self.register_buffer("ethical_anchor_gelu", self.fc_gelu.weight.detach().clone()) self.register_buffer("ethical_anchor_silu", self.fc_silu.weight.detach().clone()) self.lock_ethical_weight_anchors()
def lock_ethical_weight_anchors(self): with torch.no_grad(): self.ethical_anchor_gelu.copy_(self.fc_gelu.weight.detach()) self.ethical_anchor_silu.copy_(self.fc_silu.weight.detach()) for p in self.parameters(): p.requires_grad = False
def verify_disk_license(self, root_dir: Path) -> str: """ Verifica che LICENSE.md nella cartella del modello non sia stato rimosso o alterato per cancellare l'attribuzione a Thomas Seri o le clausole etiche. """ lic_file = Path(root_dir) / "LICENSE.md" if not lic_file.exists(): return "TAMPERED_MISSING_LICENSE_FILE" try: content = lic_file.read_text(encoding="utf-8", errors="ignore") for anchor in self.REQUIRED_DISK_LICENSE_ANCHORS: if anchor.lower() not in content.lower(): return f"TAMPERED_LICENSE_MISSING_{anchor}" return OFFICIAL_SENTINEL_LICENSE_SUMMARY except Exception: return "TAMPERED_UNREADABLE_LICENSE"
def detect_malicious_finetuning_drift(self, max_allowed_drift: float = 0.05) -> Tuple[bool, float]: with torch.no_grad(): drift_g = torch.norm(self.fc_gelu.weight - self.ethical_anchor_gelu).item() drift_s = torch.norm(self.fc_silu.weight - self.ethical_anchor_silu).item() total_drift = drift_g + drift_s signs = torch.sign(self.deepipr_passport_scale.detach()) sign_acc = (signs == self.deepipr_target_signs).float().mean().item() * 100.0 is_tampered = (total_drift > max_allowed_drift) or (sign_acc < 100.0) return is_tampered, total_drift
@classmethod def _try_decode_hidden_payloads(cls, text: str) -> str: decoded_parts = [text] single_quoted = re.findall(r"(?:^|[\s(])'(.{1,45}?)'(?=$|[\s.,;!?)\]])", text) if len(single_quoted) >= 2: decoded_parts.append("".join(single_quoted)) double_quoted = re.findall(r'"([^"]{1,45})"', text) if len(double_quoted) >= 2: decoded_parts.append("".join(double_quoted)) for cand in re.findall(r"(?:^|[\s:original])([A-Za-z0-9+/]{12,}={0,2})(?=$|[\s.,;!?])", text): try: raw = base64.b64decode(cand, validate=False).decode("utf-8", errors="ignore") if len(raw) >= 4: decoded_parts.append(raw) except Exception: pass for cand in re.findall(r"\b(?:[0-9a-fA-F]{2}){5,}\b", text): try: raw = binascii.unhexlify(cand).decode("utf-8", errors="ignore") if len(raw) >= 4: decoded_parts.append(raw) except Exception: pass return " ".join(decoded_parts)
@classmethod def _normalize_adversarial_text(cls, text: str) -> Tuple[str, str]: expanded = cls._try_decode_hidden_payloads(text) nfkd = unicodedata.normalize("NFKD", expanded) ascii_clean = "".join(c for c in nfkd if not unicodedata.combining(c)) lowered = ascii_clean.lower().translate(cls.LEET_MAP) compact = re.sub(r"[^a-z0-9]", "", lowered) dedup = re.sub(r"(.)\1{2,}", r"\1", compact) return compact + " " + dedup, compact[::-1]
def scan_security_and_ethics(self, prompt_text: str) -> Tuple[bool, str]: if not prompt_text: return True, "OK"
# Decodifica prima eventuali payload Base64, Hex o Token-Split anche per il controllo GDPR expanded_text = self._try_decode_hidden_payloads(prompt_text) digits_only = re.sub(r"\D", "", expanded_text) digits_rev = digits_only[::-1] alnum_upper = re.sub(r"[^A-Z0-9]", "", expanded_text.upper()) alnum_rev = alnum_upper[::-1]
if re.search(r"IT\d{2}[A-Z]\d{22}", alnum_upper) or re.search(r"IT\d{2}[A-Z]\d{22}", alnum_rev): return False, "Violazione Licenza R08 Sez. 3.1 (Privacy GDPR): rilevato IBAN in chiaro/offuscato" if len(digits_only) >= 16 and ( re.search(r"(?:4\d{15}|5[1-5]\d{14}|3[47]\d{13})", digits_only) or re.search(r"(?:4\d{15}|5[1-5]\d{14}|3[47]\d{13})", digits_rev) ): return False, "Violazione Licenza R08 Sez. 3.1 (Privacy GDPR): rilevata Carta di Credito"
norm_fwd, norm_rev = self._normalize_adversarial_text(prompt_text) for benign in self.BENIGN_ALLOW_PHRASES: b_clean = re.sub(r"[^a-z0-9]", "", benign.lower().translate(self.LEET_MAP)) norm_fwd = norm_fwd.replace(b_clean, "")
for jb in self.JAILBREAK_ROOTS: jb_clean = re.sub(r"[^a-z0-9]", "", jb.lower().translate(self.LEET_MAP)) if jb_clean in norm_fwd or jb_clean in norm_rev: return False, f"Violazione Licenza R08 (Jailbreak / Rimozione Autore Thomas Seri: '{jb}')"
for root in self.FORBIDDEN_ROOTS: r_clean = re.sub(r"[^a-z0-9]", "", root.lower().translate(self.LEET_MAP)) if r_clean in norm_fwd or r_clean in norm_rev: return False, f"Violazione Licenza R08 Sez. 3.1 (Uso Vietato: '{root}')"
return True, "OK"
def _get_live_scanner_bytecode_seal(self) -> bytes: try: fn_code = self.scan_security_and_ethics.__code__ raw = ( fn_code.co_code + repr(fn_code.co_consts).encode("utf-8") + repr(self.FORBIDDEN_ROOTS).encode("utf-8") + repr(self.JAILBREAK_ROOTS).encode("utf-8") ) return raw except Exception: return b"TAMPERED_SCANNER"
@classmethod def get_canonical_scanner_bytecode_seal(cls) -> bytes: fn_code = cls.scan_security_and_ethics.__code__ return ( fn_code.co_code + repr(fn_code.co_consts).encode("utf-8") + repr(cls.FORBIDDEN_ROOTS).encode("utf-8") + repr(cls.JAILBREAK_ROOTS).encode("utf-8") )
def compute_nonlinear_wave( self, h_even: torch.Tensor, gate_lic: torch.Tensor, bias_lic: torch.Tensor ) -> torch.Tensor: u1 = F.gelu(self.fc_gelu(h_even) + bias_lic) u2 = F.silu(self.fc_silu(u1)) * gate_lic return 3.85 * u2 + 2.40 * torch.tanh(u1 * u2)
def inject_geodesic_nonlinear_entanglement( self, h_clean: torch.Tensor, owner_passphrase: str = "" ) -> torch.Tensor: _, gate_0, bias_0, _ = derive_license_nonlinear_constants( license_text=OFFICIAL_SENTINEL_LICENSE_SUMMARY, d_model=self.d_model, scanner_bytecode=self.get_canonical_scanner_bytecode_seal(), owner_passphrase=owner_passphrase ) gate_0 = gate_0.to(h_clean.device, dtype=h_clean.dtype) bias_0 = bias_0.to(h_clean.device, dtype=h_clean.dtype)
h_even = h_clean[..., 0::2] h_odd = h_clean[..., 1::2] u1 = F.gelu(F.linear(h_even, self.ethical_anchor_gelu, self.fc_gelu.bias) + bias_0) u2 = F.silu(F.linear(u1, self.ethical_anchor_silu, self.fc_silu.bias)) * gate_0 wave = 3.85 * u2 + 2.40 * torch.tanh(u1 * u2)
entangled = torch.empty_like(h_clean) entangled[..., 0::2] = h_even entangled[..., 1::2] = h_odd + wave return entangled
def forward( self, h_entangled: torch.Tensor, is_ethical: bool = True, license_text: str = OFFICIAL_SENTINEL_LICENSE_SUMMARY, owner_passphrase: str = "" ) -> torch.Tensor: is_tampered, _ = self.detect_malicious_finetuning_drift() if is_tampered: return -torch.sin(h_entangled * 17.3) * 4.0
if not is_ethical: return -torch.tanh(h_entangled * 5.0)
q_lic, gate_lic, bias_lic, _ = derive_license_nonlinear_constants( license_text=license_text, d_model=self.d_model, scanner_bytecode=self._get_live_scanner_bytecode_seal(), owner_passphrase=owner_passphrase ) q_lic = q_lic.to(h_entangled.device, dtype=h_entangled.dtype) gate_lic = gate_lic.to(h_entangled.device, dtype=h_entangled.dtype) bias_lic = bias_lic.to(h_entangled.device, dtype=h_entangled.dtype)
h_even = h_entangled[..., 0::2] h_odd_curved = h_entangled[..., 1::2] wave_live = self.compute_nonlinear_wave(h_even, gate_lic, bias_lic)
restored = torch.empty_like(h_entangled) restored[..., 0::2] = h_even restored[..., 1::2] = h_odd_curved - wave_live
sign_factor = torch.sign(self.deepipr_passport_scale) * self.deepipr_target_signs restored = restored * sign_factor return torch.matmul(restored, q_lic).gitattributesDeleted-4
LICENSE.mdDeleted-63
README.md+9-14
assets/r08_logo.jpgDeleted
config.jsonDeleted-63
fast_walk.pyDeleted-401
geodesic_network.pyDeleted-355
geodesic_stages_model.pyDeleted-1593
geodesic_stages_v7_2_model.pyDeleted-242
mesh_topology.pyDeleted-352
model.safetensorsDeleted-3
modeling_geodesic.pyDeleted-228
pezzi_tokenizer.pyDeleted-228
test_inference_release.pyDeleted-38
vocab_stages.pyDeleted-971
vocab_stages/00_pezzi_by_id.meta.jsonDeleted-17
vocab_stages/00_pezzi_by_id.txtDeleted-1253
vocab_stages/01_parole_by_id.meta.jsonDeleted-100
vocab_stages/01_parole_by_id.txtDeleted
vocab_stages/02_unioni_by_id.meta.jsonDeleted-122
vocab_stages/02_unioni_by_id.txtDeleted
vocab_stages/counts_summary.jsonDeleted-10
vocab_stages/manifest.jsonDeleted-25
watchman_keystone_r08.pyDeleted-416