currentfear commited on
Commit
905357e
·
verified ·
1 Parent(s): fe03f0d

Notebook de entrenamiento para Colab T4

Browse files
Files changed (1) hide show
  1. orpheus_colab.ipynb +482 -0
orpheus_colab.ipynb ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "accelerator": "GPU",
6
+ "colab": {
7
+ "gpuType": "T4",
8
+ "provenance": []
9
+ },
10
+ "kernelspec": {
11
+ "display_name": "Python 3",
12
+ "name": "python3"
13
+ },
14
+ "language_info": {
15
+ "name": "python"
16
+ }
17
+ },
18
+ "cells": [
19
+ {
20
+ "cell_type": "markdown",
21
+ "metadata": {},
22
+ "source": [
23
+ "# Clonar la voz en español con Orpheus + Unsloth (Colab T4)\n",
24
+ "\n",
25
+ "Entrena un LoRA sobre **Orpheus 3B oficial en español** (`canopylabs/3b-es_it-ft-research_release`, Apache 2.0)\n",
26
+ "con las 1.000 grabaciones del dataset privado [`currentfear/voz-es`](https://huggingface.co/datasets/currentfear/voz-es)\n",
27
+ "y genera audio para ir escuchando cómo queda.\n",
28
+ "\n",
29
+ "**Cómo usarlo**\n",
30
+ "1. `Entorno de ejecución → Cambiar tipo de entorno → GPU T4`.\n",
31
+ "2. Añade tu token de Hugging Face como secreto: icono de la llave 🔑 en la barra izquierda →\n",
32
+ " `Agregar nuevo secreto` → nombre `HF_TOKEN`, valor `hf_...` → activa *Acceso del notebook*.\n",
33
+ " (Si no lo haces, el notebook te lo pedirá al ejecutarse.)\n",
34
+ "3. `Entorno de ejecución → Ejecutar todo`.\n",
35
+ "3. Al final de cada época se generan las frases de prueba y aparecen aquí mismo para escucharlas.\n",
36
+ "4. Cuando termine, usa la celda **Generar audio** con la frase que quieras. Cada audio sale en `.wav` y en `.ogg` listo para WhatsApp.\n",
37
+ "\n",
38
+ "Tiempo aproximado en T4: ~10 min de descarga y preparación + ~10–15 min por época con 1.000 frases."
39
+ ]
40
+ },
41
+ {
42
+ "cell_type": "markdown",
43
+ "metadata": {},
44
+ "source": [
45
+ "## 1. Instalación"
46
+ ]
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "execution_count": null,
52
+ "outputs": [],
53
+ "source": [
54
+ "%%capture\n",
55
+ "import os, re\n",
56
+ "if \"COLAB_\" not in \"\".join(os.environ.keys()):\n",
57
+ " !pip install unsloth\n",
58
+ "else:\n",
59
+ " import torch; v = re.match(r'[\\d]{1,}\\.[\\d]{1,}', str(torch.__version__)).group(0)\n",
60
+ " xformers = 'xformers==' + {'2.10':'0.0.34','2.9':'0.0.33.post1','2.8':'0.0.32.post2'}.get(v, \"0.0.34\")\n",
61
+ " !pip install sentencepiece protobuf \"datasets==4.3.0\" \"huggingface_hub>=0.34.0\" hf_transfer\n",
62
+ " !pip install --no-deps unsloth_zoo bitsandbytes accelerate {xformers} peft trl triton unsloth\n",
63
+ " !pip install --no-deps --upgrade \"torchao>=0.16.0\"\n",
64
+ "!pip install transformers==4.56.2\n",
65
+ "!pip install --no-deps trl==0.22.2\n",
66
+ "!pip install snac soundfile"
67
+ ]
68
+ },
69
+ {
70
+ "cell_type": "markdown",
71
+ "metadata": {},
72
+ "source": [
73
+ "## 2. Configuración\n",
74
+ "Cambia aquí las frases de prueba o los parámetros."
75
+ ]
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "execution_count": null,
81
+ "outputs": [],
82
+ "source": [
83
+ "import os, re\n",
84
+ "HF_DATASET = \"currentfear/voz-es\" # dataset privado (1.000 clips, 24 kHz)\n",
85
+ "BASE_MODEL = \"canopylabs/3b-es_it-ft-research_release\" # Orpheus 3B oficial español/italiano\n",
86
+ "LORA_REPO = \"currentfear/voz-es-orpheus-lora\" # donde se sube el modelo entrenado (privado)\n",
87
+ "SPEAKER = \"voz\" # nombre con el que se entrena la voz (va delante del texto)\n",
88
+ "\n",
89
+ "EPOCHS = 3 # pasadas completas por las 1.000 frases\n",
90
+ "LEARNING_RATE= 2e-4\n",
91
+ "BATCH_SIZE = 4 # frases por paso en la GPU (se reduce solo si no cabe)\n",
92
+ "GRAD_ACCUM = 4 # lote efectivo = BATCH_SIZE * GRAD_ACCUM\n",
93
+ "LORA_RANK = 64\n",
94
+ "MAX_SEQ_LEN = 1024 # la frase más larga del dataset ocupa ~800 tokens\n",
95
+ "\n",
96
+ "FRASES_PRUEBA = [\n",
97
+ " \"Hola jefe, Feláp está poderoso.\",\n",
98
+ " \"Hola jefe, ¿cuándo vamos por unas hamburguesas?\",\n",
99
+ " \"Hola jefe, una pregunta, ¿cuándo nos vamos a Orlando a Disney?\",\n",
100
+ "]\n",
101
+ "\n",
102
+ "SUBIR_A_HF = True # subir el LoRA entrenado a LORA_REPO al terminar\n",
103
+ "\n",
104
+ "# Token de Hugging Face: secreto de Colab \"HF_TOKEN\" o se pide por teclado\n",
105
+ "try:\n",
106
+ " from google.colab import userdata\n",
107
+ " HF_TOKEN = userdata.get(\"HF_TOKEN\")\n",
108
+ "except Exception:\n",
109
+ " HF_TOKEN = None\n",
110
+ "if not HF_TOKEN:\n",
111
+ " from getpass import getpass\n",
112
+ " HF_TOKEN = getpass(\"Token de Hugging Face (hf_...): \").strip()\n",
113
+ "os.environ[\"HF_TOKEN\"] = HF_TOKEN"
114
+ ]
115
+ },
116
+ {
117
+ "cell_type": "markdown",
118
+ "metadata": {},
119
+ "source": [
120
+ "## 3. Descargar el dataset y el modelo base\n",
121
+ "Del modelo solo se bajan los pesos (~13 GB); el repo trae además un `optimizer.pt` de 26 GB que no hace falta."
122
+ ]
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "execution_count": null,
128
+ "outputs": [],
129
+ "source": [
130
+ "import io, time\n",
131
+ "import pyarrow.parquet as pq\n",
132
+ "from huggingface_hub import hf_hub_download, snapshot_download\n",
133
+ "\n",
134
+ "t0 = time.time()\n",
135
+ "parquet = hf_hub_download(HF_DATASET, \"data/train-00000-of-00001.parquet\", repo_type=\"dataset\", token=HF_TOKEN)\n",
136
+ "table = pq.read_table(parquet)\n",
137
+ "print(f\"Dataset: {table.num_rows} grabaciones · {time.time()-t0:.0f}s\")\n",
138
+ "print(\"Ejemplo:\", table.column(\"text\")[0].as_py())\n",
139
+ "\n",
140
+ "t0 = time.time()\n",
141
+ "MODEL_DIR = snapshot_download(BASE_MODEL, token=HF_TOKEN,\n",
142
+ " allow_patterns=[\"*.json\", \"*.safetensors\"])\n",
143
+ "print(f\"Modelo base descargado en {time.time()-t0:.0f}s\")"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "markdown",
148
+ "metadata": {},
149
+ "source": [
150
+ "## 4. Cargar Orpheus + LoRA"
151
+ ]
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "execution_count": null,
157
+ "outputs": [],
158
+ "source": [
159
+ "from unsloth import FastLanguageModel\n",
160
+ "import torch\n",
161
+ "\n",
162
+ "model, tokenizer = FastLanguageModel.from_pretrained(\n",
163
+ " model_name = MODEL_DIR,\n",
164
+ " max_seq_length = MAX_SEQ_LEN,\n",
165
+ " dtype = None, # T4 → float16 automáticamente\n",
166
+ " load_in_4bit = False, # 16 bits: mejor calidad y cabe en los 15 GB de la T4\n",
167
+ ")\n",
168
+ "model = FastLanguageModel.get_peft_model(\n",
169
+ " model,\n",
170
+ " r = LORA_RANK,\n",
171
+ " lora_alpha = LORA_RANK,\n",
172
+ " target_modules = [\"q_proj\", \"k_proj\", \"v_proj\", \"o_proj\", \"gate_proj\", \"up_proj\", \"down_proj\"],\n",
173
+ " lora_dropout = 0,\n",
174
+ " bias = \"none\",\n",
175
+ " use_gradient_checkpointing = \"unsloth\", # ahorra VRAM para usar lotes grandes\n",
176
+ " random_state = 3407,\n",
177
+ ")\n",
178
+ "gpu = torch.cuda.get_device_properties(0)\n",
179
+ "print(f\"GPU {gpu.name} · {gpu.total_memory/2**30:.1f} GB · reservado {torch.cuda.memory_reserved()/2**30:.1f} GB\")"
180
+ ]
181
+ },
182
+ {
183
+ "cell_type": "markdown",
184
+ "metadata": {},
185
+ "source": [
186
+ "## 5. Convertir el audio a tokens (SNAC)\n",
187
+ "Mismo formato que el notebook oficial de Orpheus de Unsloth."
188
+ ]
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "execution_count": null,
194
+ "outputs": [],
195
+ "source": [
196
+ "import numpy as np, soundfile as sf, gc\n",
197
+ "from snac import SNAC\n",
198
+ "from datasets import Dataset\n",
199
+ "\n",
200
+ "TOKENISER_LENGTH = 128256\n",
201
+ "END_OF_TEXT = 128009\n",
202
+ "START_OF_SPEECH = TOKENISER_LENGTH + 1\n",
203
+ "END_OF_SPEECH = TOKENISER_LENGTH + 2\n",
204
+ "START_OF_HUMAN = TOKENISER_LENGTH + 3\n",
205
+ "END_OF_HUMAN = TOKENISER_LENGTH + 4\n",
206
+ "START_OF_AI = TOKENISER_LENGTH + 5\n",
207
+ "END_OF_AI = TOKENISER_LENGTH + 6\n",
208
+ "PAD_TOKEN = TOKENISER_LENGTH + 7\n",
209
+ "AUDIO_START = TOKENISER_LENGTH + 10\n",
210
+ "\n",
211
+ "snac = SNAC.from_pretrained(\"hubertsiuzdak/snac_24khz\").eval().to(\"cuda\")\n",
212
+ "\n",
213
+ "def encode_audio(wav):\n",
214
+ " x = torch.from_numpy(wav).float().cuda().view(1, 1, -1)\n",
215
+ " with torch.inference_mode():\n",
216
+ " c0, c1, c2 = (c.squeeze(0).cpu().tolist() for c in snac.encode(x))\n",
217
+ " out = []\n",
218
+ " for i in range(len(c0)):\n",
219
+ " out += [c0[i] + AUDIO_START,\n",
220
+ " c1[2*i] + AUDIO_START + 4096,\n",
221
+ " c2[4*i] + AUDIO_START + 2*4096,\n",
222
+ " c2[4*i+1] + AUDIO_START + 3*4096,\n",
223
+ " c1[2*i+1] + AUDIO_START + 4*4096,\n",
224
+ " c2[4*i+2] + AUDIO_START + 5*4096,\n",
225
+ " c2[4*i+3] + AUDIO_START + 6*4096]\n",
226
+ " # quitar frames repetidos consecutivos (igual que el notebook de Unsloth)\n",
227
+ " res = out[:7]\n",
228
+ " for i in range(7, len(out), 7):\n",
229
+ " if out[i] != res[-7]:\n",
230
+ " res += out[i:i+7]\n",
231
+ " return res\n",
232
+ "\n",
233
+ "def prompt_ids(text):\n",
234
+ " ids = tokenizer(f\"{SPEAKER}: {text}\", add_special_tokens=True).input_ids\n",
235
+ " return [START_OF_HUMAN] + ids + [END_OF_TEXT, END_OF_HUMAN]\n",
236
+ "\n",
237
+ "examples, skipped = [], 0\n",
238
+ "for i, row in enumerate(table.to_pylist()):\n",
239
+ " text = row[\"text\"]\n",
240
+ " wav, sr = sf.read(io.BytesIO(row[\"audio\"][\"bytes\"]), dtype=\"float32\")\n",
241
+ " assert sr == 24000\n",
242
+ " ids = prompt_ids(text) + [START_OF_AI, START_OF_SPEECH] + encode_audio(wav) + [END_OF_SPEECH, END_OF_AI]\n",
243
+ " if len(ids) > MAX_SEQ_LEN:\n",
244
+ " skipped += 1\n",
245
+ " continue\n",
246
+ " examples.append({\"input_ids\": ids})\n",
247
+ " if (i + 1) % 200 == 0:\n",
248
+ " print(f\"{i+1}/{table.num_rows}\")\n",
249
+ "\n",
250
+ "del table; gc.collect()\n",
251
+ "lengths = [len(e[\"input_ids\"]) for e in examples]\n",
252
+ "print(f\"{len(examples)} ejemplos (omitidos por largos: {skipped}) · tokens min/media/max {min(lengths)}/{int(np.mean(lengths))}/{max(lengths)}\")\n",
253
+ "train_dataset = Dataset.from_list(examples)"
254
+ ]
255
+ },
256
+ {
257
+ "cell_type": "markdown",
258
+ "metadata": {},
259
+ "source": [
260
+ "## 6. Funciones para generar audio"
261
+ ]
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "execution_count": null,
267
+ "outputs": [],
268
+ "source": [
269
+ "import subprocess, os, re\n",
270
+ "from IPython.display import Audio, display, Markdown\n",
271
+ "os.makedirs(\"/content/salidas\", exist_ok=True)\n",
272
+ "\n",
273
+ "def decode_codes(codes):\n",
274
+ " codes = codes[: len(codes) // 7 * 7]\n",
275
+ " l0, l1, l2 = [], [], []\n",
276
+ " for i in range(len(codes) // 7):\n",
277
+ " f = [c - AUDIO_START - k * 4096 for k, c in enumerate(codes[7*i:7*i+7])]\n",
278
+ " l0.append(f[0]); l1 += [f[1], f[4]]; l2 += [f[2], f[3], f[5], f[6]]\n",
279
+ " layers = [torch.tensor(l, device=\"cuda\").unsqueeze(0) for l in (l0, l1, l2)]\n",
280
+ " if any((t < 0).any() or (t > 4095).any() for t in layers):\n",
281
+ " return None\n",
282
+ " with torch.inference_mode():\n",
283
+ " return snac.decode(layers).squeeze().float().cpu().numpy()\n",
284
+ "\n",
285
+ "def a_whatsapp(wav_path):\n",
286
+ " ogg = wav_path[:-4] + \".ogg\"\n",
287
+ " subprocess.run([\"ffmpeg\", \"-hide_banner\", \"-loglevel\", \"error\", \"-y\", \"-i\", wav_path,\n",
288
+ " \"-ac\", \"1\", \"-ar\", \"48000\", \"-c:a\", \"libopus\", \"-b:a\", \"32k\", \"-application\", \"voip\", ogg], check=True)\n",
289
+ " return ogg\n",
290
+ "\n",
291
+ "def generar(texto, n=2, temperature=0.6, top_p=0.95, repetition_penalty=1.1, nombre=None, mostrar=True):\n",
292
+ " \"\"\"Genera n versiones de `texto`, las muestra y las guarda en /content/salidas (.wav + .ogg).\"\"\"\n",
293
+ " FastLanguageModel.for_inference(model)\n",
294
+ " prompt = prompt_ids(texto) + [START_OF_AI, START_OF_SPEECH]\n",
295
+ " ids = torch.tensor([prompt], device=\"cuda\")\n",
296
+ " with torch.inference_mode():\n",
297
+ " out = model.generate(\n",
298
+ " input_ids = ids, attention_mask = torch.ones_like(ids),\n",
299
+ " max_new_tokens = 1500, do_sample = True,\n",
300
+ " temperature = temperature, top_p = top_p, repetition_penalty = repetition_penalty,\n",
301
+ " num_return_sequences = n, eos_token_id = END_OF_SPEECH, pad_token_id = PAD_TOKEN,\n",
302
+ " )\n",
303
+ " nombre = nombre or re.sub(r\"[^a-z0-9]+\", \"_\", texto.lower())[:40].strip(\"_\")\n",
304
+ " if mostrar:\n",
305
+ " display(Markdown(f\"**{texto}**\"))\n",
306
+ " paths = []\n",
307
+ " for k, seq in enumerate(out):\n",
308
+ " codes = [t for t in seq[len(prompt):].tolist() if AUDIO_START <= t < AUDIO_START + 7 * 4096]\n",
309
+ " wav = decode_codes(codes)\n",
310
+ " if wav is None or len(wav) < 2400:\n",
311
+ " print(f\" versión {k+1}: salió mal, se descarta\")\n",
312
+ " continue\n",
313
+ " path = f\"/content/salidas/{nombre}-{k+1}.wav\"\n",
314
+ " sf.write(path, wav, 24000)\n",
315
+ " a_whatsapp(path)\n",
316
+ " paths.append(path)\n",
317
+ " if mostrar:\n",
318
+ " print(f\" versión {k+1} · {len(wav)/24000:.1f}s · {path}\")\n",
319
+ " display(Audio(wav, rate=24000))\n",
320
+ " return paths"
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "markdown",
325
+ "metadata": {},
326
+ "source": [
327
+ "## 7. (Opcional) Cómo suena ANTES de entrenar\n",
328
+ "Para comparar. Puedes saltarte esta celda."
329
+ ]
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "execution_count": null,
335
+ "outputs": [],
336
+ "source": [
337
+ "generar(FRASES_PRUEBA[0], n=1, nombre=\"antes_de_entrenar\")"
338
+ ]
339
+ },
340
+ {
341
+ "cell_type": "markdown",
342
+ "metadata": {},
343
+ "source": [
344
+ "## 8. Entrenar\n",
345
+ "Al terminar **cada época** se generan las frases de prueba y aparecen debajo, para ir escuchando cómo mejora.\n",
346
+ "La pérdida (`loss`) debería ir bajando; con estos datos suele terminar alrededor de 3,4–3,7."
347
+ ]
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "execution_count": null,
353
+ "outputs": [],
354
+ "source": [
355
+ "from transformers import Trainer, TrainingArguments, TrainerCallback\n",
356
+ "from unsloth import is_bf16_supported\n",
357
+ "\n",
358
+ "def collate(batch):\n",
359
+ " n = max(len(b[\"input_ids\"]) for b in batch)\n",
360
+ " ids = torch.full((len(batch), n), PAD_TOKEN, dtype=torch.long)\n",
361
+ " mask = torch.zeros((len(batch), n), dtype=torch.long)\n",
362
+ " for i, b in enumerate(batch):\n",
363
+ " L = len(b[\"input_ids\"])\n",
364
+ " ids[i, :L] = torch.tensor(b[\"input_ids\"]); mask[i, :L] = 1\n",
365
+ " labels = ids.masked_fill(mask == 0, -100)\n",
366
+ " return {\"input_ids\": ids, \"attention_mask\": mask, \"labels\": labels}\n",
367
+ "\n",
368
+ "class EscucharCadaEpoca(TrainerCallback):\n",
369
+ " def on_epoch_end(self, args, state, control, **kw):\n",
370
+ " ep = round(state.epoch)\n",
371
+ " display(Markdown(f\"### Época {ep} · loss {state.log_history[-1].get('loss', float('nan')):.3f}\"))\n",
372
+ " try:\n",
373
+ " for i, frase in enumerate(FRASES_PRUEBA):\n",
374
+ " generar(frase, n=1, nombre=f\"epoca{ep}_frase{i+1}\")\n",
375
+ " except Exception as e:\n",
376
+ " print(\"No se pudo generar la muestra:\", e)\n",
377
+ " finally:\n",
378
+ " FastLanguageModel.for_training(model)\n",
379
+ " torch.cuda.empty_cache()\n",
380
+ "\n",
381
+ "trainer = Trainer(\n",
382
+ " model = model,\n",
383
+ " train_dataset = train_dataset,\n",
384
+ " data_collator = collate,\n",
385
+ " callbacks = [EscucharCadaEpoca()],\n",
386
+ " args = TrainingArguments(\n",
387
+ " per_device_train_batch_size = BATCH_SIZE,\n",
388
+ " gradient_accumulation_steps = GRAD_ACCUM,\n",
389
+ " auto_find_batch_size = True, # si no cabe en la VRAM, baja el lote solo\n",
390
+ " group_by_length = True, # agrupa frases de largo parecido → menos relleno, más rápido\n",
391
+ " num_train_epochs = EPOCHS,\n",
392
+ " learning_rate = LEARNING_RATE,\n",
393
+ " warmup_steps = 5,\n",
394
+ " lr_scheduler_type = \"linear\",\n",
395
+ " optim = \"adamw_8bit\",\n",
396
+ " weight_decay = 0.01,\n",
397
+ " fp16 = not is_bf16_supported(),\n",
398
+ " bf16 = is_bf16_supported(),\n",
399
+ " logging_steps = 5,\n",
400
+ " dataloader_num_workers = 2,\n",
401
+ " dataloader_pin_memory = True,\n",
402
+ " save_strategy = \"no\",\n",
403
+ " seed = 3407,\n",
404
+ " output_dir = \"outputs\",\n",
405
+ " report_to = \"none\",\n",
406
+ " remove_unused_columns = False,\n",
407
+ " ),\n",
408
+ ")\n",
409
+ "\n",
410
+ "FastLanguageModel.for_training(model)\n",
411
+ "stats = trainer.train()\n",
412
+ "print(f\"Entrenamiento: {stats.metrics['train_runtime']/60:.1f} min · pico VRAM {torch.cuda.max_memory_reserved()/2**30:.1f} GB de {gpu.total_memory/2**30:.1f} GB\")"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "markdown",
417
+ "metadata": {},
418
+ "source": [
419
+ "## 9. Generar audio\n",
420
+ "Cambia la frase y ejecuta. Consejos:\n",
421
+ "- Escribe como se pronuncia (`Feláp` en vez de `Felapp`).\n",
422
+ "- Las comas, puntos y `¿?` `¡!` cambian mucho la entonación.\n",
423
+ "- `temperature`: 0.5 más estable · 0.6 normal · 0.7 más expresiva.\n",
424
+ "- Puedes usar etiquetas del dataset: `<giggle>`, `<pause>`, `<whisper>`, `<sigh>`..."
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "metadata": {},
430
+ "execution_count": null,
431
+ "outputs": [],
432
+ "source": [
433
+ "frase = \"Hola jefe, ¿cuándo vamos por unas hamburguesas?\"\n",
434
+ "generar(frase, n=3, temperature=0.6)"
435
+ ]
436
+ },
437
+ {
438
+ "cell_type": "markdown",
439
+ "metadata": {},
440
+ "source": [
441
+ "## 10. Descargar los audios generados"
442
+ ]
443
+ },
444
+ {
445
+ "cell_type": "code",
446
+ "metadata": {},
447
+ "execution_count": null,
448
+ "outputs": [],
449
+ "source": [
450
+ "import shutil\n",
451
+ "from google.colab import files\n",
452
+ "shutil.make_archive(\"/content/salidas\", \"zip\", \"/content/salidas\")\n",
453
+ "files.download(\"/content/salidas.zip\")"
454
+ ]
455
+ },
456
+ {
457
+ "cell_type": "markdown",
458
+ "metadata": {},
459
+ "source": [
460
+ "## 11. Guardar el modelo entrenado (LoRA, ~390 MB)\n",
461
+ "Se sube a tu Hugging Face como repositorio privado, para no perderlo cuando Colab se desconecte."
462
+ ]
463
+ },
464
+ {
465
+ "cell_type": "code",
466
+ "metadata": {},
467
+ "execution_count": null,
468
+ "outputs": [],
469
+ "source": [
470
+ "model.save_pretrained(\"/content/lora_voz\")\n",
471
+ "tokenizer.save_pretrained(\"/content/lora_voz\")\n",
472
+ "if SUBIR_A_HF:\n",
473
+ " model.push_to_hub(LORA_REPO, token=HF_TOKEN, private=True)\n",
474
+ " tokenizer.push_to_hub(LORA_REPO, token=HF_TOKEN, private=True)\n",
475
+ " print(f\"Subido: https://huggingface.co/{LORA_REPO}\")\n",
476
+ "else:\n",
477
+ " shutil.make_archive(\"/content/lora_voz\", \"zip\", \"/content/lora_voz\")\n",
478
+ " files.download(\"/content/lora_voz.zip\")"
479
+ ]
480
+ }
481
+ ]
482
+ }