Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lucianosilvi/53117247afdeaed4aa3c41d07243115b to your computer and use it in GitHub Desktop.
Save lucianosilvi/53117247afdeaed4aa3c41d07243115b to your computer and use it in GitHub Desktop.
Fine tuning de GPT-2 con GPU gratis en Colab
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Fine tuning de GPT-2 con GPU gratis en Colab",
"provenance": [],
"collapsed_sections": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"accelerator": "GPU"
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/lucianosilvi/53117247afdeaed4aa3c41d07243115b/fine-tuning-de-gpt-2-con-gpu-gratis-en-colab.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "H7LoMj4GA4n_",
"colab_type": "text"
},
"source": [
"# Fine tuning de GPT-2 con GPU gratis en Colab \n",
"\n",
"por [Luciano Silvi](https://www.linkedin.com/in/luciano-silvi-b9755437/)\n",
"Para contextualizar el experimento: [https://medium.com/@lucianosilvi/fine-tuning-de-gpt-2-para-generar-ficci%C3%B3n-en-espa%C3%B1ol-muestra-resultados-cre%C3%ADbles-e14de3838d3e](https://medium.com/@lucianosilvi/fine-tuning-de-gpt-2-para-generar-ficci%C3%B3n-en-espa%C3%B1ol-muestra-resultados-cre%C3%ADbles-e14de3838d3e)",
"\n",
"\n",
"Colab utiliza por defecto la versión 2 de Tensorflow, que tiene incompatibilidades con código escrito para versiones previas. Por compatibilidad con la librería a utilizar, cambiamos a la versión anterior."
]
},
{
"cell_type": "code",
"metadata": {
"id": "KBkpRgBCBS2_",
"colab_type": "code",
"colab": {}
},
"source": [
"%tensorflow_version 1.x\n",
"!pip install -q gpt-2-simple\n",
"import gpt_2_simple as gpt2\n",
"from datetime import datetime\n",
"from google.colab import files"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "0wXB05bPDYxS",
"colab_type": "text"
},
"source": [
"## *Mise en place*: Descargar GPT-2, acceder a Drive y cargar el dataset\n",
"\n",
"El fine tuning parte de la utilización de un modelo pre entrenado. GPT-2 ha sido liberado en 4 versiones, según los millones de parámetros utilizados durante el entrenamiento:\n",
"\n",
"* `124M`\n",
"* `355M`\n",
"* `774M` \n",
"* `1558M`\n",
"\n",
"Los últimos 2 no pueden ser refinados en Colab, pues los recursos no son suficientes, aunque pueden usarse sólo para generar texto si la GPU asignada por Colab es de las más avanzadas.\n",
"\n",
"Con la ejecución de la celda siguiente, se descargará en la VM de Colab el modelo \"small\"."
]
},
{
"cell_type": "code",
"metadata": {
"id": "P8wSlgXoDPCR",
"colab_type": "code",
"colab": {}
},
"source": [
"gpt2.download_gpt2(model_name=\"124M\")"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "N8KXuKWzQSsN",
"colab_type": "text"
},
"source": [
"Si se desea generar texto con el modelo por defecto sin hacerle fine tuning, se puede ir directamente a la sección `Generar Texto a partir del modelo`. En caso contrario, proseguimos con las celdas siguientes para refinar.\n",
"\n",
"\n",
"\n",
"---\n",
"\n",
"\n",
"\n",
"Con la siguiente celda, se habilitará el acceso al Drive personal mediante un path en la VM. Se solicita un código de autorización que se obtiene mediante el link que aparecerá. \n",
"El acceso a Drive permite guardar y cargar datasets o modelos entrenados para uso futuro, puesto que todo lo que se almacena sólo en la VM desaparece con la misma al finalizar la conexión."
]
},
{
"cell_type": "code",
"metadata": {
"id": "puq4iC6vUAHc",
"colab_type": "code",
"colab": {}
},
"source": [
"gpt2.mount_gdrive()"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "BT__brhBCvJu",
"colab_type": "text"
},
"source": [
"### Cargar el archivo de texto a Colab\n",
"\n",
"En el panel de la izquierda, en el apartado \"Files\", puede cargarse un archivo que estará en la VM durante la sesión vigente. También funciona arrastrando el archivo a cargar hacia el panel, estando ubicados previamente en el apartado \"Files\".\n",
"\n",
"Se recomienda usar este método sólo para archivos no muy grandes. En caso contrario, es mejor subirlos a Drive y accederlos mediante la ruta apropiada, de esta manera se evita la espera de carga del archivo cada vez que se desee realizar una nueva ejecución.\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "6OFnPCLADfll",
"colab_type": "code",
"colab": {}
},
"source": [
"import os\n",
"file_name = \"fiction.txt\"\n",
"filename_root = os.path.splitext(file_name)[0]\n",
"run_name = 'gpt2_finetuned_run_%s' % filename_root"
],
"execution_count": 3,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "LdpZQXknFNY3",
"colab_type": "text"
},
"source": [
"## Fine tuning\n",
"\n",
"A continuación comenzará el entrenamiento para refinar el modelo, se ejcutará por la cantidad de pasos indicado en steps. El tiempo de ejecución depende del tamaño del modelo, del dataset y de la cantidad de steps. Se sugiere comenzar con 1500 o 2000 steps y luego ir avanzando en caso de ser necesario, dado que los tiempos de ejecución habilitados en Colab son acotados, dependiendo de varios factores.\n",
"\n",
"Los checkpoints se generan cada cierta cantidad de pasos (*save_every*) en el path `/checkpoint/*run_name*` de la VM. \n",
"Es importante copiar el modelo entrenado a Drive para luego poder cargarlo sin reentrenar.\n"
]
},
{
"cell_type": "code",
"metadata": {
"id": "aeXshJM-Cuaf",
"colab_type": "code",
"colab": {}
},
"source": [
"sess = gpt2.start_tf_sess()\n",
"\n",
"\n",
"gpt2.finetune(sess,\n",
" dataset=file_name,\n",
" model_name='124M',\n",
" steps=1000,\n",
" restore_from='fresh',\n",
" run_name=run_name,\n",
" print_every=50,\n",
" sample_every=150,\n",
" save_every=500,\n",
" learning_rate=1e-4\n",
" )"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "IXSuTNERaw6K",
"colab_type": "text"
},
"source": [
"La librería utilizada abstrae el proceso de guardado del modelo entrenado en Drive, reduciéndolo sólo a la ejecución de la siguiente celda:"
]
},
{
"cell_type": "code",
"metadata": {
"id": "VHdTL8NDbAh3",
"colab_type": "code",
"colab": {}
},
"source": [
"gpt2.copy_checkpoint_to_gdrive(run_name=run_name)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "ClJwpF_ACONp",
"colab_type": "text"
},
"source": [
"## Generar texto a partir del modelo entrenado\n",
"\n",
"Llamando al método `generate` obtendremos un fragmento de texto generado a partir del modelo recién entrenado. \n",
"\n",
"El método permite diferentes parámetros opcionales:\n",
"* **`length`**: Número de tokens a generar (1023 por defecto)\n",
"* **`temperature`**: 0.7 por defecto. Valores entre 0.7 y 1.0 arrojarán resultados más novedosos, mientras que valores menores arrojarán más cantidad de textos presentes en el dataset de entrenamiento. Los valores de temperatura ideales varían de una librería o implementación a otra.\n",
"* **`truncate`**: Trunca el texto ante una secuencia dada (si `truncate='<|endoftext|>'`, el texto resultante incluirá los tokens hasta el primer `<|endoftext|>`).\n",
"* **`prefix`**: Se utiliza para indicar la *seed* con la cual comenzará el texto generado.\n",
"\n",
"Más información sobre parámetros extra puede encontrarse en la [web oficial de la librería](https://github.com/minimaxir/gpt-2-simple)"
]
},
{
"cell_type": "code",
"metadata": {
"id": "8DKMc0fiej4N",
"colab_type": "code",
"colab": {}
},
"source": [
"gpt2.generate(sess,\n",
" length=300,\n",
" temperature=0.8,\n",
" prefix=\"El profesor le dijo que no podría llegar, debido a que \",\n",
" nsamples=5,\n",
" run_name=run_name\n",
" )"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "pel-uBULXO2L",
"colab_type": "text"
},
"source": [
"## Cargar un modelo previamente entrenado desde Drive\n",
"\n",
"La siguiente celda copia el modelo entrenado desde Google Drive a la VM vigente en Colab."
]
},
{
"cell_type": "code",
"metadata": {
"id": "DCcx5u7sbPTD",
"colab_type": "code",
"colab": {}
},
"source": [
"gpt2.copy_checkpoint_from_gdrive(run_name=run_name)"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "9gZ8zgyFvoSF",
"colab_type": "text"
},
"source": [
"A continuación, cargamos el modelo."
]
},
{
"cell_type": "code",
"metadata": {
"id": "-fxL77nvAMAX",
"colab_type": "code",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 51
},
"outputId": "728fa588-1078-4ac5-df58-81f7f17d307a"
},
"source": [
"sess = gpt2.start_tf_sess()\n",
"gpt2.load_gpt2(sess, run_name=run_name)"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"text": [
"Loading checkpoint checkpoint/gpt2_finetuned_run1_all_fiction_sXX-XXI/model-1500\n",
"INFO:tensorflow:Restoring parameters from checkpoint/gpt2_finetuned_run1_all_fiction_sXX-XXI/model-1500\n"
],
"name": "stdout"
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wmTXWNUygS5E",
"colab_type": "text"
},
"source": [
"# LICENSE\n",
"\n",
"MIT License\n",
"\n",
"Copyright (c) 2020 Luciano Silvi\n",
"\n",
"Permission is hereby granted, free of charge, to any person obtaining a copy\n",
"of this software and associated documentation files (the \"Software\"), to deal\n",
"in the Software without restriction, including without limitation the rights\n",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n",
"copies of the Software, and to permit persons to whom the Software is\n",
"furnished to do so, subject to the following conditions:\n",
"\n",
"The above copyright notice and this permission notice shall be included in all\n",
"copies or substantial portions of the Software.\n",
"\n",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n",
"SOFTWARE."
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment