{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Inżynieria uczenia maszynowego\n", "### 17 kwietnia 2024\n", "# 7. Sacred" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Sacred\n", "> Every experiment is sacred
\n", "> Every experiment is great
\n", "> If an experiment is wasted
\n", "> God gets quite irate\n", ">\n", " —https://github.com/IDSIA/sacred / [Sens życia według Monty Pythona](https://en.wikipedia.org/wiki/Every_Sperm_Is_Sacred) " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "- https://sacred.readthedocs.io/ - dokumentacja\n", "- https://github.com/IDSIA/sacred - Github\n", "- Open source\n", "- Prosty w użyciu\n", "- Wiele webowych frontendów" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "- Przeprowadzanie eksperymentów (zmiana parametrów, trenowanie, ewaluacja) uczenia maszynowego jest kosztowne i czasochłonne\n", "- Dlatego warto przeprowadzać je w zorganizowany sposób\n", "- I tak, żebyśmy mogli powtórzyć / odtworzyć raz uzyskane wyniki" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "> Sacred is a tool to help you:\n", "> - configure\n", "> - organize\n", "> - log \n", "> - reproduce \n", "> experiments. \n", "> \n", ">It is designed to do all the tedious overhead work that you need to do around your actual experiment in order to:\n", "> - keep track of all the parameters of your experiment\n", "> - easily run your experiment for different settings\n", "> - save configurations for individual runs in a database\n", "> - reproduce your results\n", " \n", " —https://github.com/IDSIA/sacred" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "- **ConfigScopes** A very convenient way of the local variables in a function to define the parameters your experiment uses.\n", "- **Config Injection** You can access all parameters of your configuration from every function. They are automatically injected by name.\n", "- **Command-line interface** You get a powerful command-line interface for each experiment that you can use to change parameters and run different variants.\n", "- **Observers** Sacred provides Observers that log all kinds of information about your experiment, its dependencies, the configuration you used, the machine it is run on, and of course the result. These can be saved to a MongoDB, for easy access later.\n", "- **Automatic seeding** helps controlling the randomness in your experiments, such that the results remain reproducible." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Instalacja" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting sacred\n", " Downloading sacred-0.8.5-py2.py3-none-any.whl (107 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m107.9/107.9 KB\u001b[0m \u001b[31m2.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n", "\u001b[?25hCollecting jsonpickle>=2.2.0\n", " Downloading jsonpickle-3.0.4-py3-none-any.whl (39 kB)\n", "Collecting colorama>=0.4\n", " Downloading colorama-0.4.6-py2.py3-none-any.whl (25 kB)\n", "Collecting munch<5.0,>=2.5\n", " Downloading munch-4.0.0-py2.py3-none-any.whl (9.9 kB)\n", "Requirement already satisfied: packaging>=18.0 in ./venv/lib/python3.10/site-packages (from sacred) (24.0)\n", "Collecting wrapt<2.0,>=1.0\n", " Downloading wrapt-1.16.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (80 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m80.3/80.3 KB\u001b[0m \u001b[31m12.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hCollecting docopt<1.0,>=0.3\n", " Downloading docopt-0.6.2.tar.gz (25 kB)\n", " Preparing metadata (setup.py) ... \u001b[?25ldone\n", "\u001b[?25hCollecting GitPython\n", " Downloading GitPython-3.1.43-py3-none-any.whl (207 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m207.3/207.3 KB\u001b[0m \u001b[31m9.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hCollecting py-cpuinfo>=4.0\n", " Downloading py_cpuinfo-9.0.0-py3-none-any.whl (22 kB)\n", "Collecting gitdb<5,>=4.0.1\n", " Downloading gitdb-4.0.11-py3-none-any.whl (62 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m62.7/62.7 KB\u001b[0m \u001b[31m15.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", "\u001b[?25hCollecting smmap<6,>=3.0.1\n", " Downloading smmap-5.0.1-py3-none-any.whl (24 kB)\n", "Using legacy 'setup.py install' for docopt, since package 'wheel' is not installed.\n", "Installing collected packages: py-cpuinfo, docopt, wrapt, smmap, munch, jsonpickle, colorama, gitdb, GitPython, sacred\n", " Running setup.py install for docopt ... \u001b[?25ldone\n", "\u001b[?25hSuccessfully installed GitPython-3.1.43 colorama-0.4.6 docopt-0.6.2 gitdb-4.0.11 jsonpickle-3.0.4 munch-4.0.0 py-cpuinfo-9.0.0 sacred-0.8.5 smmap-5.0.1 wrapt-1.16.0\n" ] } ], "source": [ "!pip3 install sacred" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Funkcja main" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting IUM_07/sacred_hello.py\n" ] } ], "source": [ "%%writefile IUM_07/sacred_hello.py\n", "from sacred import Experiment\n", "\n", "ex = Experiment()\n", "\n", "@ex.automain\n", "def my_main():\n", " print('Witaj świecie!')\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "WARNING - sacred_hello - No observers have been added to this run\n", "INFO - sacred_hello - Running command 'my_main'\n", "INFO - sacred_hello - Started\n", "Witaj świecie!\n", "INFO - sacred_hello - Completed after 0:00:00\n" ] } ], "source": [ "!python3 IUM_07/sacred_hello.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### Co się dzieje w kodzie powyżej?\n", "1. Tworzymy obiekt klasy Experiment\n", "2. Dekorujemy funkcję \"my_main\" dekoratorem [automain](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.Experiment.automain)\n", " Dzięki temu:\n", " - otrzymujemy interfejs CLI, m.in. do kontrolowania poziomu logowania, przekazywania parametrów itp.\n", " - oznaczamy funkcję \"my_main\" jako główną funkcję, która będzie wywoływana podczas wykonywania eksperymentu\n", " - funkcja oznaczona jako główna musi być ostatnią funkcją zdefiniowaną w pliku!\n", " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### Co nam daje interejs CLI:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Usage:\n", " sacred_hello.py [(with UPDATE...)] [options]\n", " sacred_hello.py help [COMMAND]\n", " sacred_hello.py (-h | --help)\n", " sacred_hello.py COMMAND [(with UPDATE...)] [options]\n", "\n", "\n", "\n", "Options:\n", " -b VALUE --beat-interval=VALUE Set the heart-beat interval for this run. Time\n", " between two heartbeat events is measured in\n", " seconds.\n", " -C VALUE --capture=VALUE Control the way stdout and stderr are captured.\n", " The argument value must be one of [no, sys, fd]\n", " -c VALUE --comment=VALUE Add a comment to this run.\n", " -d --debug Set this run to debug mode. Suppress warnings\n", " about missing observers and don't filter the\n", " stacktrace. Also enables usage with ipython\n", " `--pdb`.\n", " -e --enforce_clean Fail if any version control repository is\n", " dirty.\n", " -F VALUE --file_storage=VALUE Add a file-storage observer to the experiment.\n", " The value of the arguement should be the base-\n", " directory to write the runs to\n", " -f --force Disable warnings about suspicious changes for\n", " this run.\n", " -h --help Print this help message and exit.\n", " -i VALUE --id=VALUE Set the id for this run.\n", " -l VALUE --loglevel=VALUE Set the LogLevel. Loglevel either as 0 - 50 or\n", " as string: DEBUG(10), INFO(20), WARNING(30),\n", " ERROR(40), CRITICAL(50)\n", " -m VALUE --mongo_db=VALUE Add a MongoDB Observer to the experiment. The\n", " argument value is the database specification.\n", " Should be in the form: `[host:port:]db_name[.c\n", " ollection[:id]][!priority]`\n", " -n VALUE --name=VALUE Set the name for this run.\n", " -D --pdb Automatically enter post-mortem debugging with\n", " pdb on failure.\n", " -p --print-config Always print the configuration first.\n", " -P VALUE --priority=VALUE Sets the priority for a queued up experiment.\n", " `--priority=NUMBER` The number represent the\n", " priority for this run.\n", " -q --queue Only queue this run, do not start it.\n", " -S VALUE --s3=VALUE Add a S3 File observer to the experiment. The\n", " argument value should be\n", " `s3:///path/to/exp`.\n", " -s VALUE --sql=VALUE Add a SQL Observer to the experiment. The\n", " typical form is:\n", " dialect://username:password@host:port/database\n", " -t VALUE --tiny_db=VALUE Add a TinyDB Observer to the experiment. The\n", " argument is the path to be given to the\n", " TinyDbObserver.\n", " -u --unobserved Ignore all observers for this run.\n", "\n", "\n", "Arguments:\n", " COMMAND Name of command to run (see below for list of commands)\n", " UPDATE Configuration assignments of the form foo.bar=17\n", "\n", "\n", "Commands:\n", " print_config Print the updated configuration and exit.\n", " print_dependencies Print the detected source-files and dependencies.\n", " save_config Store the updated configuration in a file.\n", " print_named_configs Print the available named configs and exit.\n", " my_main \n", "\n" ] } ], "source": [ "!python3 IUM_07/sacred_hello.py -h" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Konfiguracje\n", " - Konfiguracje pozwalają nam sparametryzować wywołania eksperymentu.\n", " - Ułatwiają przekazywanie parametrów - zmienne z konfiguracji są wstrzykiwane do funkcji wywoływanych \n", " - Mogą być automatycznie zapisywane (dzięki czemu możemy śledzić jak zmieniały się parametry i jaki miały wpływ na wyniki)\n", " - Konfigurację można stworzyć w jeden z 3 sposobów:\n", " - używając config scopes (z dekoratorem `@config`)\n", " - jako słownik\n", " - wczytując ją z pliku" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Konfiguracje - config scopes\n", "Jeśli oznaczymy jakąś funkcję dekoratorem `@config`, to zostanie ona uruchoniona przed wywołaniem eksperymentu i wszystkie jej lokalne zmienne, które da się zserializować jako json, zostaną dodane do konfiguracji. Potem ich wartości zostaną wstrzyknięte do innych funkcji wywoływanych w eksperymencie. " ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "from sacred import Experiment\n", "\n", "exint = Experiment(\"sacred_scopes\", interactive=True) #Jeśli wykonujemy interaktywnie (w konsoli Pythona albo w Jupyter):\n", "# - musimy podać nazwę eksperymentu (domyślnie jako nazwa używana jest nazwa pliku źródłowego)\n", "# - musimy dodać parametr \"interactive=True\"\n", "# - zamiast dekoratora \"@ex.automain\" używamy \"@ex.main\"\n", "\n", "@exint.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", " message = \"{0} {1}!\".format(greeting, recipient)\n", "\n", "\n", "@exint.main\n", "def my_main(message):\n", " print(message)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING - sacred_scopes - No observers have been added to this run\n", "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Witaj Świecie!\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exint.run()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "##### Możemy podejrzeć wartości zmiennych w konfiguracji:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "{'recipient': 'Świecie', 'greeting': 'Witaj', 'message': 'Witaj Świecie!'}" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_config()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Parametry możemy podejrzeć i modyfikować z poziomu CLI\n", " - wartości podane w CLI nadpiszą te podane w kodzie" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting IUM_07/sacred_scopes.py\n" ] } ], "source": [ "%%writefile IUM_07/sacred_scopes.py\n", "from sacred import Experiment\n", "\n", "ex = Experiment()\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", " message = \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.automain\n", "def my_main(message):\n", " print(message)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "WARNING - sacred_scopes - No observers have been added to this run\n", "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started\n", "Witaj Przygodo!\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] } ], "source": [ "!python3 IUM_07/sacred_scopes.py with 'recipient=Przygodo'" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO - sacred_scopes - Running command 'print_config'\n", "INFO - sacred_scopes - Started\n", "Configuration (\u001b[34mmodified\u001b[0m, \u001b[32madded\u001b[0m, \u001b[31mtypechanged\u001b[0m, \u001b[2mdoc\u001b[0m):\n", " greeting = 'Witaj'\n", " message = 'Witaj Świecie!'\n", " recipient = 'Świecie'\n", " seed = 166269169 \u001b[2m# the random seed for this experiment\u001b[0m\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] } ], "source": [ "!python3 IUM_07/sacred_scopes.py print_config" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO - sacred_scopes - Running command 'print_config'\n", "INFO - sacred_scopes - Started\n", "Configuration (\u001b[34mmodified\u001b[0m, \u001b[32madded\u001b[0m, \u001b[31mtypechanged\u001b[0m, \u001b[2mdoc\u001b[0m):\n", " greeting = 'Witaj'\n", " message = 'Witaj Przygodo!'\n", "\u001b[34m recipient = 'Przygodo'\u001b[0m\n", " seed = 496449715 \u001b[2m# the random seed for this experiment\u001b[0m\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] } ], "source": [ "!python IUM_07/sacred_scopes.py print_config with 'recipient=Przygodo'" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Wczytywanie konfiguracji z pliku" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "{'recipient': 'samotności', 'greeting': 'Żegnaj'}" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# %load IUM_07/config.json\n", "{\n", " \"recipient\": \"samotności\",\n", " \"greeting\": \"Żegnaj\"\n", "}" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "from sacred import Experiment\n", "\n", "ex = Experiment(\"sacred_scopes\", interactive=True) #Jeśli wykonujemy interaktywnie (w konsoli Pythona albo w Jupyter):\n", "# - musimy podać nazwę eksperymentu (domyślnie jako nazwa używana jest nazwa pliku źródłowego)\n", "# - musimy dodać parametr \"interactive=True\"\n", "# - zamiast \"automain\" używamy parametru \"main\"\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "ex.add_config(\"IUM_07/config.json\")\n", "\n", "\n", "@ex.main\n", "def my_main(recipient, greeting):\n", " print(\"{0} {1}!\".format(greeting, recipient))" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING - sacred_scopes - No observers have been added to this run\n", "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Żegnaj samotności!\n" ] } ], "source": [ "r = ex.run()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "{'recipient': 'samotności', 'greeting': 'Żegnaj', 'seed': 557578089}" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.config" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Możemy modyfikować części konfiguracji bezpośrednio przed wywołaniem" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING - sacred_scopes - No observers have been added to this run\n", "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Żegnaj nudo!\n" ] } ], "source": [ "r = ex.run(config_updates={\"recipient\":\"nudo\"})" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Wstrzykiwanie zależności\n", " - Oprócz funkcji głównej, wartości z konfiguracji są też wstrzykiwane do funkcji udekorowanych dekoratorem `@ex.capture`\n", " - Możemy korzystać w nich ze specjalnych parametrów, np.:\n", " - `_log` - daje nam dostęp do obiektu logera (więcej: [logowanie](https://sacred.readthedocs.io/en/stable/logging.html))\n", " - `_run` - daje dostęp do obiektu reprezentującego aktualne wywołanie eksperymentu (przykład później)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING - sacred_scopes - No observers have been added to this run\n", "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started\n", "INFO - prepare_message - Enterred prepare_message\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Witaj Świecie!\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sacred import Experiment\n", "\n", "ex = Experiment(\"sacred_scopes\", interactive=True)\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "@ex.capture\n", "def prepare_message(recipient, greeting, _log):\n", " _log.info(\"Enterred prepare_message\")\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.main\n", "def my_main():\n", " print(prepare_message()) ## Nie musimy przekazywać wartości\n", " \n", "ex.run()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Obserwowanie eksperymentów\n", "Sacred zapisuje szereg informacji na temat każdego eksperymentu:\n", " - czas wykonania\n", " - konfigurację\n", " - tekst zwrócony na stdout/stderr\n", " - błędy, jeśli wystąpiły\n", " - podstawowe informacje o środowisku (maszynie), na której przeprowadzono eksperyment\n", " - użyte pliki źródłowe\n", " - użyte zależności i ich wersje\n", " - pliki otwarte za pomocą [ex.open_resource()](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.Experiment.open_resource) albo [ex.add_resource()](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.Experiment.add_resource)\n", " - pliki dodane za pomocą [ex.add_artifact()](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.run.Run.add_artifact)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 8\n", "drwxr-xr-x 2 pawel pawel 4096 Apr 17 07:51 1\n", "drwxr-xr-x 2 pawel pawel 4096 Apr 17 07:51 _sources\n" ] } ], "source": [ "!ls -l my_runs" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Obserwowane infromacje mogą zostać zapisane za pomocą jednego z [obserwatorów](https://sacred.readthedocs.io/en/stable/observers.html):\n", " - Mongo Observer - zapisuje dane w MongoDB\n", " - File Storage Observer - zapisuje dane lokalnie w pliku\n", " - TinyDB Observer - korzysta z lokalnej bazy zapisanej w pliku JSON\n", " - SQL Observer - przechowuje informacje w bazie SQL\n", " - S3 Observer - korzysta z AWS S3\n", " - gcs_observer - korzysta z Google Cloud Storage\n", " - Queue Observer - rodzaj lokalnego bufora nakładanego na jeden z powyższych\n", " - Slack Observer - używany do powiadomień wysyłanych na komunikator Slack\n", " - Telegram Observer - używany do powiadomień wysyłanych na komunikator Telegram" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### File storage observer\n", "- zapisuje informacje o eksperymencie w lokalnych plikach \n", "- można go dodać tak: `ex.observers.append(FileStorageObserver('my_runs_directory'))`, gdzie `my_runs_directory` to ścieżka, gdzie będą zapisywane informacje o eksperymentach" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting IUM_07/file_observer.py\n" ] } ], "source": [ "%%writefile IUM_07/file_observer.py\n", "from sacred.observers import FileStorageObserver\n", "from sacred import Experiment\n", "\n", "ex = Experiment(\"file_observer\")\n", "\n", "ex.observers.append(FileStorageObserver('my_runs'))\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "@ex.capture\n", "def prepare_message(recipient, greeting):\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.automain\n", "def my_main(recipient, greeting):\n", " print(prepare_message()) ## Nie musimy przekazywać wartości" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO - file_observer - Running command 'my_main'\n", "INFO - file_observer - Started run with ID \"1\"\n", "Witaj Świecie!\n", "INFO - file_observer - Completed after 0:00:00\n" ] } ], "source": [ "!python3 IUM_07/file_observer.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Zobaczmy jakie informacje zostały zapisane" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 8\n", "drwxr-xr-x 2 pawel pawel 4096 Apr 17 07:51 1\n", "drwxr-xr-x 2 pawel pawel 4096 Apr 17 07:51 _sources\n" ] } ], "source": [ "!ls -l my_runs" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 16\n", "-rw-r--r-- 1 pawel pawel 77 Apr 17 07:51 config.json\n", "-rw-r--r-- 1 pawel pawel 159 Apr 17 07:51 cout.txt\n", "-rw-r--r-- 1 pawel pawel 2 Apr 17 07:51 metrics.json\n", "-rw-r--r-- 1 pawel pawel 1715 Apr 17 07:51 run.json\n" ] } ], "source": [ "!ls -l my_runs/1" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "{'greeting': 'Witaj', 'recipient': 'Świecie', 'seed': 805857632}" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# %load my_runs/1/config.json\n", "{\n", " \"greeting\": \"Witaj\",\n", " \"recipient\": \"\\u015awiecie\",\n", " \"seed\": 805857632\n", "}" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "INFO - file_observer - Running command 'my_main'\n", "INFO - file_observer - Started run with ID \"1\"\n", "Witaj Świecie!\n", "INFO - file_observer - Completed after 0:00:00\n" ] } ], "source": [ "!cat my_runs/1/cout.txt" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# %load my_runs/1/run.json\n", "{\n", " \"artifacts\": [],\n", " \"command\": \"my_main\",\n", " \"experiment\": {\n", " \"base_dir\": \"/home/tomek/repos/aitech/aitech-ium/IUM_07\",\n", " \"dependencies\": [\n", " \"sacred==0.8.2\"\n", " ],\n", " \"mainfile\": \"file_observer.py\",\n", " \"name\": \"file_observer\",\n", " \"repositories\": [\n", " {\n", " \"commit\": \"3055a4f1c2ef06ea1c29e3d41d862827cede7e2a\",\n", " \"dirty\": true,\n", " \"url\": \"git@git.wmi.amu.edu.pl:tzietkiewicz/aitech-ium.git\"\n", " }\n", " ],\n", " \"sources\": [\n", " [\n", " \"file_observer.py\",\n", " \"_sources/file_observer_cd34a0ef4a32fb0a966eaa01ea6371ad.py\"\n", " ]\n", " ]\n", " },\n", " \"heartbeat\": \"2022-04-25T07:51:37.853633\",\n", " \"host\": {\n", " \"ENV\": {},\n", " \"cpu\": \"Intel(R) Core(TM) i5-4200H CPU @ 2.80GHz\",\n", " \"hostname\": \"ASUSEK\",\n", " \"os\": [\n", " \"Linux\",\n", " \"Linux-4.4.0-19041-Microsoft-x86_64-with-Ubuntu-18.04-bionic\"\n", " ],\n", " \"python_version\": \"3.6.9\"\n", " },\n", " \"meta\": {\n", " \"command\": \"my_main\",\n", " \"options\": {\n", " \"--beat-interval\": null,\n", " \"--capture\": null,\n", " \"--comment\": null,\n", " \"--debug\": false,\n", " \"--enforce_clean\": false,\n", " \"--file_storage\": null,\n", " \"--force\": false,\n", " \"--help\": false,\n", " \"--loglevel\": null,\n", " \"--mongo_db\": null,\n", " \"--name\": null,\n", " \"--pdb\": false,\n", " \"--print-config\": false,\n", " \"--priority\": null,\n", " \"--queue\": false,\n", " \"--s3\": null,\n", " \"--sql\": null,\n", " \"--tiny_db\": null,\n", " \"--unobserved\": false,\n", " \"COMMAND\": null,\n", " \"UPDATE\": [],\n", " \"help\": false,\n", " \"with\": false\n", " }\n", " },\n", " \"resources\": [],\n", " \"result\": null,\n", " \"start_time\": \"2022-04-25T07:51:37.831461\",\n", " \"status\": \"COMPLETED\",\n", " \"stop_time\": \"2022-04-25T07:51:37.849334\"\n", "}" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 4\n", "-rw-r--r-- 1 pawel pawel 464 Apr 17 07:51 file_observer_cd34a0ef4a32fb0a966eaa01ea6371ad.py\n" ] } ], "source": [ "! ls -l my_runs/_sources\n", "## W run.json możemy znaleźć ścieżkę do pliku z źródłami: \"_sources/file_observer_bb0a5c4720d1072b641d23da080696b6.py\"\n" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "ename": "RuntimeError", "evalue": "Defining an experiment in interactive mode! The sourcecode cannot be stored and the experiment won't be reproducible. If you still want to run it pass interactive=True", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[33], line 5\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msacred\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mobservers\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m FileStorageObserver\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01msacred\u001b[39;00m \u001b[38;5;28;01mimport\u001b[39;00m Experiment\n\u001b[0;32m----> 5\u001b[0m ex \u001b[38;5;241m=\u001b[39m \u001b[43mExperiment\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mfile_observer\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 7\u001b[0m ex\u001b[38;5;241m.\u001b[39mobservers\u001b[38;5;241m.\u001b[39mappend(FileStorageObserver(\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mmy_runs\u001b[39m\u001b[38;5;124m'\u001b[39m))\n\u001b[1;32m 9\u001b[0m \u001b[38;5;129m@ex\u001b[39m\u001b[38;5;241m.\u001b[39mconfig\n\u001b[1;32m 10\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mmy_config\u001b[39m():\n", "File \u001b[0;32m~/ium/venv/lib/python3.10/site-packages/sacred/experiment.py:119\u001b[0m, in \u001b[0;36mExperiment.__init__\u001b[0;34m(self, name, ingredients, interactive, base_dir, additional_host_info, additional_cli_options, save_git_info)\u001b[0m\n\u001b[1;32m 117\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m name\u001b[38;5;241m.\u001b[39mendswith(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m.pyc\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[1;32m 118\u001b[0m name \u001b[38;5;241m=\u001b[39m name[:\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m4\u001b[39m]\n\u001b[0;32m--> 119\u001b[0m \u001b[38;5;28;43msuper\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[38;5;21;43m__init__\u001b[39;49m\u001b[43m(\u001b[49m\n\u001b[1;32m 120\u001b[0m \u001b[43m \u001b[49m\u001b[43mpath\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mname\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 121\u001b[0m \u001b[43m \u001b[49m\u001b[43mingredients\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mingredients\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 122\u001b[0m \u001b[43m \u001b[49m\u001b[43minteractive\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43minteractive\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 123\u001b[0m \u001b[43m \u001b[49m\u001b[43mbase_dir\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mbase_dir\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 124\u001b[0m \u001b[43m \u001b[49m\u001b[43m_caller_globals\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mcaller_globals\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 125\u001b[0m \u001b[43m \u001b[49m\u001b[43msave_git_info\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43msave_git_info\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 126\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 127\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mdefault_command \u001b[38;5;241m=\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m\n\u001b[1;32m 128\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mcommand(print_config, unobserved\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n", "File \u001b[0;32m~/ium/venv/lib/python3.10/site-packages/sacred/ingredient.py:79\u001b[0m, in \u001b[0;36mIngredient.__init__\u001b[0;34m(self, path, ingredients, interactive, _caller_globals, base_dir, save_git_info)\u001b[0m\n\u001b[1;32m 71\u001b[0m (\n\u001b[1;32m 72\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmainfile,\n\u001b[1;32m 73\u001b[0m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39msources,\n\u001b[0;32m (...)\u001b[0m\n\u001b[1;32m 76\u001b[0m _caller_globals, save_git_info, \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mbase_dir\n\u001b[1;32m 77\u001b[0m )\n\u001b[1;32m 78\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39mmainfile \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m interactive:\n\u001b[0;32m---> 79\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m(\n\u001b[1;32m 80\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mDefining an experiment in interactive mode! \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 81\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mThe sourcecode cannot be stored and the \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 82\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mexperiment won\u001b[39m\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mt be reproducible. If you still\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 83\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m want to run it pass interactive=True\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 84\u001b[0m )\n", "\u001b[0;31mRuntimeError\u001b[0m: Defining an experiment in interactive mode! The sourcecode cannot be stored and the experiment won't be reproducible. If you still want to run it pass interactive=True" ] } ], "source": [ "# %load my_runs/_sources/file_observer_cd34a0ef4a32fb0a966eaa01ea6371ad.py\n", "from sacred.observers import FileStorageObserver\n", "from sacred import Experiment\n", "\n", "ex = Experiment(\"file_observer\")\n", "\n", "ex.observers.append(FileStorageObserver('my_runs'))\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "@ex.capture\n", "def prepare_message(recipient, greeting):\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.automain\n", "def my_main(recipient, greeting):\n", " print(prepare_message()) ## Nie musimy przekazywać wartości\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Dodawanie własnych informacji\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO - file_observer - Running command 'my_main'\n", "INFO - file_observer - Started run with ID \"3\"\n", "INFO - file_observer - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Witaj Świecie!\n" ] } ], "source": [ "from sacred.observers import FileStorageObserver\n", "from sacred import Experiment\n", "from datetime import datetime\n", "\n", "ex = Experiment(\"file_observer\", interactive=True)\n", "\n", "ex.observers.append(FileStorageObserver('my_runs'))\n", "\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "### - Do \"przechwyconej\" przez @ex.capture funkcji prepare_message dodaliśmy specjalny parametr _run\n", "### - Daje on dostęp do obiektu wywołania eksperymentu w trakcie jego wywołania\n", "### - umożliwia m.in. zapisywanie dodatkowych informacji w słowniku info\n", "@ex.capture\n", "def prepare_message(recipient, greeting, _run):\n", " _run.info[\"prepare_message_ts\"] = str(datetime.now())\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.main\n", "def my_main(recipient, greeting):\n", " print(prepare_message()) ## Nie musimy przekazywać wartości\n", " \n", "r = ex.run()" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{\n", " \"prepare_message_ts\": \"2024-04-17 07:53:12.105121\"\n", "}" ] } ], "source": [ "cat my_runs/3/info.json" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Artefakty\n", "\n", "- Artefakty służą do zapisywania plików, np. z wytrenowanym modelem\n", "- Plik można zapisać jako artefakt korzystając z : [ex.add_artifact()](https://sacred.readthedocs.io/en/stable/apidoc.html?highlight=artifact#sacred.Experiment.add_artifact)\n", "```python\n", "ex.add_artifact(\"model.pb\")\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Otwieranie zasobów\n", "- Zmiana danych wejściowych wpłwa w oczywisty sposób na wyniki\n", "- Dlatego warto śledzić te zmiany za pomocą:\n", " - [ex.open_resource()](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.Experiment.open_resource)\n", " - [ex.add_resource()](https://sacred.readthedocs.io/en/stable/apidoc.html#sacred.Experiment.add_resource)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO - resources - Running command 'my_main'\n", "INFO - resources - Started run with ID \"6\"\n", "INFO - resources - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Id,SepalLengthCm,SepalWidthCm,PetalLengthCm,PetalWidthCm,Species\n", "\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sacred import Experiment\n", "from sacred.observers import FileStorageObserver\n", "\n", "\n", "ex = Experiment(\"resources\", interactive=True)\n", "ex.observers.append(FileStorageObserver('my_runs'))\n", "\n", "@ex.main\n", "def my_main():\n", " f = ex.open_resource(\"Iris.csv\", \"r\")\n", " print(f.readline())\n", " \n", "ex.run()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "total 8\r\n", "-rw-r--r-- 1 tomek tomek 5107 Apr 12 15:11 Iris_717820ef0af287ff346c5cabfb4c612c.csv\r\n" ] } ], "source": [ "!ls -l my_runs/_resources" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my_runs/6/run.json: \"name\": \"resources\",\r\n", "my_runs/6/run.json: \"resources\": [\r\n", "my_runs/6/run.json: \"my_runs/_resources/Iris_717820ef0af287ff346c5cabfb4c612c.csv\"\r\n" ] } ], "source": [ "!grep -e \"resources\" -R my_runs/6" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ " ## Obserwator mongo\n", " - Żeby skorzystać z obserwatora Mongo, musimy mieć dostęp do bazy Mongo.\n", " - Można ją łatwo \"postawić\" za pomocą [docker-compose ](https://docs.docker.com/compose/).\n", " - W tym celu wystarczy skopiować katalog [examples/docker](https://github.com/IDSIA/sacred/tree/master/examples/docker) z repozytorium SACRED i uruchomić `docker-compose up` - dostaniemy uruchomioną bazę MongoDB i dodatkowo [Omniboard ](https://vivekratnavel.github.io/omniboard/#/). Więcej informacji w [dokumentacji](https://sacred.readthedocs.io/en/stable/examples.html#docker-setup)\n", " - Baza taka została już postawiona na serwerze Jenkins, więc pracując na Jenkinsie można skorzystać z lokalnej bazy (`localhost:27017`)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Collecting pymongo\n", " Downloading pymongo-4.6.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (676 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m676.9/676.9 KB\u001b[0m \u001b[31m2.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n", "\u001b[?25hCollecting dnspython<3.0.0,>=1.16.0\n", " Downloading dnspython-2.6.1-py3-none-any.whl (307 kB)\n", "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m307.7/307.7 KB\u001b[0m \u001b[31m1.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n", "\u001b[?25hInstalling collected packages: dnspython, pymongo\n", "Successfully installed dnspython-2.6.1 pymongo-4.6.3\n" ] } ], "source": [ "!pip3 install pymongo" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO - sacred_scopes - Running command 'my_main'\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO - sacred_scopes - Started run with ID \"641\"\n", "INFO - sacred_scopes - Completed after 0:00:00\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Witaj Świecie!\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sacred.observers import MongoObserver\n", "from sacred import Experiment\n", "\n", "ex = Experiment(\"sacred_scopes\", interactive=True)\n", "ex.observers.append(MongoObserver(url='mongodb://admin:IUM_2021@tzietkiewicz.vm.wmi.amu.edu.pl:27017',\n", " db_name='sacred')) # Tutaj podajemy dane uwierzytelniające i nazwę bazy skonfigurowane w pliku .env podczas uruchamiania bazy.\n", "# W przypadku instancji na Jenkinsie url będzie wyglądał następująco: mongodb://admin:IUM_2021@tzietkiewicz.vm.wmi.amu.edu.pl:27017\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "@ex.capture\n", "def prepare_message(recipient, greeting):\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.main\n", "def my_main(recipient, greeting):\n", " print(prepare_message()) ## Nie musimy przekazywać wartości\n", " \n", "ex.run()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "- Informacje o eksperymencie można obejrzeć na Omniboard: http://127.0.0.1:9000/sacred\n", "- Instancja na Jenkinsie: http://tzietkiewicz.vm.wmi.amu.edu.pl:9000/sacred\n", "" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Metryki\n", "\n", "- W trakcie eksperymentu możemy śledzić [metryki](https://sacred.readthedocs.io/en/stable/collected_information.html#metrics-api), np. aktualny loss\n", "- W tym celu wystarczy:\n", " - dodać do funkcji udekorowanej `@ex.main` albo `@ex.capure` parametr `_run`\n", " - potem wywołać np. `_run.log_scalar()`" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO - sacred_scopes - Running command 'my_main'\n", "INFO - sacred_scopes - Started run with ID \"642\"\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Witaj Świecie!\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "INFO - sacred_scopes - Completed after 0:00:39\n" ] }, { "data": { "text/plain": [ "" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sacred.observers import MongoObserver\n", "from sacred import Experiment\n", "import random\n", "import time\n", "\n", "ex = Experiment(\"sacred_scopes\", interactive=True)\n", "ex.observers.append(MongoObserver(url='mongodb://admin:IUM_2021@tzietkiewicz.vm.wmi.amu.edu.pl:27017',\n", " db_name='sacred')) # Tutaj podajemy dane uwierzytelniające i nazwę bazy skonfigurowane w pliku .env podczas uruchamiania bazy.\n", "# W przypadku instancji na Jenkinsie url będzie wyglądał następująco: mongodb://admin:IUM_2021@tzietkiewicz.vm.wmi.amu.edu.pl:27017\n", "@ex.config\n", "def my_config():\n", " recipient = \"Świecie\"\n", " greeting = \"Witaj\"\n", "\n", "@ex.capture\n", "def prepare_message(recipient, greeting):\n", " return \"{0} {1}!\".format(greeting, recipient)\n", "\n", "@ex.main\n", "def my_main(recipient, greeting, _run):\n", " print(prepare_message()) ## Nie musimy przekazywać wartości \n", " counter = 0\n", " while counter < 20:\n", " counter+=1\n", " value = counter\n", " ms_to_wait = random.randint(5, 5000)\n", " time.sleep(ms_to_wait/1000)\n", " noise = 1.0 + 0.1 * (random.randint(0, 10) - 5)\n", " # This will add an entry for training.loss metric in every second iteration.\n", " # The resulting sequence of steps for training.loss will be 0, 2, 4, ...\n", " if counter % 2 == 0:\n", " _run.log_scalar(\"training.loss\", value * 1.5 * noise, counter)\n", " # Implicit step counter (0, 1, 2, 3, ...)\n", " # incremented with each call for training.accuracy:\n", " _run.log_scalar(\"training.accuracy\", value * 2 * noise)\n", "\n", "ex.run() " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Wartości metryk możemy na żywo śledzić w Omniboard\n", "" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Zadanie [15 pkt] (do 2024-06-12)\n", "1. \"Owiń\" wywołanie swojego eksperymentu za pomocą Sacred, w ten sposób, żeby zapisane zostały [10pkt]:\n", " - parametry, z którymi wywołany był trening\n", " - powstały plik z modelem (jako artefakt)\n", " - kod źródłowy użyty do przeprowadzenia treningu\n", " - pliki wejściowe otwarte za pomocą open_resource\n", " - metryki\n", " \n", "Jako nazwę eksperymentu użyj swojego numeru indeksu tak, żebyś mogła/mógł je odnaleźć w Omniboard\n", "\n", "2. Wykorzystaj 2 obserwatory [5pkt]: \n", " - MongoObserver, skorzytaj nastęþującego URL: `mongodb://admin:IUM_2021@tzietkiewicz.vm.wmi.amu.edu.pl:27017` (będziesz mógł przeglądać wyniki na http://tzietkiewicz.vm.wmi.amu.edu.pl:9000/sacred)\n", " - FileObserver - zapisane pliki zarchiwizuj na Jenkinsie jako jego artefakty\n" ] } ], "metadata": { "author": "Tomasz Ziętkiewicz", "celltoolbar": "Slideshow", "email": "tomasz.zietkiewicz@amu.edu.pl", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "lang": "pl", "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" }, "slideshow": { "slide_type": "slide" }, "subtitle": "7.Sacred[laboratoria]", "title": "Inżynieria uczenia maszynowego", "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": false, "sideBar": false, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": false, "toc_window_display": false }, "year": "2021" }, "nbformat": 4, "nbformat_minor": 4 }