Thomas commited on
Commit ·
3b0ef19
0
Parent(s):
feat: initial release of gpTommy 32k Italian Vocabulary & Tokenizer by Thomas Seri
Browse filesFiles changed (6)
- .gitignoreAdded+3
- LICENSE.mdAdded+26
- README.mdAdded+98
- gpTommy_vocab_by_id.txtAdded
- gptommy_tokenizer.pyAdded+166
- vocab.jsonAdded
123__pycache__/*.pyc.DS_Store1234567891011121314151617181920212223242526# gpTommy 32k — RESEARCH LICENSE & ATTRIBUTION
Copyright (c) 2026 Thomas Seri (Sentinel). All Rights Reserved.
---
### 1. DEFINITIONS- **"Author"** means Thomas Seri.- **"Software"** means the gpTommy 32k vocabulary, tokenizer implementation, mappings, and related documentation.- **"Official Ecosystem"** means Sentinel LifeOS (https://www.sentinelhub.eu) and Sentinel R-08 models.
---
### 2. GRANT OF PERMISSIONSubject to the terms and restrictions of this License, the Author grants you a personal, worldwide, royalty-free, non-exclusive license to:1. Use the vocabulary and tokenizer for research, educational, and open experimentation purposes.2. Integrate the tokenizer in open-source NLP pipelines, provided that **prominent attribution** is given to **Thomas Seri** and **Sentinel AI / Sentinel LifeOS**.
---
### 3. STRICT ETHICAL RESTRICTIONSIt is strictly, unconditionally, and globally FORBIDDEN to use gpTommy 32k for:1. Military, weapons development, defense warfare, or autonomous weapon systems.2. Religious propaganda, doctrinal coercion, or political disinformation.3. Pornography, sexually explicit content, or exploitation.4. Cyberattacks, malware generation, phishing, or predatory surveillance.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798# 🇮🇹 gpTommy 32k — Vocabolario & Tokenizer Nativo per la Lingua Italiana
[](https://www.sentinelhub.eu)[](https://www.sentinelhub.eu)[](https://github.com/Thomasseri/gpTommy-32k)[](https://github.com/Thomasseri/gpTommy-32k)[-orange.svg)](https://www.sentinelhub.eu)
> **Vocabolario e Tokenizer lessicale a 32.768 token concepito e strutturato specificamente per la lingua italiana.** > **Autore & Ideatore:** Thomas Seri (Sentinel) > **Ecosistema di Riferimento:** [Sentinel LifeOS](https://www.sentinelhub.eu) & Famiglia di Modelli **Sentinel R-08**
---
## 🌐 Ecosistema Sentinel & Modelli R-08 Correlati
Il vocabolario **gpTommy 32k** è il motore lessicale ad alta densità impiegato per la nuova generazione di modelli geodetici compatti e leggeri della famiglia **Sentinel R-08**:
* 🌍 **Sito Ufficiale:** **[www.sentinelhub.eu](https://www.sentinelhub.eu)** — Piattaforma Sentinel LifeOS* 🤖 **Sentinel R-08 v7 (Pyramid 44.5M):** [GitHub](https://github.com/Thomasseri/R-08) | [Hugging Face](https://huggingface.co/Tom2701/R-08)* 🚀 **Sentinel R-08 v7.2 (51.6M con 12 Hub Icosaedrici):** [GitHub](https://github.com/Thomasseri/R-08-v7.2) | [Hugging Face](https://huggingface.co/Tom2701/R-08-v7.2)* 🌟 **Sentinel R-08 v7.2a DA ZERO (51.6M Record 82.51% BLiMP):** [GitHub](https://github.com/Thomasseri/R-08-v7.2a) | [Hugging Face](https://huggingface.co/Tom2701/R-08-v7.2a)* 🔬 **Modello di Controllo A/B Transformer Baseline (44.9M):** [GitHub](https://github.com/Thomasseri/R-08-Transformer-Baseline) | [Hugging Face](https://huggingface.co/Tom2701/R-08-Transformer-Baseline)
---
## 🎯 Perché gpTommy 32k è Diverso dai Tokenizer Tradizionali
La quasi totalità dei Large Language Model commerciali (come GPT-4, LLaMA o Mistral) utilizza tokenizer BPE statistici calibrati sulla lingua inglese. Nel testo italiano questo comporta una grave frammentazione:* Una parola come *«cuscinetto»* o *«manutenzione»* viene spezzata in 3 o 4 sottosillabe arbitrarie (`cus-`, `ci-`, `net-`, `to`), aumentando a dismisura la lunghezza del contesto, i costi computazionali e il rischio di allucinazioni ortografiche.
**gpTommy 32k** adotta un approccio lessicale nativo e strutturato:* Contiene **29.775 parole italiane complete** (il **90,9%** dell'intero vocabolario), coprendo forme base, singolari, plurali, verbi coniugati e l'intero lessico tecnico-scientifico.* Le parole non vengono spezzettate: la rete neurale associa un **singolo token atomico** a ciascun concetto lessicale finito.
---
## 📚 Architettura ad Archivio: Il Sistema a Schede `SSvvv`
Il vocabolario gpTommy adotta una codifica deterministica a 5 cifre `SSvvv`:* **`SS` (Scheda)**: Indica la categoria o la lettera dell'alfabeto (da `01` a `26` per le lettere **A..Z**).* **`vvv` (Riga)**: Indica la specifica riga / lemma all'interno di quella scheda.
| Scheda | Intervallo ID | Contenuto Principale | Esempi di Token || :---: | :---: | :--- | :--- || **`00`** | `00000` – `00999` | Token speciali AI, punteggiatura, cifre, simboli matematici | `<\|user\|>`, `<\|assistant\|>`, `<\|system\|>`, `+`, `-`, `=`, `*`, `%` || **`01`** | `01000` – `01999` | Lettera **A** (parole italiane e forme latine) | `anche`, `amico`, `allora`, `avere`, `analizzare`, `attualità` || **`03`** | `03000` – `03999` | Lettera **C** | `casa`, `cosa`, `città`, `cuscinetto`, `costruire`, `cilindro` || **`07`** | `07000` – `07999` | Lettera **G** | `giorno`, `grande`, `gruppo`, `giovane`, `governo` || **`20`** | `20000` – `20999` | Lettera **T** | `tempo`, `terra`, `tavolo`, `totale`, `tiranti`, `trasmissione` || **`26`** | `26000` – `26999` | Lettera **Z** (oltre 940 lemmi in Z) | `zona`, `zone`, `zero`, `zio`, `zucchero`, `zaino`, `zitto`, `zucca` |
---
## 📊 Ripartizione dei 32.768 Token
```┌─────────────────────────────────────────────────────────────┐│ gpTommy 32k (32.768 ID) │├──────────────────────────────────────┬──────────┬───────────┤│ Tipologia │ Conteggio│ Percentual│├──────────────────────────────────────┼──────────┼───────────┤│ Parole Italiane Complete │ 29.775 │ 90,9% ││ Caratteri Singoli, Cifre e Simboli │ 1.925 │ 5,9% ││ Token Speciali di Controllo & Chat │ 1.069 │ 3,2% │└──────────────────────────────────────┴──────────┴───────────┘```
---
## 🚀 Utilizzo Rapido in Python (Zero Dipendenze Esterne)
Il tokenizer `gptommy_tokenizer.py` è completamente autonomo e non richiede pacchetti pesanti esterni:
```pythonfrom gptommy_tokenizer import gpTommyTokenizer
# 1. Inizializza il tokenizer con il vocabolario gpTommytokenizer = gpTommyTokenizer()
# 2. Codifica una frase italiana in token IDtesto = "Il cuscinetto a sfere radiale riduce l'attrito volvente."token_ids = tokenizer.encode(testo)print("Token IDs:", token_ids)# Esempio: [9043, 10, 3001, 21472, 14147, 10, 1001, 10, 19529, ...]
# 3. Decodifica tornando al testo italiano originaletesto_ricostruito = tokenizer.decode(token_ids)print("Decodifica:", testo_ricostruito)# Output: "Il cuscinetto a sfere radiale riduce l'attrito volvente."```
---
## 🛡️ Licenza e AttribuzioneQuesto vocabolario è rilasciato per scopi di **Ricerca Scientifica e Sperimentazione Libera (Non-Commercial Research License)** con vincoli etici di protezione (esclusione di impieghi bellici, propaganda e usi lesivi).
Tutti i diritti sull'architettura a schede e sull'organizzazione lessicale sono riservati a **Thomas Seri (Sentinel)**. Per collaborazioni o utilizzi in progetti di produzione: **[www.sentinelhub.eu](https://www.sentinelhub.eu)**.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166#!/usr/bin/env python3"""gpTommy 32k Tokenizer: Tokenizer nativo ad alta efficienza per la lingua italiana.Autore & Ideatore: Thomas Seri (Sentinel)Ecosistema: Sentinel LifeOS (https://www.sentinelhub.eu)Modelli di riferimento: Sentinel R-08 v7, v7.2, v7.2a, v7.2b
Vocabolario strutturato a schede (SSvvv):- 32.768 token totali (ID 0..32767)- 29.775 parole italiane complete (Schede 01..26 per le lettere A..Z)- 1.925 caratteri singoli, punteggiatura, cifre e simboli matematici- 1.069 token speciali di dialogo AI (<|user|>, <|assistant|>, <|system|>, <|think|>)"""from __future__ import annotations
import unicodedatafrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence, Union
DEFAULT_VOCAB_PATH = Path(__file__).resolve().parent / "gpTommy_vocab_by_id.txt"
WS_PIECES = {"\n": "<riga>", "\t": "<tab>", "\r": "<cr>", "\xa0": "<nbsp>", " ": "<spazio>"}DECODE_WS = {"<spazio>": " ", "<riga>": "\n", "<tab>": "\t", "<cr>": "\r", "<nbsp>": " "}
class gpTommyTokenizer: """Tokenizer compatto e nativo per il vocabolario gpTommy 32k."""
def __init__(self, vocab_file: Optional[Union[str, Path]] = None): self.vocab_file = Path(vocab_file) if vocab_file else DEFAULT_VOCAB_PATH if not self.vocab_file.exists(): raise FileNotFoundError(f"File vocabolario gpTommy non trovato: {self.vocab_file}")
self.id_to_token: Dict[int, str] = {} self.token_to_id: Dict[str, int] = {} self.specials: List[str] = [] self._load_vocab()
# Token speciali standard self.pad_id = self.token_to_id.get("<|pad|>", 3) self.eos_id = self.token_to_id.get("<|eos|>", 2) self.bos_id = self.token_to_id.get("<|bos|>", 1) self.unk_id = self.token_to_id.get("<|unk|>", 4) self.sep_id = self.token_to_id.get("<|sep|>", 5)
# Marcatori di chat / dialoghi self.user_id = self.token_to_id.get("<|user|>", 16) self.assistant_id = self.token_to_id.get("<|assistant|>", 17) self.system_id = self.token_to_id.get("<|system|>", 15)
self.max_len = max((len(t) for t in self.id_to_token.values() if not t.startswith("<")), default=1)
def _load_vocab(self) -> None: """Carica il file tabellare gpTommy 32k.""" with open(self.vocab_file, "r", encoding="utf-8") as f: for line in f: if line.startswith("#") or not line.strip(): continue parts = line.strip().split("\t") if len(parts) >= 5: gid = int(parts[3]) tok = parts[4] self.id_to_token[gid] = tok self.token_to_id[tok] = gid if tok.startswith("<") and tok.endswith(">"): self.specials.append(tok) self.specials.sort(key=len, reverse=True)
@property def vocab_size(self) -> int: return len(self.id_to_token)
def encode(self, text: str, add_special_tokens: bool = False, literal_specials: bool = True) -> List[int]: """Codifica secondo il contratto canonico gpTommy.""" if not text: return []
ids: List[int] = [] if add_special_tokens and self.bos_id is not None: ids.append(self.bos_id)
n = len(text) i = 0 t2i = self.token_to_id
while i < n: ch = text[i] # Gestione Whitespace if ch.isspace() or ch in WS_PIECES: tid = t2i.get(WS_PIECES.get(ch, "<spazio>")) if tid is not None: ids.append(tid) i += 1 continue
# Gestione speciali letterali <|...|> if literal_specials and ch == "<": hit = next((sp for sp in self.specials if text.startswith(sp, i)), None) if hit is not None: ids.append(t2i[hit]) i += len(hit) continue
# Longest match greedy upper = min(n, i + self.max_len) tid = None j = upper while j > i: frag = text[i:j] tid = t2i.get(frag) if tid is None and 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
# Fallback singolo carattere tid = t2i.get(ch) if tid is None and ch.isalpha(): tid = t2i.get(ch.lower()) ids.append(self.unk_id if tid is None else tid) i += 1
if add_special_tokens and self.eos_id is not None: ids.append(self.eos_id)
return ids
def decode(self, token_ids: Sequence[int], skip_special_tokens: bool = False) -> str: """Decodifica gli ID di token in testo ricostruito (sostituisce i whitespace).""" out: List[str] = [] for tid in token_ids: tok = self.id_to_token.get(int(tid), "<|unk|>") if skip_special_tokens and tok.startswith("<|") and tok.endswith("|>"): continue out.append(DECODE_WS.get(tok, tok)) return "".join(out)
def batch_encode(self, texts: Sequence[str]) -> List[List[int]]: return [self.encode(t) for t in texts]
def batch_decode(self, batch_ids: Sequence[Sequence[int]], skip_special_tokens: bool = False) -> List[str]: return [self.decode(ids, skip_special_tokens=skip_special_tokens) for ids in batch_ids]
if __name__ == "__main__": tok = gpTommyTokenizer() print(f"=== gpTommy 32k Tokenizer (Vocabolario: {tok.vocab_size} token) ===") test_frasi = [ "ciao, come stai?", "qual è la capitale d'italia?", "il cuscinetto a sfera radiale riduce l'attrito volvente.", "<|user|> spiegami il teorema di pitagora <|assistant|> certo!", ] for frase in test_frasi: ids = tok.encode(frase) ricostruita = tok.decode(ids) print(f"\nFrase: '{frase}'") print(f"Tokens ({len(ids)} ID): {ids[:10]}...") print(f"Decodifica: '{ricostruita}'") assert frase == ricostruita, f"Mismatch: {frase} != {ricostruita}" print("\n✅ Tutti i test di conformità gpTommy 32k sono passati con successo!").gitignoreAdded+3
LICENSE.mdAdded+26
README.mdAdded+98
gpTommy_vocab_by_id.txtAdded
gptommy_tokenizer.pyAdded+166
vocab.jsonAdded