aitech-ium/IUM_07.Sacred.ipynb

46 KiB
Raw Permalink Blame History

Logo 1

Inżynieria uczenia maszynowego

7. Sacred [laboratoria]

Tomasz Ziętkiewicz (2021)

Logo 2

Sacred

Every experiment is sacred
Every experiment is great
If an experiment is wasted
God gets quite irate

https://github.com/IDSIA/sacred / Sens życia według Monty Pythona

  • Przeprowadzanie eksperymentów (zmiana parametrów, trenowanie, ewaluacja) uczenia maszynowego jest kosztowne i czasochłonne
  • Dlatego warto przeprowadzać je w zorganizowany sposób
  • I tak, żebyśmy mogli powtórzyć / odtworzyć raz uzyskane wyniki

Sacred is a tool to help you:

  • configure
  • organize
  • log
  • reproduce experiments.

It is designed to do all the tedious overhead work that you need to do around your actual experiment in order to:

  • keep track of all the parameters of your experiment
  • easily run your experiment for different settings
  • save configurations for individual runs in a database
  • reproduce your results

https://github.com/IDSIA/sacred

  • ConfigScopes A very convenient way of the local variables in a function to define the parameters your experiment uses.
  • Config Injection You can access all parameters of your configuration from every function. They are automatically injected by name.
  • Command-line interface You get a powerful command-line interface for each experiment that you can use to change parameters and run different variants.
  • 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.
  • Automatic seeding helps controlling the randomness in your experiments, such that the results remain reproducible.

Instalacja

!pip install sacred
Collecting sacred
  Downloading sacred-0.8.2-py2.py3-none-any.whl (106 kB)
     |████████████████████████████████| 106 kB 1.7 MB/s eta 0:00:01
[?25hRequirement already satisfied: packaging>=18.0 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from sacred) (20.4)
Collecting jsonpickle<2.0,>=1.2
  Downloading jsonpickle-1.5.2-py2.py3-none-any.whl (37 kB)
Requirement already satisfied: GitPython in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from sacred) (3.1.14)
Collecting munch<3.0,>=2.0.2
  Downloading munch-2.5.0-py2.py3-none-any.whl (10 kB)
Collecting py-cpuinfo>=4.0
  Downloading py-cpuinfo-8.0.0.tar.gz (99 kB)
     |████████████████████████████████| 99 kB 2.7 MB/s eta 0:00:011
[?25hCollecting docopt<1.0,>=0.3
  Downloading docopt-0.6.2.tar.gz (25 kB)
Requirement already satisfied: wrapt<2.0,>=1.0 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from sacred) (1.11.2)
Requirement already satisfied: colorama>=0.4 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from sacred) (0.4.4)
Requirement already satisfied: pyparsing>=2.0.2 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from packaging>=18.0->sacred) (2.4.7)
Requirement already satisfied: six in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from packaging>=18.0->sacred) (1.15.0)
Requirement already satisfied: gitdb<5,>=4.0.1 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from GitPython->sacred) (4.0.5)
Requirement already satisfied: smmap<4,>=3.0.1 in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (from gitdb<5,>=4.0.1->GitPython->sacred) (3.0.5)
Building wheels for collected packages: py-cpuinfo, docopt
  Building wheel for py-cpuinfo (setup.py) ... [?25ldone
[?25h  Created wheel for py-cpuinfo: filename=py_cpuinfo-8.0.0-py3-none-any.whl size=22245 sha256=556a8ea1e899c40b6266eab7562141327aecacfb2cdb6509279a85c91bf729b2
  Stored in directory: /home/tomek/.cache/pip/wheels/57/cb/6d/bab2257f26c5be4a96ff65c3d2a7122c96529b73773ee37f36
  Building wheel for docopt (setup.py) ... [?25ldone
[?25h  Created wheel for docopt: filename=docopt-0.6.2-py2.py3-none-any.whl size=13704 sha256=a9cd4cc934499c413a39353a865132382f2f2b230f614d2a2a495b1ccc0b2dd4
  Stored in directory: /home/tomek/.cache/pip/wheels/56/ea/58/ead137b087d9e326852a851351d1debf4ada529b6ac0ec4e8c
Successfully built py-cpuinfo docopt
Installing collected packages: jsonpickle, munch, py-cpuinfo, docopt, sacred
Successfully installed docopt-0.6.2 jsonpickle-1.5.2 munch-2.5.0 py-cpuinfo-8.0.0 sacred-0.8.2

Funkcja main

# %load sacred_hello.py
from sacred import Experiment

ex = Experiment()

@ex.automain
def my_main():
    print('Witaj świecie!')
!python IUM_07/sacred_hello.py
WARNING - sacred_hello - No observers have been added to this run
INFO - sacred_hello - Running command 'my_main'
INFO - sacred_hello - Started
Witaj świecie!
INFO - sacred_hello - Completed after 0:00:00
Co się dzieje w kodzie powyżej?
  1. Tworzymy obiekt klasy Experiment
  2. Dekorujemy funkcję "ma_main" dekoratorem automain Dzięki temu:
    • otrzymujemy interfejs CLI, m.in. do kontrolowania poziomu logowania, przekazywania parametrów itp.
    • oznaczamy funkcję "my_main" jako główną funkcję, która będzie wywoływana podczas wykonywania eksperymentu
    • funkcja oznaczona jako główna musi być ostatnią funkcją zdefiniowaną w pliku!
Co nam daje interejs CLI:
!python IUM_07/sacred_hello.py -h
Usage:
  sacred_hello.py [(with UPDATE...)] [options]
  sacred_hello.py help [COMMAND]
  sacred_hello.py (-h | --help)
  sacred_hello.py COMMAND [(with UPDATE...)] [options]



Options:
  -b VALUE --beat-interval=VALUE  Set the heart-beat interval for this run.  Time
                                between two heartbeat events is measured in
                                seconds.
  -C VALUE --capture=VALUE      Control the way stdout and stderr are captured.
                                The argument value must be one of [no, sys, fd]
  -c VALUE --comment=VALUE      Add a comment to this run.
  -d --debug                    Set this run to debug mode.  Suppress warnings
                                about missing observers and don't filter the
                                stacktrace. Also enables usage with ipython
                                `--pdb`.
  -e --enforce_clean            Fail if any version control repository is
                                dirty.
  -F VALUE --file_storage=VALUE  Add a file-storage observer to the experiment.
                                The value of the arguement should be the base-
                                directory to write the runs to
  -f --force                    Disable warnings about suspicious changes for
                                this run.
  -h --help                     Print this help message and exit.
  -l VALUE --loglevel=VALUE     Set the LogLevel.  Loglevel either as 0 - 50 or
                                as string: DEBUG(10), INFO(20), WARNING(30),
                                ERROR(40), CRITICAL(50)
  -m VALUE --mongo_db=VALUE     Add a MongoDB Observer to the experiment.  The
                                argument value is the database specification.
                                Should be in the form:  `[host:port:]db_name[.c
                                ollection[:id]][!priority]`
  -n VALUE --name=VALUE         Set the name for this run.
  -D --pdb                      Automatically enter post-mortem debugging with
                                pdb on failure.
  -p --print-config             Always print the configuration first.
  -P VALUE --priority=VALUE     Sets the priority for a queued up experiment.
                                `--priority=NUMBER` The number represent the
                                priority for this run.
  -q --queue                    Only queue this run, do not start it.
  -S VALUE --s3=VALUE           Add a S3 File observer to the experiment.  The
                                argument value should be
                                `s3://<bucket>/path/to/exp`.
  -s VALUE --sql=VALUE          Add a SQL Observer to the experiment.  The
                                typical form is:
                                dialect://username:password@host:port/database
  -t VALUE --tiny_db=VALUE      Add a TinyDB Observer to the experiment.  The
                                argument is the path to be given to the
                                TinyDbObserver.
  -u --unobserved               Ignore all observers for this run.


Arguments:
  COMMAND   Name of command to run (see below for list of commands)
  UPDATE    Configuration assignments of the form foo.bar=17


Commands:
  print_config         Print the updated configuration and exit.
  print_dependencies   Print the detected source-files and dependencies.
  save_config          Store the updated configuration in a file.
  print_named_configs  Print the available named configs and exit.
  my_main              

Konfiguracje

  • Konfiguracje pozwalają nam sparametryzować wywołania eksperymentu.
  • Ułatwiają przekazywanie parametrów - zmienne z konfiguracji są wstrzykiwane do funkcji wywoływanych
  • Mogą być automatycznie zapisywane (dzięki czemu możemy śledzić jak zmieniały się parametry i jaki miały wpływ na wyniki)
  • Konfigurację można stworzyć w jeden z 3 sposobów:
    • używając config scopes (zasięg konfiguracji)
    • jako słownik
    • wczytując ją z pliku

Konfiguracje - config scopes

Jeśli oznaczymy jakąś funkcję dekoratorem config, to zostanie ona uruchoniona przed wywołaniem eksperymentu i wszystkie jej lokalne zmienne, które da sie zserializować jako json, zostaną dodane do konfiguracji. Potem ich wartości zostaną wstrzyknięte

from sacred import Experiment

exint = Experiment("sacred_scopes", interactive=True) #Jeśli wykonujemy interaktywnie (w konsoli Pythona albo w Jupyter):
# - musimy podać nazwę eksperymentu (domyślnie jako nazwa używana jest nazwa pliku źródłowego)
# - musimy dodać parametr "interactive=True"
# - zamiast "automain" używamy parametru "main"

@exint.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"
    message = "{0} {1}!".format(greeting, recipient)


@exint.main
def my_main(message):
    print(message)
exint.run()
WARNING - sacred_scopes - No observers have been added to this run
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started
INFO - sacred_scopes - Completed after 0:00:00
Witaj Świecie!
<sacred.run.Run at 0x7f423da33160>
Możemy podejrzeć wartości zmiennych w konfiguracji:
my_config()
{'recipient': 'Świecie', 'greeting': 'Witaj', 'message': 'Witaj Świecie!'}

Parametry możemy podejrzeć i modyfikować z poziomu CLI

  • wartości podane w CLI nadpiszą te podane w kodzie
# %load IUM_07/sacred_scopes.py
from sacred import Experiment

ex = Experiment()

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"
    message = "{0} {1}!".format(greeting, recipient)

@ex.automain
def my_main(message):
    print(message)
!python IUM_07/sacred_scopes.py with 'recipient=Przygodo'
WARNING - sacred_scopes - No observers have been added to this run
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started
Witaj Przygodo!
INFO - sacred_scopes - Completed after 0:00:00
!python IUM_07/sacred_scopes.py print_config
INFO - sacred_scopes - Running command 'print_config'
INFO - sacred_scopes - Started
Configuration (modified, added, typechanged, doc):
  greeting = 'Witaj'
  message = 'Witaj Świecie!'
  recipient = 'Świecie'
  seed = 29744255                    # the random seed for this experiment
INFO - sacred_scopes - Completed after 0:00:00
!python IUM_07/sacred_scopes.py print_config with 'recipient=Przygodo'
INFO - sacred_scopes - Running command 'print_config'
INFO - sacred_scopes - Started
Configuration (modified, added, typechanged, doc):
  greeting = 'Witaj'
  message = 'Witaj Przygodo!'
  recipient = 'Przygodo'
  seed = 215765170                   # the random seed for this experiment
INFO - sacred_scopes - Completed after 0:00:00

Wczytywanie konfiguracji z pliku

# %load IUM_07/config.json
{
    "recipient": "samotności",
    "greeting": "Żegnaj"
}
from sacred import Experiment

ex = Experiment("sacred_scopes", interactive=True) #Jeśli wykonujemy interaktywnie (w konsoli Pythona albo w Jupyter):
# - musimy podać nazwę eksperymentu (domyślnie jako nazwa używana jest nazwa pliku źródłowego)
# - musimy dodać parametr "interactive=True"
# - zamiast "automain" używamy parametru "main"

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

ex.add_config("IUM_07/config.json")


@ex.main
def my_main(recipient, greeting):
    print("{0} {1}!".format(greeting, recipient))
r = ex.run()
WARNING - sacred_scopes - No observers have been added to this run
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started
INFO - sacred_scopes - Completed after 0:00:00
Żegnaj samotności!
r.config
{'recipient': 'samotności', 'greeting': 'Żegnaj', 'seed': 529757761}

Możemy modyfikować części konfiguracji bezpośrednio przed wywołaniem

r = ex.run(config_updates={"recipient":"nudo"})
WARNING - sacred_scopes - No observers have been added to this run
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started
INFO - sacred_scopes - Completed after 0:00:00
Żegnaj nudo!

Wtrzykiwanie zależności

  • Oprócz funkcji głównej, wartości z konfiguracji są też wstrzykiwane do funkcji udekorowanych dekoratorem @ex.capture
  • Możemy skorzystać w nich ze specjalnych parametrów, np.:
    • _log - daje nam dostęp do obiektu logera (więcej: logowanie)
    • _run - daje dostęp do obiektu reprezentującego aktualne wywołanie eksperymentu (przykład później)
from sacred import Experiment

ex = Experiment("sacred_scopes", interactive=True)

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

@ex.capture
def prepare_message(recipient, greeting, _log):
    _log.info("Enterred prepare_message")
    return "{0} {1}!".format(greeting, recipient)

@ex.main
def my_main():
    print(prepare_message()) ## Nie musimy przekazywać wartości
    
ex.run()
WARNING - sacred_scopes - No observers have been added to this run
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started
INFO - prepare_message - Enterred prepare_message
INFO - sacred_scopes - Completed after 0:00:00
Witaj Świecie!
<sacred.run.Run at 0x7f423c40d820>

Obserwowanie eksperymentów

Sacred zapisuje szereg informacji na temat każdego eksperymentu:

  • czas wykonania
  • konfigurację
  • tekst zwrócony na stdout/stderr
  • błędy, jeśli wystąpiły
  • podstawowe informacje o środowisku (maszynie), na której przeprowadzono eksperyment
  • użyte pliki źródłowe
  • użyte zależności i ich wersje
  • pliki otwarte za pomocą ex.open_resource
  • pliki dodane za pomocą ex.add_artifact

Obserwowane infromacje mogą zostać zapisane za pomocą jednego z obserwatorów:

  • Mongo Observer - zapisuje dane w MongoDB
  • File Storage Observer - zapisuje dane lokalnie w pliku
  • TinyDB Observer - korzysta z lokalnej bazy zapisanej w pliku JSON
  • SQL Observer - przechowuje informacje w bazie SQL
  • S3 Observer - korzysta z AWS S3
  • gcs_observer - korzysta z Google Cloud Storage
  • Queue Observer - rodzaj lokalnego bufora nakładanego na jeden z powyższych
  • Slack Observer - używany do powiadomień wysyłanych na komunikator Slack
  • Telegram Observer - używany do powiadomień wysyłanych na komunikator Telegram

File storage observer

  • zapisuje informacje o eksperymencie w lokalnych plikach
  • 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
# %load IUM_07/file_observer.py
from sacred.observers import FileStorageObserver
from sacred import Experiment

ex = Experiment("file_observer")

ex.observers.append(FileStorageObserver('my_runs'))

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

@ex.capture
def prepare_message(recipient, greeting):
    return "{0} {1}!".format(greeting, recipient)

@ex.automain
def my_main(recipient, greeting):
    print(prepare_message()) ## Nie musimy przekazywać wartości
!python IUM_07/file_observer.py
INFO - file_observer - Running command 'my_main'
INFO - file_observer - Started run with ID "2"
Witaj Świecie!
INFO - file_observer - Completed after 0:00:00

Zobaczmy jakie informacje zostały zapisane

!ls -l my_runs
total 12
drwxrwxr-x 2 tomek tomek 4096 kwi 26 09:54 1
drwxrwxr-x 2 tomek tomek 4096 kwi 26 10:21 2
drwxrwxr-x 2 tomek tomek 4096 kwi 26 10:21 _sources
!ls -l my_runs/2
total 16
-rw-rw-r-- 1 tomek tomek   76 kwi 26 10:21 config.json
-rw-rw-r-- 1 tomek tomek  159 kwi 26 10:21 cout.txt
-rw-rw-r-- 1 tomek tomek    2 kwi 26 10:21 metrics.json
-rw-rw-r-- 1 tomek tomek 1686 kwi 26 10:21 run.json
# %load my_runs/2/config.json
{
  "greeting": "Witaj",
  "recipient": "\u015awiecie",
  "seed": 178660254
}
{'greeting': 'Witaj', 'recipient': 'Świecie', 'seed': 178660254}
!cat my_runs/2/cout.txt
INFO - file_observer - Running command 'my_main'
INFO - file_observer - Started run with ID "2"
Witaj Świecie!
INFO - file_observer - Completed after 0:00:00
# %load my_runs/2/run.json
{
  "artifacts": [],
  "command": "my_main",
  "experiment": {
    "base_dir": "/home/tomek/AITech/repo/aitech-ium-private/IUM_07",
    "dependencies": [
      "numpy==1.19.2",
      "sacred==0.8.2"
    ],
    "mainfile": "file_observer.py",
    "name": "file_observer",
    "repositories": [
      {
        "commit": "9a2064faaf4d209233ab0e20ad522638bb99b6f4",
        "dirty": true,
        "url": "git@git.wmi.amu.edu.pl:tzietkiewicz/aitech-ium-private.git"
      }
    ],
    "sources": [
      [
        "file_observer.py",
        "_sources/file_observer_bb0a5c4720d1072b641d23da080696b6.py"
      ]
    ]
  },
  "heartbeat": "2021-04-26T08:21:35.718761",
  "host": {
    "ENV": {},
    "cpu": "Intel(R) Core(TM) i5-4200H CPU @ 2.80GHz",
    "hostname": "tomek-asus",
    "os": [
      "Linux",
      "Linux-5.4.0-72-generic-x86_64-with-glibc2.10"
    ],
    "python_version": "3.8.5"
  },
  "meta": {
    "command": "my_main",
    "options": {
      "--beat-interval": null,
      "--capture": null,
      "--comment": null,
      "--debug": false,
      "--enforce_clean": false,
      "--file_storage": null,
      "--force": false,
      "--help": false,
      "--loglevel": null,
      "--mongo_db": null,
      "--name": null,
      "--pdb": false,
      "--print-config": false,
      "--priority": null,
      "--queue": false,
      "--s3": null,
      "--sql": null,
      "--tiny_db": null,
      "--unobserved": false,
      "COMMAND": null,
      "UPDATE": [],
      "help": false,
      "with": false
    }
  },
  "resources": [],
  "result": null,
  "start_time": "2021-04-26T08:21:35.714091",
  "status": "COMPLETED",
  "stop_time": "2021-04-26T08:21:35.717141"
}
! ls -l my_runs/_sources
## W run.json możemy znaleźć ścieżkę do pliku z źródłami:         "_sources/file_observer_bb0a5c4720d1072b641d23da080696b6.py"
total 4
-rw-rw-r-- 1 tomek tomek 463 kwi 26 10:21 file_observer_bb0a5c4720d1072b641d23da080696b6.py
## Źródła zostały zapisane
# %load my_runs/_sources/file_observer_bb0a5c4720d1072b641d23da080696b6.py
from sacred.observers import FileStorageObserver
from sacred import Experiment

ex = Experiment("file_observer")

ex.observers.append(FileStorageObserver('my_runs'))

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

@ex.capture
def prepare_message(recipient, greeting):
    return "{0} {1}!".format(greeting, recipient)

@ex.automain
def my_main(recipient, greeting):
    print(prepare_message()) ## Nie musimy przekazywać wartości

Dodawanie własnych informacji

from sacred.observers import FileStorageObserver
from sacred import Experiment
from datetime import datetime

ex = Experiment("file_observer", interactive=True)

ex.observers.append(FileStorageObserver('my_runs'))

@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

### - Do "przechwyconej" przez @ex.capture funkcji prepare_message dodaliśmy specjalny parametr _run
### - Daje on dostęp do obiektu wywołania eksperymentu w trakcie jego wywołania
### - umożliwia m.in. zapisywanie dodatkowych informacji w słowniku info
@ex.capture
def prepare_message(recipient, greeting, _run):
    _run.info["prepare_message_ts"] = str(datetime.now())
    return "{0} {1}!".format(greeting, recipient)

@ex.main
def my_main(recipient, greeting):
    print(prepare_message()) ## Nie musimy przekazywać wartości
    
r = ex.run()
INFO - file_observer - Running command 'my_main'
INFO - file_observer - Started run with ID "6"
INFO - file_observer - Completed after 0:00:00
Witaj Świecie!
cat my_runs/6/info.json
{
  "prepare_message_ts": "2021-04-26 10:39:59.268539"
}

Artefakty

  • Artefakty służą do zapisywania plików, np. z wytrenowanym modelem
  • Plik można zapisać jako artefakt korzystając z : ex.add_artifact()
    ex.add_artifact("model.pb")
    

Obserwator mongo

  • Żeby skorzystać z obserwatora Mongo, musimy mieć dostęp do bazy Mongo.
  • Można ją łatwo "postawić" za pomocą docker-compose .
  • W tym celu wystarczy skopiować katalog examples/docker z repozytorium SACRED i uruchomić docker-compose up - dostaniemy uruchomioną bazę MongoDB i dodatkowo Omniboard . Więcej informacji w dokumentacji
  • Baza taka została już postawiona na serwerze Jenkins, więc pracując na Jenkinsie można skorzystać z lokalnej bazy (localhost:27017)
!pip install pymongo
Requirement already satisfied: pymongo in /media/tomek/Linux_data/home/tomek/anaconda3/lib/python3.8/site-packages (3.11.3)
from sacred.observers import MongoObserver
from sacred import Experiment

ex = Experiment("sacred_scopes", interactive=True)
ex.observers.append(MongoObserver(url='mongodb://mongo_user:mongo_password@localhost:27017',
                                  db_name='sacred'))  # Tutaj podajemy dane uwierzytelniające i nazwę bazy skonfigurowane w pliku .env podczas uruchamiania bazy.
# W przypadku instancji na Jenkinsie url będzie wyglądał następująco: mongodb://mongo_user:mongo_password_IUM_2021@localhost:27017
@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

@ex.capture
def prepare_message(recipient, greeting):
    return "{0} {1}!".format(greeting, recipient)

@ex.main
def my_main(recipient, greeting):
    print(prepare_message()) ## Nie musimy przekazywać wartości
    
ex.run()
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started run with ID "2"
INFO - sacred_scopes - Completed after 0:00:00
Witaj Świecie!
<sacred.run.Run at 0x7f423c3667c0>

Metryki

  • W trakcie eksperymentu możemy śledzić metryki, np. aktualny loss
  • W tym celu wystarczy:
    • dodać do funkcji udekorowanej @ex.main albo @ex.capure parametr _run
    • potem wywołać np. _run.log_scalar()
from sacred.observers import MongoObserver
from sacred import Experiment
import random
import time

ex = Experiment("sacred_scopes", interactive=True)
ex.observers.append(MongoObserver(url='mongodb://mongo_user:mongo_password@localhost:27017',
                                  db_name='sacred'))  # Tutaj podajemy dane uwierzytelniające i nazwę bazy skonfigurowane w pliku .env podczas uruchamiania bazy.
# W przypadku instancji na Jenkinsie url będzie wyglądał następująco: mongodb://mongo_user:mongo_password_IUM_2021@localhost:27017
@ex.config
def my_config():
    recipient = "Świecie"
    greeting = "Witaj"

@ex.capture
def prepare_message(recipient, greeting):
    return "{0} {1}!".format(greeting, recipient)

@ex.main
def my_main(recipient, greeting, _run):
    print(prepare_message()) ## Nie musimy przekazywać wartości  
    counter = 0
    while counter < 20:
        counter+=1
        value = counter
        ms_to_wait = random.randint(5, 5000)
        time.sleep(ms_to_wait/1000)
        noise = 1.0 + 0.1 * (random.randint(0, 10) - 5)
        # This will add an entry for training.loss metric in every second iteration.
        # The resulting sequence of steps for training.loss will be 0, 2, 4, ...
        if counter % 2 == 0:
           _run.log_scalar("training.loss", value * 1.5 * noise, counter)
        # Implicit step counter (0, 1, 2, 3, ...)
        # incremented with each call for training.accuracy:
        _run.log_scalar("training.accuracy", value * 2 * noise)

ex.run()    
INFO - sacred_scopes - Running command 'my_main'
INFO - sacred_scopes - Started run with ID "9"
Witaj Świecie!
INFO - sacred_scopes - Completed after 0:00:50
<sacred.run.Run at 0x7f423c2de550>

Wartości metryk możemy na żywo śledzić w Omniboard

Zadanie [15 pkt] (do 9 V 2021)

  1. "Owiń" wywołanie swojego eksperymentu za pomocą Sacred, w ten sposób, żeby zapisane zostały [10pkt]:
  • parametry, z którymi wywołany był trening
  • powstały plik z modelem (jako artefakt)
  • kod źródłowy użyty do przeprowadzenia treningu
  • wyniki (np. ostateczny loss albo wyniki ewaluacji)
  1. Wykorzystaj 2 obserwatory [5pkt]:
  • MongoObserver, skorzytaj nastęþującego URL: mongodb://mongo_user:mongo_password_IUM_2021@localhost:27017 (będziesz mógł przeglądać wyniki na http://tzietkiewicz.vm.wmi.amu.edu.pl:9000/sacred)
  • FileObserver - zapisane pliki zarchiwizuj na Jenkinsie jako jego artefakty