Commit 8e4304ec by Szeberényi Imre

Merge branch 'script' into 'master'

Slurm jupyter windows/linux

See merge request !1
parents 0a2dc08b 4791fc09
# Jupyter Notebook Bevezető
A Jupyter Notebook interaktív felületet nyújt a kódoláshoz. A _JOKER_ szerveren jelenleg csak a **Python 3**-as kernel érhető el, de nagyon sok más nyelvhez is használható.
Egy-egy ilyen notebook tartalmazhat futtatandó kódot és annak kimenetét, valamint a kód leírását, megértését megkönnyítő markdown kiterjesztést. A notebook fájl html/pdf/latex... dokumentumba is kimenthető, így pl. egy beadandónál, nagyon könnyen felhasználható. Ez a doksi is ott készült.
A _JOKER_ szerver érdekessége, hogy a Jupyter szervert nem a helyi gépen futtatjuk, hanem a _JOKER_ -en, így elérjük a _JOKER_ által biztosított erőforrásokat, mint pl. GPU számítási kapacitást is, bárhonnan.
## Kezelés
A kezelést nagyon nem is ragoznám, a Help menü alatt megtekinthetőek a fontosabb gyorsbillentyűk, illetve egy kezdetleges tutorial-t is indíthatunk.
## Hello Jupyter Notebook
Használatkor a hagyományos python-os interpreter mintájára működik, azaz tetszőlegesen tudunk a **Code** szekciókba python-os vagy más kódot elhelyezni és azt lefuttatni, pl.:
```python
print('Hello Jupyter Notebook')
```
```python
a = 10
```
```python
print('a: ', a)
```
## Magic
Van lehetőségünk további beépített parancsok használatára, melyeket most nem részletezek, néhány példát szeretnék mutatni:
```python
lsmagic
```
```python
%%HTML
<a href="https://www.vik.bme.hu/">BME VIK Honlap</a>
```
```latex
%%latex
$\sum_{n=1}^{\infty} \frac{1}{2^{n}} = 1$
```
## Mandelbrot halmaz
Komplex számokból álló sík, melyre:
$$x_1 = 0$$
$$x_{n+1}=x_n^2+c$$
Forrás: [link](https://levelup.gitconnected.com/mandelbrot-set-with-python-983e9fc47f56)
```python
# Kiszámolós függvény:
import matplotlib.pyplot as plt
import numpy as np
def get_iter(c:complex, thresh:int =4, max_steps:int =25) -> int:
z=c
i=1
while i<max_steps and (z*z.conjugate()).real<thresh:
z=z*z +c
i+=1
return i
```
```python
# Kirajzoló függvény
def plotter(n, thresh, max_steps=25):
mx = 2.48 / (n-1)
my = 2.26 / (n-1)
mapper = lambda x,y: (mx*x - 2, my*y - 1.13)
img=np.full((n,n), 255)
for x in range(n):
for y in range(n):
it = get_iter(complex(*mapper(x,y)), thresh=thresh, max_steps=max_steps)
img[y][x] = 255 - it
return img
```
```python
n=3000
img = plotter(n, thresh=4, max_steps=50)
plt.imshow(img, cmap="plasma")
plt.axis("off")
plt.show()
```
## GPU támogatott Mandelbrot
Helyezzük el a @jit annotációt a számítási függvényekhez. Meg kell jegyezni, hogy az annotáció a pythonos kódot natívra is cseréli, nemcsak a GPU-t használja.
```python
# Kiszámolós függvény:
import matplotlib.pyplot as plt
import numpy as np
from numba import jit
@jit
def get_iter(c:complex, thresh:int =4, max_steps:int =25) -> int:
z=c
i=1
while i<max_steps and (z*z.conjugate()).real<thresh:
z=z*z +c
i+=1
return i
```
```python
# Kirajzoló függvény
@jit
def plotter(n, thresh, max_steps=25):
mx = 2.48 / (n-1)
my = 2.26 / (n-1)
mapper = lambda x,y: (mx*x - 2, my*y - 1.13)
img=np.full((n,n), 255)
for x in range(n):
for y in range(n):
it = get_iter(complex(*mapper(x,y)), thresh=thresh, max_steps=max_steps)
img[y][x] = 255 - it
return img
```
```python
n=3000
img = plotter(n, thresh=4, max_steps=50)
plt.imshow(img, cmap="plasma")
plt.axis("off")
plt.show()
# sokkal gyorsabban kapunk eredményt :)
```
```python
from numba import jit
import numpy as np
from timeit import default_timer as timer
def func(a):
for i in range(10000000):
a[i]+= 1
@jit
def func2(a):
for i in range(10000000):
a[i]+= 1
if __name__=="__main__":
n = 10000000
a = np.ones(n, dtype = np.float64)
b = np.ones(n, dtype = np.float32)
start = timer()
func(a)
print("without GPU:", timer()-start)
start = timer()
func2(a)
print("with GPU:", timer()-start)
```
## PyTorch
[link](https://pytorch.org/tutorials/beginner/basics/quickstart_tutorial.html)
```python
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt
```
```python
# Download training data from open datasets.
training_data = datasets.FashionMNIST(
root="data",
train=True,
download=True,
transform=ToTensor(),
)
# Download test data from open datasets.
test_data = datasets.FashionMNIST(
root="data",
train=False,
download=True,
transform=ToTensor(),
)
```
```python
batch_size = 64
# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
for X, y in test_dataloader:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break
```
Shape of X [N, C, H, W]: torch.Size([64, 1, 28, 28])
Shape of y: torch.Size([64]) torch.int64
_HF befejezni_
## Osztályozás TensorFlow-val
Telepítsük a TensorFlow-t, egyszer majd talán központilag le lesz töltve, így nem kell magunknak leszedni:
```
module load anaconda3
conda create -n tf-gpu tensorflow-gpu
conda activate tf-gpu
```
Nézzük meg ezt a csomagot, és kövessük végig a leckét a JOKER szerveren: [image classification](https://www.tensorflow.org/tutorials/images/classification)
```python
#importok behúzása
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
```
......@@ -6,7 +6,7 @@ diff -Naur '--exclude=*cache*' anaconda3/lib/python3.8/site-packages/slurm_jupyt
"""
- cmd = 'ssh {user}@{frontend} cat - > {tmp_dir}/{tmp_script} ; mkdir -p {tmp_dir} ; sbatch {tmp_dir}/{tmp_script} '.format(**spec)
+ cmd = 'ssh {user}@{frontend} mkdir -p {tmp_dir} ; cat - > {tmp_dir}/{tmp_script} ; sbatch {tmp_dir}/{tmp_script} '.format(**spec)
+ cmd = 'ssh {user}@{frontend} module load anaconda3; mkdir -p {tmp_dir} ; cat - > {tmp_dir}/{tmp_script} ; sbatch {tmp_dir}/{tmp_script} '.format(**spec)
if verbose: print("script ssh transfer:", cmd, sep='\n')
......
from subprocess import Popen, PIPE
import requests
import socket
import re
import platform
import requests.packages.urllib3.util.connection as urllib3_cn
def allowed_gai_family():
family = socket.AF_INET # force IPv4
return family
urllib3_cn.allowed_gai_family = allowed_gai_family
# támogatott verziók
ANACONDA = ['4.10.3']
SLURM_JUPYTER = ['2.0.22']
codec = 'utf-8'
FILES = {
'linux_init' : ['https://git.ik.bme.hu/joker/joker/raw/script/upgrade/files/__init__.py', '/lib/python3.8/site-packages/slurm_jupyter/__init__.py'],
'win_init' : ['https://git.ik.bme.hu/joker/joker/raw/script/upgrade/files/win/__init__.py', '\Lib\site-packages\slurm_jupyter\__init__.py']
}
def anaconda():
with Popen('conda --version', stdout=PIPE, stderr=PIPE, shell=True) as proc:
(outdata, errdata) = proc.communicate()
if errdata.decode(codec) != '':
return False
ver = outdata.decode(codec).split()
print(f'\tAnaconda jelenlegi verzió: {ver[1]}')
print(f'\tAnaconda ajánlott verziók: {ANACONDA}')
return ver[1] in ANACONDA
def slurm():
with Popen('conda list', stdout=PIPE, stderr=PIPE, shell=True) as proc:
(outdata, errdata) = proc.communicate()
if errdata.decode(codec) != '':
return False, ''
packages = outdata.decode(codec)
res = re.search(r'slurm-jupyter \s*([\d.]+)', packages)
ver = res.group(1)
print(f'\tslurm-jupyter jelenlegi verzió: {ver}')
print(f'\tslurm-jupyter ajánlott verziók: {SLURM_JUPYTER}')
return ver in SLURM_JUPYTER
def path():
with Popen('conda info', stdout=PIPE, stderr=PIPE, shell=True) as proc:
(outdata, errdata) = proc.communicate()
if errdata.decode(codec) != '':
return False, ''
path = outdata.decode(codec)
res = re.search(r'base environment : (\S+)', path)
path = res.group(1)
return True, path
def getFile(dir, name):
print(f'\tLetöltés: {FILES[name][0]}')
print(f'\tA fájl ide kerül: {dir}{FILES[name][1]}')
headers = {"User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"}
req = requests.get(FILES[name][0], stream=True, headers=headers)
print('\t', end =" ")
with open(f'{dir}{FILES[name][1]}', 'wb') as f:
for chunk in req.iter_content(chunk_size=256):
if chunk:
f.write(chunk)
print('.', end ="")
print('\n\tOK\n')
def files(dir):
print('Fájlok letöltése')
if platform.system() == 'Linux':
getFile(dir, 'linux_init')
elif platform.system() == 'Windows':
getFile(dir, 'win_init')
def upgrade():
print('Anaconda könyvtár keresése')
ok, dir = path()
if ok:
print(f'\tKiolvasott útvonal: {dir}')
else:
print('\tNem tudtam útvonalat kiolvasni, adja meg: ')
dir = input()
print('Megpróbálom ezzel ...')
files(dir)
if __name__ == '__main__':
if platform.system() == 'Windows':
codec = 'latin-1'
print('Rendszer: ' + platform.platform())
print("Anaconda vizsgálata ...")
if anaconda() and slurm():
print('OK\n')
upgrade()
else:
print('Valami baj lehet! Folytatja (i/n) ?')
ok = input()
if ok == 'i' or ok == 'I':
upgrade()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment