File size: 7,444 Bytes
02b7845 1559083 d761945 02b7845 af9a85b 02b7845 a3fb300 96e6c88 a3fb300 02b7845 a76e286 02b7845 a76e286 02b7845 a76e286 02b7845 a76e286 02b7845 a76e286 02b7845 a76e286 02b7845 a76e286 14e68fe b690bbc 14e68fe b690bbc 14e68fe b690bbc a76e286 02b7845 a76e286 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 |
---
license: gpl-3.0
datasets:
- Mattimax/Little_ITA_60k
language:
- it
library_name: transformers
tags:
- DAC
- data-ai
- DATA-AI
- transformer
- experimental
new_version: Mattimax/PicoDAC-IT
---
# PicoDAC

## Informazioni sul modello
- **Autore:** [Mattimax](https://huggingface.co/Mattimax)
- **Organizzazione:** [M.INC](https://huggingface.co/MINC01)
- **Pagina GitHub:** [PicoDAC](https://github.com/M-INC-01/PicoDAC/tree/main)
- **Licenza:** GPL-3.0
**Descrizione:**
PicoDAC è un modello di linguaggio compatto progettato per chat in lingua italiana. Basato su una architettura Transformer leggera, è ottimizzato per essere rapido e facilmente distribuibile. Questo modello è un **esperimento** ed è ancora in fase di sviluppo, quindi le prestazioni possono essere limitate rispetto a modelli più grandi e sofisticati.
**Dataset di addestramento:**
Il modello è stato addestrato sul dataset [Little_ITA_60k](https://huggingface.co/datasets/Mattimax/Little_ITA_60k), contenente conversazioni brevi in italiano.
**Obiettivo:**
Fornire un prototipo di chatbot italiano leggero, utile per test, sperimentazioni e applicazioni dove la dimensione del modello e la velocità sono prioritarie rispetto alla qualità generativa.
---
## Caratteristiche tecniche
* Architettura: Transformer autoregressivo compatto
* Dimensione del vocabolario: 1.920 token
* Lunghezza massima del contesto: 64 token
* Numero di strati (layers): 6
* Numero di teste di attenzione: 6
* Dimensione embedding: 240
* Quantizzazione: int8 per la maggior parte dei pesi, con embedding e layernorm ottimizzati a bit più alti
---
## Avvertenze e limitazioni
* Questo modello è **ancora sperimentale**: può generare risposte incoerenti o incomplete.
* Non è addestrato per conversazioni sensibili o contenuti critici.
* Performance su testi lunghi o conversazioni complesse sono limitate a causa della breve lunghezza del contesto e della piccola dimensione del modello.
---
## Uso previsto
* Chatbot sperimentali in italiano
* Applicazioni leggere dove la dimensione del modello è critica
* Prototipazione e testing di modelli di dialogo
**Nota:** consigliato l’uso con input brevi e contesti semplici.
---
## Installazione
```bash
pip install transformers torch
```
---
## Esempio di utilizzo in Python
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from safetensors.torch import load_file
from transformers import PreTrainedTokenizerFast
import os
# ----------------------------
# Config modello
# ----------------------------
VOCAB_SIZE = 1920
D_MODEL = 240
N_LAYERS = 6
N_HEADS = 6
D_HEAD = 40
D_FF = 960
N_CTX = 64
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Usando device: {device}")
# ----------------------------
# Scarica tokenizer e modello da HF
# ----------------------------
repo_id = "Mattimax/PicoDAC"
tokenizer_path = hf_hub_download(repo_id, "tokenizer.json")
model_path = hf_hub_download(repo_id, "model.safetensors")
# opzionale: scales_path = hf_hub_download(repo_id, "best/scales.json")
# ----------------------------
# Carica tokenizer
# ----------------------------
tokenizer = PreTrainedTokenizerFast(tokenizer_file=tokenizer_path)
tokenizer.add_special_tokens({
"pad_token": "<PAD>",
"bos_token": "<BOS>",
"eos_token": "<EOS>",
"sep_token": "<SEP>",
"unk_token": "<UNK>"
})
# ----------------------------
# RMSNorm
# ----------------------------
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-8):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x):
norm = x.pow(2).mean(-1, keepdim=True).add(self.eps).sqrt()
return x / norm * self.weight
# ----------------------------
# Transformer Block
# ----------------------------
class TransformerBlock(nn.Module):
def __init__(self):
super().__init__()
self.ln1 = RMSNorm(D_MODEL)
self.ln2 = RMSNorm(D_MODEL)
self.attn = nn.MultiheadAttention(D_MODEL, N_HEADS, batch_first=True)
self.ffn = nn.Sequential(
nn.Linear(D_MODEL, D_FF),
nn.SiLU(),
nn.Linear(D_FF, D_MODEL)
)
def forward(self, x, mask=None):
attn_out, _ = self.attn(self.ln1(x), self.ln1(x), self.ln1(x), attn_mask=mask)
x = x + attn_out
x = x + self.ffn(self.ln2(x))
return x
# ----------------------------
# TinyGPT
# ----------------------------
class TinyGPT(nn.Module):
def __init__(self):
super().__init__()
self.tok_emb = nn.Embedding(VOCAB_SIZE, D_MODEL)
self.pos_emb = nn.Embedding(N_CTX, D_MODEL)
self.layers = nn.ModuleList([TransformerBlock() for _ in range(N_LAYERS)])
self.ln_f = RMSNorm(D_MODEL)
self.head = nn.Linear(D_MODEL, VOCAB_SIZE, bias=False)
self.head.weight = self.tok_emb.weight
def forward(self, idx):
B, T = idx.shape
pos = torch.arange(T, device=idx.device).unsqueeze(0)
x = self.tok_emb(idx) + self.pos_emb(pos)
mask = torch.triu(torch.ones(T, T, device=idx.device) * float('-inf'), diagonal=1)
for layer in self.layers:
x = layer(x, mask=mask)
x = self.ln_f(x)
logits = self.head(x)
return logits
# ----------------------------
# Carica pesi
# ----------------------------
state_dict = load_file(model_path)
model = TinyGPT()
model.load_state_dict(state_dict, strict=False)
model.to(device)
model.eval()
# ----------------------------
# Funzione generazione
# ----------------------------
def generate(prompt, max_new_tokens=50, temperature=0.7):
model_input = tokenizer.encode(prompt, return_tensors="pt").to(device)
for _ in range(max_new_tokens):
logits = model(model_input)
next_token_logits = logits[0, -1, :] / temperature
probs = F.softmax(next_token_logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
model_input = torch.cat([model_input, next_token.unsqueeze(0)], dim=1)
if next_token.item() == tokenizer.eos_token_id:
break
return tokenizer.decode(model_input[0], skip_special_tokens=True)
# ----------------------------
# Loop chat
# ----------------------------
print("Chat PicoDAC (scrivi 'exit' per uscire)")
while True:
user_input = input("Tu: ").strip()
if user_input.lower() in ["exit", "quit"]:
print("Chiusura chat. Ciao!")
break
response = generate(user_input)
print(f"PicoDAC: {response}")
```
**Suggerimenti pratici:**
* Usa `max_length` basso per mantenere la coerenza delle risposte.
* Temperature intorno a 0.7–1.0 favoriscono generazioni più creative.
* Evita input troppo lunghi (oltre 64 token), perché il modello può perdere il contesto precedente.
---
## Integrazione consigliata
* **Applicazioni mobile**: dimensione ridotta e quantizzazione riducono il consumo di RAM e storage.
* **Sperimentazione NLP**: utile per test di prompt, fine-tuning leggero o per costruire dataset sintetici.
---
## Riferimenti
* Dataset: [Little_ITA_60k](https://huggingface.co/datasets/Mattimax/Little_ITA_60k)
* Autore: [Mattimax](https://huggingface.co/Mattimax)
* Organizzazione: [M.INC](https://huggingface.co/MINC01) |