Thomas commited on
Commit
3b0ef19
·
0 Parent(s):

feat: initial release of gpTommy 32k Italian Vocabulary & Tokenizer by Thomas Seri

Browse files
Files changed (6) hide show
  1. .gitignore +3 -0
  2. LICENSE.md +26 -0
  3. README.md +98 -0
  4. gpTommy_vocab_by_id.txt +0 -0
  5. gptommy_tokenizer.py +166 -0
  6. vocab.json +0 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .DS_Store
LICENSE.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gpTommy 32k — RESEARCH LICENSE & ATTRIBUTION
2
+
3
+ Copyright (c) 2026 Thomas Seri (Sentinel). All Rights Reserved.
4
+
5
+ ---
6
+
7
+ ### 1. DEFINITIONS
8
+ - **"Author"** means Thomas Seri.
9
+ - **"Software"** means the gpTommy 32k vocabulary, tokenizer implementation, mappings, and related documentation.
10
+ - **"Official Ecosystem"** means Sentinel LifeOS (https://www.sentinelhub.eu) and Sentinel R-08 models.
11
+
12
+ ---
13
+
14
+ ### 2. GRANT OF PERMISSION
15
+ Subject to the terms and restrictions of this License, the Author grants you a personal, worldwide, royalty-free, non-exclusive license to:
16
+ 1. Use the vocabulary and tokenizer for research, educational, and open experimentation purposes.
17
+ 2. Integrate the tokenizer in open-source NLP pipelines, provided that **prominent attribution** is given to **Thomas Seri** and **Sentinel AI / Sentinel LifeOS**.
18
+
19
+ ---
20
+
21
+ ### 3. STRICT ETHICAL RESTRICTIONS
22
+ It is strictly, unconditionally, and globally FORBIDDEN to use gpTommy 32k for:
23
+ 1. Military, weapons development, defense warfare, or autonomous weapon systems.
24
+ 2. Religious propaganda, doctrinal coercion, or political disinformation.
25
+ 3. Pornography, sexually explicit content, or exploitation.
26
+ 4. Cyberattacks, malware generation, phishing, or predatory surveillance.
README.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🇮🇹 gpTommy 32k — Vocabolario & Tokenizer Nativo per la Lingua Italiana
2
+
3
+ [![Official Site](https://img.shields.io/badge/Sito%20Ufficiale-sentinelhub.eu-007acc.svg)](https://www.sentinelhub.eu)
4
+ [![Ecosystem](https://img.shields.io/badge/Ecosistema-Sentinel%20LifeOS-purple.svg)](https://www.sentinelhub.eu)
5
+ [![Vocabolario](https://img.shields.io/badge/Vocabolario-32.768%20Tokens-blue.svg)](https://github.com/Thomasseri/gpTommy-32k)
6
+ [![Lingua](https://img.shields.io/badge/Lingua-Italiano%20Puro%2091%25-green.svg)](https://github.com/Thomasseri/gpTommy-32k)
7
+ [![Autore](https://img.shields.io/badge/Autore-Thomas%20Seri%20(Sentinel)-orange.svg)](https://www.sentinelhub.eu)
8
+
9
+ > **Vocabolario e Tokenizer lessicale a 32.768 token concepito e strutturato specificamente per la lingua italiana.**
10
+ > **Autore & Ideatore:** Thomas Seri (Sentinel)
11
+ > **Ecosistema di Riferimento:** [Sentinel LifeOS](https://www.sentinelhub.eu) & Famiglia di Modelli **Sentinel R-08**
12
+
13
+ ---
14
+
15
+ ## 🌐 Ecosistema Sentinel & Modelli R-08 Correlati
16
+
17
+ 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**:
18
+
19
+ * 🌍 **Sito Ufficiale:** **[www.sentinelhub.eu](https://www.sentinelhub.eu)** — Piattaforma Sentinel LifeOS
20
+ * 🤖 **Sentinel R-08 v7 (Pyramid 44.5M):** [GitHub](https://github.com/Thomasseri/R-08) | [Hugging Face](https://huggingface.co/Tom2701/R-08)
21
+ * 🚀 **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)
22
+ * 🌟 **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)
23
+ * 🔬 **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)
24
+
25
+ ---
26
+
27
+ ## 🎯 Perché gpTommy 32k è Diverso dai Tokenizer Tradizionali
28
+
29
+ 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:
30
+ * 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.
31
+
32
+ **gpTommy 32k** adotta un approccio lessicale nativo e strutturato:
33
+ * 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.
34
+ * Le parole non vengono spezzettate: la rete neurale associa un **singolo token atomico** a ciascun concetto lessicale finito.
35
+
36
+ ---
37
+
38
+ ## 📚 Architettura ad Archivio: Il Sistema a Schede `SSvvv`
39
+
40
+ Il vocabolario gpTommy adotta una codifica deterministica a 5 cifre `SSvvv`:
41
+ * **`SS` (Scheda)**: Indica la categoria o la lettera dell'alfabeto (da `01` a `26` per le lettere **A..Z**).
42
+ * **`vvv` (Riga)**: Indica la specifica riga / lemma all'interno di quella scheda.
43
+
44
+ | Scheda | Intervallo ID | Contenuto Principale | Esempi di Token |
45
+ | :---: | :---: | :--- | :--- |
46
+ | **`00`** | `00000` – `00999` | Token speciali AI, punteggiatura, cifre, simboli matematici | `<\|user\|>`, `<\|assistant\|>`, `<\|system\|>`, `+`, `-`, `=`, `*`, `%` |
47
+ | **`01`** | `01000` – `01999` | Lettera **A** (parole italiane e forme latine) | `anche`, `amico`, `allora`, `avere`, `analizzare`, `attualità` |
48
+ | **`03`** | `03000` – `03999` | Lettera **C** | `casa`, `cosa`, `città`, `cuscinetto`, `costruire`, `cilindro` |
49
+ | **`07`** | `07000` – `07999` | Lettera **G** | `giorno`, `grande`, `gruppo`, `giovane`, `governo` |
50
+ | **`20`** | `20000` – `20999` | Lettera **T** | `tempo`, `terra`, `tavolo`, `totale`, `tiranti`, `trasmissione` |
51
+ | **`26`** | `26000` – `26999` | Lettera **Z** (oltre 940 lemmi in Z) | `zona`, `zone`, `zero`, `zio`, `zucchero`, `zaino`, `zitto`, `zucca` |
52
+
53
+ ---
54
+
55
+ ## 📊 Ripartizione dei 32.768 Token
56
+
57
+ ```
58
+ ┌─────────────────────────────────────────────────────────────┐
59
+ │ gpTommy 32k (32.768 ID) │
60
+ ├──────────────────────────────────────┬──────────┬───────────┤
61
+ │ Tipologia │ Conteggio│ Percentual│
62
+ ├──────────────────────────────────────┼──────────┼───────────┤
63
+ │ Parole Italiane Complete │ 29.775 │ 90,9% │
64
+ │ Caratteri Singoli, Cifre e Simboli │ 1.925 │ 5,9% │
65
+ │ Token Speciali di Controllo & Chat │ 1.069 │ 3,2% │
66
+ └──────────────────────────────────────┴──────────┴───────────┘
67
+ ```
68
+
69
+ ---
70
+
71
+ ## 🚀 Utilizzo Rapido in Python (Zero Dipendenze Esterne)
72
+
73
+ Il tokenizer `gptommy_tokenizer.py` è completamente autonomo e non richiede pacchetti pesanti esterni:
74
+
75
+ ```python
76
+ from gptommy_tokenizer import gpTommyTokenizer
77
+
78
+ # 1. Inizializza il tokenizer con il vocabolario gpTommy
79
+ tokenizer = gpTommyTokenizer()
80
+
81
+ # 2. Codifica una frase italiana in token ID
82
+ testo = "Il cuscinetto a sfere radiale riduce l'attrito volvente."
83
+ token_ids = tokenizer.encode(testo)
84
+ print("Token IDs:", token_ids)
85
+ # Esempio: [9043, 10, 3001, 21472, 14147, 10, 1001, 10, 19529, ...]
86
+
87
+ # 3. Decodifica tornando al testo italiano originale
88
+ testo_ricostruito = tokenizer.decode(token_ids)
89
+ print("Decodifica:", testo_ricostruito)
90
+ # Output: "Il cuscinetto a sfere radiale riduce l'attrito volvente."
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 🛡️ Licenza e Attribuzione
96
+ Questo 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).
97
+
98
+ 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)**.
gpTommy_vocab_by_id.txt ADDED
The diff for this file is too large to render. See raw diff
 
gptommy_tokenizer.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """gpTommy 32k Tokenizer: Tokenizer nativo ad alta efficienza per la lingua italiana.
3
+ Autore & Ideatore: Thomas Seri (Sentinel)
4
+ Ecosistema: Sentinel LifeOS (https://www.sentinelhub.eu)
5
+ Modelli di riferimento: Sentinel R-08 v7, v7.2, v7.2a, v7.2b
6
+
7
+ Vocabolario strutturato a schede (SSvvv):
8
+ - 32.768 token totali (ID 0..32767)
9
+ - 29.775 parole italiane complete (Schede 01..26 per le lettere A..Z)
10
+ - 1.925 caratteri singoli, punteggiatura, cifre e simboli matematici
11
+ - 1.069 token speciali di dialogo AI (<|user|>, <|assistant|>, <|system|>, <|think|>)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import unicodedata
16
+ from pathlib import Path
17
+ from typing import Dict, List, Optional, Sequence, Union
18
+
19
+ DEFAULT_VOCAB_PATH = Path(__file__).resolve().parent / "gpTommy_vocab_by_id.txt"
20
+
21
+ WS_PIECES = {"\n": "<riga>", "\t": "<tab>", "\r": "<cr>", "\xa0": "<nbsp>", " ": "<spazio>"}
22
+ DECODE_WS = {"<spazio>": " ", "<riga>": "\n", "<tab>": "\t", "<cr>": "\r", "<nbsp>": " "}
23
+
24
+
25
+ class gpTommyTokenizer:
26
+ """Tokenizer compatto e nativo per il vocabolario gpTommy 32k."""
27
+
28
+ def __init__(self, vocab_file: Optional[Union[str, Path]] = None):
29
+ self.vocab_file = Path(vocab_file) if vocab_file else DEFAULT_VOCAB_PATH
30
+ if not self.vocab_file.exists():
31
+ raise FileNotFoundError(f"File vocabolario gpTommy non trovato: {self.vocab_file}")
32
+
33
+ self.id_to_token: Dict[int, str] = {}
34
+ self.token_to_id: Dict[str, int] = {}
35
+ self.specials: List[str] = []
36
+ self._load_vocab()
37
+
38
+ # Token speciali standard
39
+ self.pad_id = self.token_to_id.get("<|pad|>", 3)
40
+ self.eos_id = self.token_to_id.get("<|eos|>", 2)
41
+ self.bos_id = self.token_to_id.get("<|bos|>", 1)
42
+ self.unk_id = self.token_to_id.get("<|unk|>", 4)
43
+ self.sep_id = self.token_to_id.get("<|sep|>", 5)
44
+
45
+ # Marcatori di chat / dialoghi
46
+ self.user_id = self.token_to_id.get("<|user|>", 16)
47
+ self.assistant_id = self.token_to_id.get("<|assistant|>", 17)
48
+ self.system_id = self.token_to_id.get("<|system|>", 15)
49
+
50
+ self.max_len = max((len(t) for t in self.id_to_token.values() if not t.startswith("<")), default=1)
51
+
52
+ def _load_vocab(self) -> None:
53
+ """Carica il file tabellare gpTommy 32k."""
54
+ with open(self.vocab_file, "r", encoding="utf-8") as f:
55
+ for line in f:
56
+ if line.startswith("#") or not line.strip():
57
+ continue
58
+ parts = line.strip().split("\t")
59
+ if len(parts) >= 5:
60
+ gid = int(parts[3])
61
+ tok = parts[4]
62
+ self.id_to_token[gid] = tok
63
+ self.token_to_id[tok] = gid
64
+ if tok.startswith("<") and tok.endswith(">"):
65
+ self.specials.append(tok)
66
+ self.specials.sort(key=len, reverse=True)
67
+
68
+ @property
69
+ def vocab_size(self) -> int:
70
+ return len(self.id_to_token)
71
+
72
+ def encode(self, text: str, add_special_tokens: bool = False, literal_specials: bool = True) -> List[int]:
73
+ """Codifica secondo il contratto canonico gpTommy."""
74
+ if not text:
75
+ return []
76
+
77
+ ids: List[int] = []
78
+ if add_special_tokens and self.bos_id is not None:
79
+ ids.append(self.bos_id)
80
+
81
+ n = len(text)
82
+ i = 0
83
+ t2i = self.token_to_id
84
+
85
+ while i < n:
86
+ ch = text[i]
87
+ # Gestione Whitespace
88
+ if ch.isspace() or ch in WS_PIECES:
89
+ tid = t2i.get(WS_PIECES.get(ch, "<spazio>"))
90
+ if tid is not None:
91
+ ids.append(tid)
92
+ i += 1
93
+ continue
94
+
95
+ # Gestione speciali letterali <|...|>
96
+ if literal_specials and ch == "<":
97
+ hit = next((sp for sp in self.specials if text.startswith(sp, i)), None)
98
+ if hit is not None:
99
+ ids.append(t2i[hit])
100
+ i += len(hit)
101
+ continue
102
+
103
+ # Longest match greedy
104
+ upper = min(n, i + self.max_len)
105
+ tid = None
106
+ j = upper
107
+ while j > i:
108
+ frag = text[i:j]
109
+ tid = t2i.get(frag)
110
+ if tid is None and frag.isalpha():
111
+ tid = t2i.get(frag.lower())
112
+ if tid is not None:
113
+ break
114
+ j -= 1
115
+
116
+ if tid is not None:
117
+ ids.append(tid)
118
+ i = j
119
+ continue
120
+
121
+ # Fallback singolo carattere
122
+ tid = t2i.get(ch)
123
+ if tid is None and ch.isalpha():
124
+ tid = t2i.get(ch.lower())
125
+ ids.append(self.unk_id if tid is None else tid)
126
+ i += 1
127
+
128
+ if add_special_tokens and self.eos_id is not None:
129
+ ids.append(self.eos_id)
130
+
131
+ return ids
132
+
133
+ def decode(self, token_ids: Sequence[int], skip_special_tokens: bool = False) -> str:
134
+ """Decodifica gli ID di token in testo ricostruito (sostituisce i whitespace)."""
135
+ out: List[str] = []
136
+ for tid in token_ids:
137
+ tok = self.id_to_token.get(int(tid), "<|unk|>")
138
+ if skip_special_tokens and tok.startswith("<|") and tok.endswith("|>"):
139
+ continue
140
+ out.append(DECODE_WS.get(tok, tok))
141
+ return "".join(out)
142
+
143
+ def batch_encode(self, texts: Sequence[str]) -> List[List[int]]:
144
+ return [self.encode(t) for t in texts]
145
+
146
+ def batch_decode(self, batch_ids: Sequence[Sequence[int]], skip_special_tokens: bool = False) -> List[str]:
147
+ return [self.decode(ids, skip_special_tokens=skip_special_tokens) for ids in batch_ids]
148
+
149
+
150
+ if __name__ == "__main__":
151
+ tok = gpTommyTokenizer()
152
+ print(f"=== gpTommy 32k Tokenizer (Vocabolario: {tok.vocab_size} token) ===")
153
+ test_frasi = [
154
+ "ciao, come stai?",
155
+ "qual è la capitale d'italia?",
156
+ "il cuscinetto a sfera radiale riduce l'attrito volvente.",
157
+ "<|user|> spiegami il teorema di pitagora <|assistant|> certo!",
158
+ ]
159
+ for frase in test_frasi:
160
+ ids = tok.encode(frase)
161
+ ricostruita = tok.decode(ids)
162
+ print(f"\nFrase: '{frase}'")
163
+ print(f"Tokens ({len(ids)} ID): {ids[:10]}...")
164
+ print(f"Decodifica: '{ricostruita}'")
165
+ assert frase == ricostruita, f"Mismatch: {frase} != {ricostruita}"
166
+ print("\n✅ Tutti i test di conformità gpTommy 32k sono passati con successo!")
vocab.json ADDED
The diff for this file is too large to render. See raw diff