Skip to content
README.md 8.19 KiB
Newer Older
Tobias Strauß's avatar
Tobias Strauß committed
# Uni Rostock PyTorch Framework

The `uros_pf` framework intents to reduce the setup time for new machine 
learning projects based on pytorch. 
It unifies standard procedures, such as configuring, input/output
procedures, training, logging etc., that are used in all projects.

## Basic principles

- Files in the `uros_pf` package are of general interest. They must
not be adapted to a certain project.
- Project specific source code goes into the `scenario` folder.
- Data / configuration files / model checkpoints etc. are stored in a 
separate workdir folder.
- To implement a new scenario at least 3 files have to be coded: the 
`input_processor` (preparing the input and targets) the `model` 
 (connecting the trainer, optimizer and model) and the `module` (containing 
the neural network or the ML-method)
Tobias Strauß's avatar
Tobias Strauß committed
- The input processor, the model and all hyperparameter shall be configured
by the config file (a `yaml`-file). It is usually stored in the workdir and 
passed to the trainer by `-cn config_name` (`config_name` without extension `.yaml`).

Tobias Strauß's avatar
Tobias Strauß committed
## Sample project

A working configuration file (named `ag_linear_config.yaml`) is
```yaml
hydra:
    run:
        dir: ${trainer.model_path}
Tobias Strauß's avatar
Tobias Strauß committed
builder:
    input: "scenario.ag_news_corpus.ag_ip.AGInputProcessor"
    model: "scenario.ag_news_corpus.ag_simple_model.SimpleModel"
trainer:
    epochs: 20
    model_path: models/${now:%Y-%m-%d}/${now:%H-%M-%S}
Tobias Strauß's avatar
Tobias Strauß committed
input:
    feature_size: 1000
    train_file: "data/ag_news_corpus/train.csv"
    val_file: "data/ag_news_corpus/test.csv"
    batch_size: 10
    samples_per_epoch: 12000
model:
    num_of_classes: 4
    loss_fn: "torch.nn.MSELoss"
    metric_fns: "uros_pf.metrics.accuracy.Accuracy"
    module_cls: "scenario.ag_news_corpus.ag_least_square_module.AGLeastSquareModule"
    optimizer: "torch.optim.SGD"
    lr: 0.01
    module:
        feature_size: ${input.feature_size}
        num_of_classes: ${model.num_of_classes}

```
The structure of the workdir is: 
```commandline
├── data
│   ├── ag_news_corpus
│   │   ├── test.csv
│   │   ├── train.csv
├── config
│   ├── ag_linear_config.yaml
```
whereas the data is taken from 
[mhjabreel's github account](https://github.com/mhjabreel/CharCnn_Keras/tree/master/data/ag_news_csv).

To run the example project just execute 
`python3 path/to/src/uros_pf/trainer/trainer.py -cn ag_linear_config`
from the workdir.

## Install

### Ubuntu / Debian
Open a terminal and execute the following command lines while substituting 
`path/2/virtual/environment` and `path/to/project/dir` with your own folders.

```commandline
sudo apt-get update 
sudo apt install python3-venv python3-pip
ENV_HOME=path/2/virtual/environment
python3 -m venv $ENV_HOME 
source $ENV_HOME/bin/activate
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install tensorboard transformers[torch] evaluate datasets scikit-learn tokenizers tqdm
pip install hydra-core --upgrade
```
To install the project framework and the Pycharm environment download and install PyCharm from 
https://www.jetbrains.com/de-de/pycharm/download/other.html and run:
```
cd path/to/project/dir
git clone https://citlab0.math.uni-rostock.de/gitlab/shared/uros_pf
```
(tested with Ubuntu 23.04)

### Windows
#### Voraussetzungen
- Betriebssystem: Windows 7, 8, 10 oder 11 (64bit)
- Prozessor: x86-Prozessorarchitektur (keine ARM-Unterstützung)
- Festplatte: 5GB freier Speicherplatz
#### Generelles
Im Workshop wird Python (3.11) als Programmiersprache und werden zahlreiche in Python geschriebene Module verwendet, die über den Python-eigenen Paketmanager **pip** bezogen werden. Um all das spezifisch für die Zwecke des Workshops auf deinem System zu installieren, ohne in Konflikt mit womöglich schon vorhandenen oder später einmal zu installierenden Python- und Modul-Versionen zu kommen, verwenden wir auf Windows-Systemen **Anaconda** (genauer: die minimierte Variante **Miniconda**). Mit dieser Software ist es möglich, voneinander unabhängige Python-Installationen in sogenannten **virtuellen Umgebungen** zu betreiben. Solltest du also im Nachgang zu diesem Workshop eigene Projekte mit anderen Python-Versionen, -Modulen oder -Modulversionen anlegen wollen, ist dies mit Anaconda problemlos möglich.

Als Code-Editor verwenden wir **PyCharm**, das verschiedene Hilfsmittel für die Entwicklung von Python-Programmen bietet.
#### Schritt für Schritt
##### Virtuelle Umgebung
1. Installiere [Miniconda](https://docs.conda.io/en/latest/miniconda.html#windows-installers): Benutze dafür den Installer für Windows 64bit-Systeme. Wähle im Installationsprozess die vorgeschlagenen Standard-Einstellungen. Sollte nach der Installation keine Verknüpfung mit dem Anaconda-Prompt (der Anaconda-eigenen Eingabeaufforderung) auf dem Desktop angelegt worden sein, lege selbst eine an: Erzeuge eine neue Verknüpfung mit dem Ziel `cmd /c start "Anaconda Prompt" "C:\path\to\Miniconda3\Scripts\activate"`, wobei `C:\path\to\` durch den korrekten Pfad zur Miniconda-Installation ersetzt werden muss.
2. Erweitere die Quellen, auf die Miniconda zugreifen kann, um Software in virtuelle Umgebungen zu installieren: Anaconda hat standardmäßig häufig nur Zugriff auf ältere Versionen von Softwarepaketen. Um den Umfang zu erweitern, fügen wir mit **Conda-Forge** eine weitere, von der Community gepflegte Quelle hinzu. Öffne dazu den Anaconda-Prompt und tippe ein: `conda config --add channels conda-forge`. Conda-Forge sollte nun in der Liste der Channels zum Bezug von Softwarepaketen eingetragen sein: `conda config --show channels`.
3. Erzeuge eine neue virtuelle Umgebung: Im Anaconda-Prompt sollte vor dem Cursor das Präfix `(base)` in der Zeile zu sehen sein, was bedeutet, dass du dich aktuell in der Basis-Umgebung von Anaconda befindest. Zum Erzeugen der neuen Umgebung, gebe ein: `conda create -n llm_workshop python=3.11 git`. Du kannst `llm_workshop` mit einem Namen deiner Wahl ersetzen.
4. Aktiviere die neue virtuelle Umgebung: `conda activate llm_workshop`. Solltest du einmal den Namen der Umgebung vergessen haben oder eine Übersicht über alle angelegte virtuelle Umgebungen sehen wollen: `conda env list`.
5. Aktualisiere die mit Python installierten Pakete *pip* und *setuptools*: `python -m pip install -U pip && pip install -U setuptools`.
6. Installiere die für den Workshop benötigten Python-Module: `pip install torch torchvision torchaudio transformers[torch] tensorboard evaluate datasets scikit-learn notebook hydra-core --upgrade`.
##### Workshop-Ordner und Repository
7. Lege auf deinem System einen Workshop-Ordner an. Wechsle im Anaconda-Prompt in diesen Workshop-Ordner.
8. Klone das Workshop-Repository in den Workshop-Ordner: `git clone https://citlab0.math.uni-rostock.de/gitlab/shared/uros_pf.git`.
9. Lege im Workshop-Ordner den Ordner `workdir` an, so dass jetzt insgesamt zwei Ordner sich im Workshop-Ordner befinden sollten: `workdir` und `uros_pf`. In `workdir` werden wir Daten, Konfigurationen und Modelle speichern.
##### PyCharm
10. Installiere [PyCharm](https://www.jetbrains.com/de-de/pycharm/download/other.html) (Community-Version 2023.2.1 für Windows).
11. Starte PyCharm und öffne den Repository-Ordner `uros_pf` im Workshop-Ordner: Klicke auf das Hauptmenü-Symbol oben links, klicke auf `Open` und wähle den Repository-Ordner aus. Beantworte die folgende Sicherheitsabfrage mit `Trust Project`.
12. Aktiviere deine virtuelle Umgebung in PyCharm: PyCharm kann nun die bereits von uns in Punkt 3 erzeugte virtuelle Umgebung als Arbeitsumgebung und damit auch den darin enthaltenen Python 3.11-Interpreter nutzen. Klicke dafür rechts unten auf die Auswahl des Python Interpreters. Sollte hier deine Miniconda-Umgebung noch nicht zur Auswahl stehen, wähle `Add New Interpreter` und anschließend `Add Local Interpreter`. In der nun geöffneten Anzeige `Add Python Interpreter` wähle als Typ links `Conda Environment`. Gebe anschließend rechts den Pfad zur `conda.exe` deiner Miniconda-Installation ein: `C:\path\to\Miniconda3\Scripts\conda.exe`. Aktiviere anschließend `Use existing environment` und wähle im Dropdown-Menü deine virtuelle Umgebung aus, die nun im Dropdown-Menü zu finden sein sollte. Bestätigte mit `OK`. Nun kann PyCharm die Python-Module nutzen, die du in Punkt 6 in die virtuelle Umgebung installiert hast.