Instructions to use Patricale/Italian_GPT_mlx with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use Patricale/Italian_GPT_mlx with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # if on a CUDA device, also pip install mlx[cuda] # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("Patricale/Italian_GPT_mlx") prompt = "Once upon a time in" text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- MLX LM
How to use Patricale/Italian_GPT_mlx with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Generate some text mlx_lm.generate --model "Patricale/Italian_GPT_mlx" --prompt "Once upon a time"
- Atomic Chat
Download minigpt/model.py from Patricale/Italian_GPT_mlx: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/Patricale/Italian_GPT_mlx/resolve/main/minigpt/model.py
- Command line
-
hf download hf://Patricale/Italian_GPT_mlx/minigpt/model.py
-
curl -L -o model.py https://huggingface.co/Patricale/Italian_GPT_mlx/resolve/main/minigpt/model.py
18.4 kB
| """Il modello: transformer decoder-only in stile GPT, scritto con primitive MLX. | |
| Schema (pre-norm): | |
| token ids (B, T) | |
| │ embedding -> (B, T, C) | |
| ▼ | |
| ┌─ Block × n_layer ───────────────────────────┐ | |
| │ x = x + Attention(RMSNorm(x)) ← RoPE qui │ | |
| │ x = x + MLP(RMSNorm(x)) │ | |
| └─────────────────────────────────────────────┘ | |
| │ RMSNorm finale | |
| │ LM head = embedding trasposto (weight tying) -> logits (B, T, V) | |
| Convenzioni sulle shape: B = batch, T = lunghezza sequenza, C = d_model, H = n_head, | |
| D = head_dim = C / H, V = vocab_size. | |
| Non c'è un embedding posizionale sommato all'ingresso: l'informazione di posizione entra | |
| solo dentro l'attention, tramite RoPE. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import mlx.core as mx | |
| import mlx.nn as nn | |
| import numpy as np | |
| from mlx.utils import tree_flatten, tree_unflatten | |
| from minigpt.config import ModelConfig | |
| # -------------------------------------------------------------------------------------- | |
| # RMSNorm | |
| # -------------------------------------------------------------------------------------- | |
| class RMSNorm(nn.Module): | |
| """Root Mean Square normalization. | |
| RMS(x) = sqrt( mean_i(x_i²) + eps ) | |
| y = g * x / RMS(x) | |
| Rispetto a LayerNorm toglie due cose: la sottrazione della media e il bias. L'idea | |
| (Zhang & Sennrich, 2019) è che il beneficio di LayerNorm venga quasi tutto dal | |
| *riscalare* le attivazioni, non dal ricentrarle: resta un vettore di norma fissa | |
| (RMS = 1, cioè norma L2 = sqrt(C)) con un guadagno `g` appreso per dimensione, a | |
| costo minore. L'output è invariante alla scala dell'input: RMSNorm(a·x) = RMSNorm(x). | |
| Shape: (..., C) -> (..., C) | |
| """ | |
| def __init__(self, dims: int, eps: float = 1e-5) -> None: | |
| super().__init__() | |
| self.weight = mx.ones((dims,)) # guadagno g, parte da 1 | |
| self.eps = eps | |
| def __call__(self, x: mx.array) -> mx.array: | |
| rms = mx.sqrt(mx.mean(mx.square(x), axis=-1, keepdims=True) + self.eps) # (..., 1) | |
| return self.weight * (x / rms) | |
| class LayerNorm(nn.Module): | |
| """Layer normalization classica (Ba et al., 2016), per il confronto con RMSNorm. | |
| y = g * (x - media(x)) / sqrt(var(x) + eps) + b | |
| Rispetto a RMSNorm in più sottrae la media e ha un bias `b`: 2·C parametri invece di C. | |
| Shape: (..., C) -> (..., C) | |
| """ | |
| def __init__(self, dims: int, eps: float = 1e-5) -> None: | |
| super().__init__() | |
| self.weight = mx.ones((dims,)) | |
| self.bias = mx.zeros((dims,)) | |
| self.eps = eps | |
| def __call__(self, x: mx.array) -> mx.array: | |
| mean = mx.mean(x, axis=-1, keepdims=True) | |
| var = mx.var(x, axis=-1, keepdims=True) | |
| return self.weight * (x - mean) / mx.sqrt(var + self.eps) + self.bias | |
| def make_norm(cfg: ModelConfig) -> nn.Module: | |
| """La normalizzazione scelta in `cfg.norm_type`.""" | |
| cls = LayerNorm if cfg.norm_type == "layernorm" else RMSNorm | |
| return cls(cfg.d_model, cfg.norm_eps) | |
| # -------------------------------------------------------------------------------------- | |
| # RoPE | |
| # -------------------------------------------------------------------------------------- | |
| def apply_rope(x: mx.array, offset: int = 0, base: float = 10000.0, scale: float = 1.0) -> mx.array: | |
| """Rotary Position Embedding (Su et al., 2021). | |
| Invece di *sommare* un vettore di posizione all'embedding, RoPE *ruota* query e key | |
| di un angolo proporzionale alla loro posizione. Le D dimensioni sono viste come D/2 | |
| coppie (x_{2i}, x_{2i+1}), cioè D/2 punti nel piano; la coppia i del token in | |
| posizione m viene ruotata dell'angolo m·θ_i, con | |
| θ_i = base^(-2i / D), i = 0 .. D/2 - 1 | |
| [x'_{2i} ] [cos mθ_i -sin mθ_i] [x_{2i} ] | |
| [x'_{2i+1}] = [sin mθ_i cos mθ_i] [x_{2i+1}] | |
| Perché funziona: il prodotto scalare tra due vettori ruotati di m·θ e n·θ dipende | |
| solo dalla differenza degli angoli, quindi | |
| <RoPE(q, m), RoPE(k, n)> = f(q, k, m - n) | |
| e lo score di attention vede direttamente la posizione *relativa*. Le frequenze θ_i | |
| vanno da 1 (i = 0: un giro ogni ~6 token, distingue posizioni vicine) a ~1/base | |
| (lunghezza d'onda di decine di migliaia di token, distingue quelle lontane), come | |
| nelle sinusoidi del Transformer originale. Essendo una rotazione non cambia la norma | |
| dei vettori, e si applica solo a q e k (non a v). | |
| Args: | |
| x: (..., T, D) con D pari; tipicamente (B, H, T, D). | |
| offset: posizione assoluta del primo token di `x`. È 0 in training; con la KV | |
| cache si elabora un token per volta e l'offset dice dove si trova. | |
| base: base delle frequenze (10000 di default). | |
| scale: fattore applicato alle posizioni (m -> scale·m). Con scale < 1 si fa | |
| "position interpolation": un contesto più lungo di quello di training viene | |
| compresso nell'intervallo di posizioni già visto. Vedi Fase 6. | |
| Returns: | |
| Tensore ruotato, stessa shape di `x`. | |
| """ | |
| T, D = x.shape[-2], x.shape[-1] | |
| half = D // 2 | |
| theta = base ** (-mx.arange(half, dtype=mx.float32) / half) # (D/2,) = base^(-2i/D) | |
| positions = scale * mx.arange(offset, offset + T, dtype=mx.float32) # (T,) | |
| angles = positions[:, None] * theta[None, :] # (T, D/2): angolo m·θ_i | |
| cos, sin = mx.cos(angles), mx.sin(angles) # (T, D/2), broadcast su (..., T, D/2) | |
| x_even = x[..., 0::2] # (..., T, D/2): prima coordinata di ogni coppia | |
| x_odd = x[..., 1::2] # (..., T, D/2): seconda coordinata | |
| rot_even = x_even * cos - x_odd * sin | |
| rot_odd = x_even * sin + x_odd * cos | |
| # Rimette le coppie nell'ordine originale: (..., T, D/2, 2) -> (..., T, D) | |
| return mx.stack([rot_even, rot_odd], axis=-1).reshape(x.shape) | |
| # -------------------------------------------------------------------------------------- | |
| # Attention | |
| # -------------------------------------------------------------------------------------- | |
| def causal_mask(T: int) -> mx.array: | |
| """Maschera additiva (T, T): 0 dove j <= i, -inf dove j > i (il futuro). | |
| Sommata agli score prima della softmax, porta a zero il peso di attention sulle | |
| posizioni future: exp(-inf) = 0. | |
| """ | |
| return mx.triu(mx.full((T, T), -math.inf), k=1) | |
| class KVCache: | |
| """Key e value già calcolate per i token passati, per *un* layer di attention. | |
| Perché si può fare. In generazione si aggiunge un token alla volta. Grazie alla | |
| maschera causale, tutto ciò che un layer calcola per le posizioni 0..t-1 non dipende | |
| dal token t: rifare il forward sull'intera sequenza ricalcola ogni volta gli stessi | |
| numeri. In particolare non cambiano le key e le value dei token passati, che sono | |
| tutto ciò che serve al token nuovo per fare attention su di loro. Le si salva qui e a | |
| ogni passo si elabora solo il token nuovo: | |
| senza cache: passo t = forward su t token -> O(t²) per token (attention) | |
| con cache: passo t = forward su 1 token, | |
| che fa attention su t key salvate -> O(t) per token | |
| Le key sono salvate *già ruotate* da RoPE con la loro posizione assoluta: non vanno | |
| più toccate. Al token nuovo basta ruotare la propria query e la propria key con | |
| offset = numero di token già in cache. | |
| Shape: k, v: (B, H, T_passati, D), oppure None se la cache è vuota. | |
| """ | |
| def __init__(self) -> None: | |
| self.k: mx.array | None = None | |
| self.v: mx.array | None = None | |
| def length(self) -> int: | |
| """Numero di posizioni già in cache.""" | |
| return 0 if self.k is None else self.k.shape[2] | |
| def append(self, k: mx.array, v: mx.array) -> tuple[mx.array, mx.array]: | |
| """Accoda le key/value dei token nuovi e restituisce quelle di tutta la sequenza.""" | |
| if self.k is not None: | |
| k = mx.concatenate([self.k, k], axis=2) # (B, H, T_passati + T_nuovi, D) | |
| v = mx.concatenate([self.v, v], axis=2) | |
| self.k, self.v = k, v | |
| return k, v | |
| class Attention(nn.Module): | |
| """Self-attention causale multi-head con RoPE. | |
| Per ogni head: score = (q · kᵀ) / sqrt(D) + maschera causale | |
| out = softmax(score) · v | |
| Ogni posizione t costruisce una query ("cosa cerco"), ogni posizione s <= t espone | |
| una key ("cosa offro") e un value ("cosa consegno"); l'output in t è la media dei | |
| value pesata dalla compatibilità query-key. La divisione per sqrt(D) tiene la | |
| varianza degli score ~1 indipendentemente da D, così la softmax non satura. | |
| Le quattro proiezioni sono `nn.Linear` separate e senza bias: tenerle distinte | |
| (invece di un'unica matrice qkv) rende banale applicare LoRA solo a q e v. | |
| Con `cache` (generazione): `x` contiene solo i token *nuovi*, che fanno attention | |
| sulle key/value in cache più le proprie. Vedi `KVCache`. | |
| Shape: (B, T, C) -> (B, T, C) | |
| """ | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.n_head = cfg.n_head | |
| self.head_dim = cfg.head_dim | |
| self.rope_base = cfg.rope_base | |
| self.use_rope = cfg.use_rope | |
| self.rope_scale = 1.0 # vedi `apply_rope(scale=...)` | |
| # Se True, i pesi di attention dell'ultimo forward restano in `_last_attention` | |
| # (il prefisso "_" evita che MLX li scambi per parametri del modello). | |
| self.record_attention = False | |
| self._last_attention = None | |
| self.q_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) | |
| self.k_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) | |
| self.v_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) | |
| self.o_proj = nn.Linear(cfg.d_model, cfg.d_model, bias=False) | |
| self.attn_dropout = nn.Dropout(cfg.dropout) | |
| self.resid_dropout = nn.Dropout(cfg.dropout) | |
| def _split_heads(self, x: mx.array) -> mx.array: | |
| """(B, T, C) -> (B, H, T, D): ogni head lavora su una fetta di D dimensioni.""" | |
| B, T, _ = x.shape | |
| return x.reshape(B, T, self.n_head, self.head_dim).transpose(0, 2, 1, 3) | |
| def __call__(self, x: mx.array, cache: KVCache | None = None) -> mx.array: | |
| B, T, C = x.shape # T = token in ingresso (tutti, oppure solo i nuovi con la cache) | |
| q = self._split_heads(self.q_proj(x)) # (B, H, T, D) | |
| k = self._split_heads(self.k_proj(x)) # (B, H, T, D) | |
| v = self._split_heads(self.v_proj(x)) # (B, H, T, D) | |
| # La posizione entra qui: q e k vengono ruotate, v no. Con la cache i token in | |
| # ingresso non partono dalla posizione 0 ma da `past`. | |
| past = cache.length if cache is not None else 0 | |
| if self.use_rope: | |
| q = apply_rope(q, offset=past, base=self.rope_base, scale=self.rope_scale) | |
| k = apply_rope(k, offset=past, base=self.rope_base, scale=self.rope_scale) | |
| if cache is not None: | |
| k, v = cache.append(k, v) # (B, H, S, D) con S = past + T: tutta la sequenza | |
| # Senza cache S = T. Con la cache le query sono solo quelle dei T token nuovi. | |
| scores = (q @ k.transpose(0, 1, 3, 2)) / math.sqrt(self.head_dim) # (B, H, T, S) | |
| # Maschera: le ultime T righe di quella (S, S). Il token nuovo vede tutto il | |
| # passato; se i nuovi sono più d'uno (prompt iniziale) restano causali tra loro. | |
| scores = scores + causal_mask(past + T)[past:] # (T, S), broadcast su (B, H) | |
| weights = mx.softmax(scores, axis=-1) # (B, H, T, S), ogni riga somma a 1 | |
| if self.record_attention: | |
| self._last_attention = weights | |
| weights = self.attn_dropout(weights) | |
| out = weights @ v # (B, H, T, D) | |
| out = out.transpose(0, 2, 1, 3).reshape(B, T, C) # riunisce le head: (B, T, C) | |
| return self.resid_dropout(self.o_proj(out)) | |
| # -------------------------------------------------------------------------------------- | |
| # MLP | |
| # -------------------------------------------------------------------------------------- | |
| class MLP(nn.Module): | |
| """Feed-forward applicata a ogni posizione in modo indipendente. | |
| Due varianti, scelte da `cfg.mlp_type`: | |
| - "gelu": y = W_proj · GELU(W_fc · x) d_hidden = 4·C | |
| - "swiglu": y = W_proj · (SiLU(W_gate · x) ⊙ W_fc · x) d_hidden = 2/3 · 4·C | |
| SwiGLU (usata in LLaMA) sostituisce l'attivazione con un *gate* moltiplicativo: un | |
| ramo decide quanto far passare dell'altro. Ha tre matrici invece di due, per cui | |
| d_hidden viene ridotto a 2/3 e il numero di parametri resta lo stesso. | |
| Shape: (B, T, C) -> (B, T, C) | |
| """ | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.mlp_type = cfg.mlp_type | |
| hidden = cfg.mlp_ratio * cfg.d_model | |
| if self.mlp_type == "swiglu": | |
| hidden = int(2 * hidden / 3) | |
| self.gate = nn.Linear(cfg.d_model, hidden, bias=False) | |
| self.fc = nn.Linear(cfg.d_model, hidden, bias=False) | |
| self.proj = nn.Linear(hidden, cfg.d_model, bias=False) | |
| self.dropout = nn.Dropout(cfg.dropout) | |
| def __call__(self, x: mx.array) -> mx.array: | |
| if self.mlp_type == "swiglu": | |
| h = nn.silu(self.gate(x)) * self.fc(x) # (B, T, hidden) | |
| else: | |
| h = nn.gelu(self.fc(x)) # (B, T, hidden) | |
| return self.dropout(self.proj(h)) | |
| # -------------------------------------------------------------------------------------- | |
| # Block e GPT | |
| # -------------------------------------------------------------------------------------- | |
| class Block(nn.Module): | |
| """Blocco transformer pre-norm. | |
| x = x + Attention(RMSNorm(x)) | |
| x = x + MLP(RMSNorm(x)) | |
| "Pre-norm": la normalizzazione sta sul ramo, non sul percorso residuo. Il residual | |
| stream `x` attraversa tutta la rete senza mai essere normalizzato, e i gradienti | |
| hanno un percorso diretto (identità) dall'uscita fino all'embedding: il training è | |
| più stabile rispetto al post-norm del Transformer originale. | |
| Shape: (B, T, C) -> (B, T, C) | |
| """ | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.norm1 = make_norm(cfg) | |
| self.attn = Attention(cfg) | |
| self.norm2 = make_norm(cfg) | |
| self.mlp = MLP(cfg) | |
| def __call__(self, x: mx.array, cache: KVCache | None = None) -> mx.array: | |
| x = x + self.attn(self.norm1(x), cache=cache) | |
| x = x + self.mlp(self.norm2(x)) | |
| return x | |
| class GPT(nn.Module): | |
| """Transformer decoder-only. | |
| Weight tying: la LM head non ha pesi propri, riusa la matrice di embedding E (V, C): | |
| ingresso: x_t = E[token_t] (riga di E) | |
| uscita: logits = h · Eᵀ (prodotto scalare con ogni riga di E) | |
| Il logit del token w è quindi la similarità tra lo stato finale h e l'embedding di w. | |
| Si risparmiano V·C parametri (1.57M su 12.2M nella config di default) e ogni token | |
| riceve gradiente sia quando è in ingresso sia quando è un candidato in uscita. | |
| Shape: idx (B, T) int -> logits (B, T, V) | |
| """ | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.cfg = cfg | |
| self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) | |
| self.emb_dropout = nn.Dropout(cfg.dropout) | |
| self.blocks = [Block(cfg) for _ in range(cfg.n_layer)] | |
| self.norm_f = make_norm(cfg) | |
| init_weights(self) | |
| def make_cache(self) -> list[KVCache]: | |
| """Una cache vuota per layer, da passare a `__call__` durante la generazione.""" | |
| return [KVCache() for _ in self.blocks] | |
| def __call__(self, idx: mx.array, cache: list[KVCache] | None = None) -> mx.array: | |
| """Con `cache`, `idx` contiene solo i token nuovi e i logit restituiti sono | |
| solo i loro; la cache viene aggiornata in place.""" | |
| x = self.emb_dropout(self.tok_emb(idx)) # (B, T, C) | |
| for i, block in enumerate(self.blocks): | |
| x = block(x, cache=cache[i] if cache is not None else None) # (B, T, C) | |
| x = self.norm_f(x) # (B, T, C) | |
| return x @ self.tok_emb.weight.T # (B, T, V): LM head = embedding trasposto | |
| def init_weights(model: GPT) -> None: | |
| """Inizializzazione in stile GPT-2. | |
| - Tutte le matrici (embedding e Linear): N(0, 0.02²). Valori piccoli → logit iniziali | |
| vicini a zero → distribuzione quasi uniforme → loss iniziale ≈ ln(V). | |
| - Le proiezioni che *scrivono* nel residual stream (`attn.o_proj`, `mlp.proj`): | |
| N(0, (0.02 / sqrt(2·n_layer))²). Il residual stream è la somma di 2·n_layer | |
| contributi; se ognuno ha varianza σ² la somma ha varianza 2L·σ². Dividere σ per | |
| sqrt(2L) rende la varianza dell'uscita indipendente dalla profondità. | |
| - I guadagni delle RMSNorm restano a 1 (sono vettori 1-D: non vengono toccati). | |
| """ | |
| std = 0.02 | |
| resid_std = std / math.sqrt(2 * model.cfg.n_layer) | |
| new_params = [] | |
| for name, p in tree_flatten(model.parameters()): | |
| if p.ndim == 2: | |
| is_residual_proj = name.endswith(("attn.o_proj.weight", "mlp.proj.weight")) | |
| p = (resid_std if is_residual_proj else std) * mx.random.normal(p.shape) | |
| new_params.append((name, p)) | |
| model.update(tree_unflatten(new_params)) | |
| def count_parameters(module: nn.Module) -> int: | |
| """Numero totale di parametri (scalari) del modulo.""" | |
| return sum(p.size for _, p in tree_flatten(module.parameters())) | |
| def attention_maps(model: GPT, idx: mx.array) -> list: | |
| """Pesi di attention di ogni layer per la sequenza `idx` (1, T). | |
| Returns: | |
| lista di n_layer array numpy (H, T, T): l'elemento [h, i, j] è quanto la head h, | |
| dalla posizione i (query), guarda la posizione j (key). Ogni riga somma a 1 e | |
| per j > i vale 0 (maschera causale). | |
| """ | |
| was_training = model.training | |
| model.eval() | |
| for block in model.blocks: | |
| block.attn.record_attention = True | |
| mx.eval(model(idx)) | |
| maps = [np.array(block.attn._last_attention[0]) for block in model.blocks] | |
| for block in model.blocks: | |
| block.attn.record_attention = False | |
| block.attn._last_attention = None | |
| model.train(was_training) | |
| return maps | |