Come creare un modello linguistico: capire il percorso e addestrarne uno piccolo
Cosa apprende un LLM, quando scegliere RAG o fine-tuning e cosa implica partire da zero. Addestra, misura e salva una piccola rete originale.

Cosa significa creare il mio LLM?
Chiamare un modello esistente con istruzioni crea un’applicazione. RAG fornisce documenti alla domanda. Il fine-tuning cambia pesi esistenti; l’addestramento da zero parte da pesi casuali. Obiettivi e costi differiscono.
Qui capirai le opzioni e addestrerai una rete minuscola che predice caratteri, salva pesi e genera testo. È un MLP didattico, non un grande Transformer o una chat utile. Vedrai dati, previsione, errore, aggiornamento e misura senza confondere un’API con un modello addestrato.
1. Scegliere secondo il bisogno
Per manuali mutevoli valuta RAG. Per formato coerente o comportamento specifico confronta prompt e fine-tuning; non garantiscono verità. Per imparare serve questo esperimento. Un LLM generale di produzione richiede molta più ricerca e infrastruttura.
Un assistente eventi necessita procedure e fonti attuali. Un classificatore JSON può iniziare da prompt e convalida. Non ricreiamo ragionamento multilingue generale. Definisci il compito misurabile prima della GPU.
2. Termini essenziali
Il tokenizer trasforma testo in ID, qui uno per carattere. L’embedding rappresenta ID con numeri appresi. I parametri si aggiornano; il contesto è la storia visibile. Logit e softmax producono probabilità, la perdita penalizza errori sul carattere successivo e i gradienti indicano come ridurli.
Un batch raggruppa esempi, un passo aggiorna, un’epoca attraversa i dati. Qui si campionano batch: 400 passi non sono 400 epoche. Un checkpoint salva pesi, l’inferenza li usa senza cambiarli. Il campionamento cambia varietà, non conoscenze.
3. Il percorso completo
Definisci compito e valutazione, raccogli dati con diritti, elimina segreti e duplicati, separa training/validazione/test senza sovrapposizioni. Scegli tokenizer e architettura, stima memoria e calcolo, monitora perdita, salva versioni e valuta dati riservati. Versiona codice, dati e configurazione.
Un assistente può richiedere istruzioni, allineamento e sicurezza. Il servizio richiede autenticazione, limiti e monitoraggio. Il budget dipende da parametri, token, ottimizzatore, precisione, sequenza e hardware. Nessuna promessa di LLM produttivo a prezzo fisso.
4. Il modello scaricabile
Contesto di otto caratteri, embedding di 12 dimensioni, strato tanh con 48 unità e output sul vocabolario. Il corpus fornito produce 6.303 parametri. Usa NumPy e CPU con gradienti espliciti, senza attention o Transformer.
I dati sono frasi originali fittizie. I test verificano perdita di training ridotta, probabilità finite con somma uno, errore per caratteri sconosciuti e predizioni identiche dopo salvataggio. Non misurano conoscenza generale.
5. Installare, addestrare e salvare
Estrai in una nuova cartella. Servono Python 3.9+ e NumPy. Installare usa il registro; addestrare non necessita modello scaricato, account, chiave o GPU. È ammesso NumPy 2.x e i numeri possono variare.
Esegui test e model.py: stampa parametri, perdite ed esempio, salva tiny-model.npz nella cartella corrente. Inizia dal corpus dato. Se lo cambi, conserva lo spazio per padding e controlla diritti. Niente segreti o conversazioni private.
# Python 3.9+; create an isolated environment in the extracted folder.
python3 -m venv .venv
# macOS/Linux (Windows: .venv\Scripts\activate)
. .venv/bin/activate
python -m pip install -r requirements.txt
python -m unittest discover -p 'test_*.py'
python model.py --steps 400
# Output checkpoint: tiny-model.npz6. Interpretare la misura
La prova locale ha ridotto la perdita da circa 3.3004 a 0.9185 in 400 passi. Predice meglio il corpus, ma il testo resta incoerente: è atteso a questa scala.
Si misura sui dati di training, senza prova di generalizzazione. Memorizzare non basta. Più passi possono sovra-adattare. Prepara validazione separata e confronta entrambe le perdite con prefissi fissi. Un numero inferiore non dimostra utilità o verità.
Measured local run, seed 7, supplied corpus, 400 training steps:
parameters: 6303
training_loss_before: 3.3004
training_loss_after: 0.9185
sample begins: seatimin whean sert tes s vitg ...
Interpretation: the model learned local character patterns.
It still produces nonsense and has not demonstrated general knowledge.
These are training-set measurements, not held-out quality scores.7. Ricaricare e generare
L’inferenza carica pesi e campiona senza aggiornarli. La finestra di otto caratteri scorre. Un carattere sconosciuto genera errore esplicito. Il file NumPy si carica senza pickle, ma verifica comunque provenienza e fiducia.
# The training objective: predict the NEXT character.
# Input: "seating "
# Target: the following character in the training text.
# In the supplied model, each input contains exactly 8 characters.
# Generation uses the last 8 characters to predict a distribution,
# samples one character, appends it, then repeats.
from model import load
model = load("tiny-model.npz")
print(model.generate("seat", count=120, seed=42))7b. Usare il modello da un’app locale
Dopo il training, server.py carica tiny-model.npz ed espone POST /generate locale. Invia prefix="seat" e count=40: restituisce generated_text ed educational=true. È testo didattico, non consiglio affidabile.
Il training resta Python/NumPy. Le schede chiamano lo stesso modello, non lo addestrano in PHP o browser. Il server limita input e ascolta soltanto localhost; produzione richiede framework, autenticazione e controlli adeguati.
# First train the model with the instructions above.
# Keep your Python virtual environment active.
python server.py
# Keep this terminal open. The API listens only on 127.0.0.1:8765.
# Browser demo: open http://127.0.0.1:8765/
# In ANOTHER terminal, from this same project folder:
# Choose your client (Python needs the same environment).
python client.py
# OR: Node.js 22+
node client.mjs
# OR: PHP 8.1+ with HTTP URL wrappers enabled
php client.php7c. Scegliere il linguaggio client
Scegli una scheda ed esegui il file. Python, Node.js e PHP usano URL locale completo. JavaScript funziona nella demo http://127.0.0.1:8765/; /generate rimane sulla stessa origine. Non incollarlo in altri siti. Premi Generate 40 characters.
Tutti inviano lo stesso JSON e ricevono il campione deterministico. educational=true non prova comprensione. Se fallisce controlla training, server e porta. Carattere ignoto o count fuori da 1..200 restituisce errore leggibile.
import json
from urllib.request import Request,urlopen
request=Request('http://127.0.0.1:8765/generate',
data=json.dumps({'prefix':'seat','count':40}).encode(),
headers={'Content-Type':'application/json'},method='POST')
with urlopen(request,timeout=10) as response:
result=json.load(response)
print(json.dumps(result,indent=2))// Node.js 22+. First run the Python model and local server.
const response = await fetch('http://127.0.0.1:8765/generate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({prefix: 'seat', count: 40}),
signal: AbortSignal.timeout(10_000),
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Generation failed');
console.log(JSON.stringify(result, null, 2));// Run on http://127.0.0.1:8765/ served by this local project.
// That page already contains <button id="generate"> and <pre id="result">.
document.querySelector('#generate').addEventListener('click', async () => {
const output = document.querySelector('#result');
try {
const response = await fetch('/generate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({prefix: 'seat', count: 40}),
signal: AbortSignal.timeout(10_000),
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Generation failed');
output.textContent = JSON.stringify(result, null, 2);
} catch (error) {
output.textContent = error.message;
}
});<?php
// PHP 8.1+ with HTTP URL wrappers enabled; run the Python server first.
$context = stream_context_create(['http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode(['prefix' => 'seat', 'count' => 40]),
'timeout' => 10,
'ignore_errors' => true,
'follow_location' => 0,
]]);
$raw = file_get_contents('http://127.0.0.1:8765/generate', false, $context);
if ($raw === false) throw new RuntimeException('Local server unavailable');
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if (isset($result['error'])) throw new RuntimeException($result['error']);
echo json_encode($result, JSON_PRETTY_PRINT).PHP_EOL;{
"model": "tiny-character-mlp",
"educational": true,
"generated_text": "seatimin whean sert tes s vitg bemovge peans"
}8. Il rapporto con un Transformer
Un Transformer autoregressivo predice token con più profondità e dati. L’attenzione combina posizioni consentite e la maschera causale impedisce di leggere il futuro. Ci sono anche posizione, blocchi feed-forward, residui e normalizzazione. Questo MLP non li implementa.
Continua con un Transformer causale separato e test di tensori/maschera o il corso Stanford. Per un prodotto confronta modelli preaddestrati con licenza adatta. LoRA modifica pesi con aggiornamenti a rango basso; non crea un modello fondazionale dal nulla. Verifica diritti e valutazione.
9. IA come insegnante e revisore
Il primo prompt richiede spiegazione ed esecuzione con misure ed esempio. Dichiarare pronto il proprio ChatGPT sarebbe ingannevole. Il secondo prepara un adattamento vero senza avviare implicitamente training costoso.
Act as a patient machine-learning teacher. Inspect this tiny NumPy character
language model and explain its data flow before modifying anything.
Identify the vocabulary, eight-character context, embeddings, hidden layer,
softmax probabilities, next-character targets, loss and gradient update.
Run the local tests, train with 400 steps, save the checkpoint and reload it.
Report actual parameter count, training loss before/after and a generated sample.
Explain why reduced training loss is not evidence of held-out quality or truth.
Do not describe this 6,303-parameter educational MLP as a large Transformer,
a chat assistant or a production LLM. Do not download a model or private dataset.
Propose one next learning experiment with a measurable success criterion.10. Risultato e seguito
Hai addestrato, misurato, salvato, ricaricato e generato. Distingui modello, applicazione, RAG e adattamento. Cambia una variabile con valutazione separata e confronta il riferimento. Per il business parti dal bisogno e confronta modelli esistenti e RAG.
Before proposing a REAL model adaptation, ask for the task, licensed base model,
data rights, deployment language, evaluation set, hardware and budget.
Compare RAG, prompting, LoRA fine-tuning and training from scratch for that task.
If fine-tuning is justified, propose an isolated reproducible experiment:
base-model revision, tokenizer, non-overlapping train/validation/test splits,
training configuration, checkpoint policy, metrics and comparison with baseline.
Include privacy leakage, memorization and unsupported-answer evaluations.
State estimates and untested assumptions explicitly. Do not start an expensive
training job, publish weights or use private data without the agreed scope.Riferimenti ufficiali e approfondimenti
- Stanford CS336 · Language Modeling from Scratch
- Vaswani et al. · Attention Is All You Need
- Hugging Face PEFT · LoRA
- NumPy · Random generator
- Python · Local teaching HTTP server
- Node.js · fetch
- PHP · HTTP context options
Portalo nel tuo progetto
Scarica i file, conserva la guida o consegna al tuo assistente istruzioni pronte.
Prepara con l’IA
Copia questo prompt inglese nel tuo assistente. Include articolo, file disponibili e passaggi di preparazione.
Mostra il prompt di preparazione
Read this tutorial as reference material:
https://nethanelfitoussi.com/article/create-language-model-explained?lang=en
Goal: apply the documented workflow to my development project.
Read the existing project instructions, inspect the relevant files and explain the smallest useful setup.
Available starter files:
https://nethanelfitoussi.com/api/media/08d5b33c-5d92-4495-ae4a-729eb570d94d.zip
Download and inspect these files in a temporary folder before using them. Do not overwrite existing project instructions.
If I have not supplied a project folder, ask which development project to use. Do not invent a repository URL.
Additional project setup instructions:
Extract the supplied ZIP into a NEW folder. Read README.md before installing or running code.
Act as a patient machine-learning teacher. Inspect this tiny NumPy character
language model and explain its data flow before modifying anything.
Identify the vocabulary, eight-character context, embeddings, hidden layer,
softmax probabilities, next-character targets, loss and gradient update.
Run the local tests, train with 400 steps, save the checkpoint and reload it.
Report actual parameter count, training loss before/after and a generated sample.
Explain why reduced training loss is not evidence of held-out quality or truth.
Do not describe this 6,303-parameter educational MLP as a large Transformer,
a chat assistant or a production LLM. Do not download a model or private dataset.
Propose one next learning experiment with a measurable success criterion.
Before proposing a REAL model adaptation, ask for the task, licensed base model,
data rights, deployment language, evaluation set, hardware and budget.
Compare RAG, prompting, LoRA fine-tuning and training from scratch for that task.
If fine-tuning is justified, propose an isolated reproducible experiment:
base-model revision, tokenizer, non-overlapping train/validation/test splits,
training configuration, checkpoint policy, metrics and comparison with baseline.
Include privacy leakage, memorization and unsupported-answer evaluations.
State estimates and untested assumptions explicitly. Do not start an expensive
training job, publish weights or use private data without the agreed scope.
Adapt example paths, commands and acceptance criteria to this repository rather than assuming they match.
Give me a short plan, then make the agreed local changes and run the relevant checks. Report actual results and anything not verified. Stop before credentials, paid services, production changes, push, merge or deployment.

