Skip to content

Commit 65710b9

Browse files
ci/test: use bare ipython instead of nbval (#324)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent d047ff8 commit 65710b9

File tree

11 files changed

+65
-36
lines changed

11 files changed

+65
-36
lines changed

.actions/assistant.py

+38-13
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def get_running_cuda_version() -> str:
113113
return ""
114114

115115

116-
def get_running_torch_version():
116+
def get_running_torch_version() -> str:
117117
"""Extract the version of actual PyTorch for this runtime."""
118118
try:
119119
import torch
@@ -322,7 +322,13 @@ def bash_render(folder: str, output_file: str = PATH_SCRIPT_RENDER) -> Optional[
322322
# dry run does not execute the notebooks just takes them as they are
323323
cmd.append(f"cp {ipynb_file} {pub_ipynb}")
324324
# copy and add meta config
325-
cmd += [f"cp {meta_file} {pub_meta}", f"cat {pub_meta}", f"git add {pub_meta}"]
325+
cmd += [
326+
f"cp {meta_file} {pub_meta}",
327+
'echo "#====== START OF YAML FILE ======#"',
328+
f"cat {pub_meta}",
329+
'echo "#======= END OF YAML FILE =======#"',
330+
f"git add {pub_meta}",
331+
]
326332
else:
327333
pip_req, pip_args = AssistantCLI._parse_requirements(folder)
328334
cmd += [f"pip install {pip_req} --quiet {pip_args}", "pip list"]
@@ -335,7 +341,13 @@ def bash_render(folder: str, output_file: str = PATH_SCRIPT_RENDER) -> Optional[
335341
# Export the actual packages used in runtime
336342
cmd.append(f"meta_file=$(python .actions/assistant.py update-env-details {folder})")
337343
# copy and add to version the enriched meta config
338-
cmd += ["echo $meta_file", "cat $meta_file", "git add $meta_file"]
344+
cmd += [
345+
"echo $meta_file",
346+
'echo "#====== START OF YAML FILE ======#"',
347+
"cat $meta_file",
348+
'echo "#======= END OF YAML FILE =======#"',
349+
"git add $meta_file",
350+
]
339351
# if thumb image is linked to the notebook, copy and version it too
340352
if thumb_file:
341353
cmd += [f"cp {thumb_file} {pub_thumb}", f"git add {pub_thumb}"]
@@ -347,7 +359,7 @@ def bash_render(folder: str, output_file: str = PATH_SCRIPT_RENDER) -> Optional[
347359
fopen.write(os.linesep.join(cmd))
348360

349361
@staticmethod
350-
def bash_test(folder: str, output_file: str = PATH_SCRIPT_TEST) -> Optional[str]:
362+
def bash_test(folder: str, output_file: str = PATH_SCRIPT_TEST, virtualenv: bool = False) -> Optional[str]:
351363
"""Prepare bash script for running tests of a particular notebook.
352364
353365
Args:
@@ -364,11 +376,12 @@ def bash_test(folder: str, output_file: str = PATH_SCRIPT_TEST) -> Optional[str]
364376

365377
# prepare isolated environment with inheriting the global packages
366378
path_venv = os.path.join(folder, "venv")
367-
cmd += [
368-
f"python -m virtualenv --system-site-packages {path_venv}",
369-
f"source {os.path.join(path_venv, 'bin', 'activate')}",
370-
"pip --version",
371-
]
379+
if virtualenv:
380+
cmd += [
381+
f"python -m virtualenv --system-site-packages {path_venv}",
382+
f"source {os.path.join(path_venv, 'bin', 'activate')}",
383+
"pip --version",
384+
]
372385

373386
cmd.append(f"# available: {AssistantCLI.DEVICE_ACCELERATOR}")
374387
if AssistantCLI._valid_accelerator(folder):
@@ -378,21 +391,30 @@ def bash_test(folder: str, output_file: str = PATH_SCRIPT_TEST) -> Optional[str]
378391
# Export the actual packages used in runtime
379392
cmd.append(f"meta_file=$(python .actions/assistant.py update-env-details {folder} --base_path .)")
380393
# show created meta config
381-
cmd += ["echo $meta_file", "cat $meta_file"]
382-
cmd.append(f"python -m pytest {ipynb_file} -v --nbval --nbval-cell-timeout=300")
394+
cmd += [
395+
"echo $meta_file",
396+
'echo "#====== START OF YAML FILE ======#"',
397+
"cat $meta_file",
398+
'echo "#======= END OF YAML FILE =======#"',
399+
]
400+
# use standard jupyter's executable via CMD
401+
cmd.append(f"jupyter execute {ipynb_file} --inplace")
383402
else:
384403
pub_ipynb = os.path.join(DIR_NOTEBOOKS, f"{folder}.ipynb")
385404
pub_meta = pub_ipynb.replace(".ipynb", ".yaml")
386405
# copy and add meta config
387406
cmd += [
388407
f"mkdir -p {os.path.dirname(pub_meta)}",
389408
f"cp {meta_file} {pub_meta}",
409+
'echo "#====== START OF YAML FILE ======#"',
390410
f"cat {pub_meta}",
411+
'echo "#======= END OF YAML FILE =======#"',
391412
f"git add {pub_meta}",
392413
]
393414
warn("Invalid notebook's accelerator for this device. So no tests will be run!!!", RuntimeWarning)
394415
# deactivate and clean local environment
395-
cmd += ["deactivate", f"rm -rf {os.path.join(folder, 'venv')}"]
416+
if virtualenv:
417+
cmd += ["deactivate", f"rm -rf {os.path.join(folder, 'venv')}"]
396418
if not output_file:
397419
return os.linesep.join(cmd)
398420
with open(output_file, "w") as fopen:
@@ -707,7 +729,10 @@ def update_env_details(folder: str, base_path: str = DIR_NOTEBOOKS) -> str:
707729
708730
Args:
709731
folder: path to the folder
710-
base_path:
732+
base_path: base path with notebooks
733+
734+
Returns:
735+
path the updated YAML file
711736
712737
"""
713738
meta = AssistantCLI._load_meta(folder)

.azure/ipynb-tests.yml .azure/ipynb-validate.yml

+8-5
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@ jobs:
1919
displayName: "Install dependencies"
2020
2121
- bash: |
22-
head=$(git rev-parse origin/main)
23-
printf "Head: $head\n"
24-
git diff --name-only $head --output=target-diff.txt
22+
git fetch --all # some issues with missing main :/
23+
# head=$(git rev-parse origin/main)
24+
# printf "Head: $head\n" # this shall be commit hash
25+
# git diff --name-only $head --output=target-diff.txt
26+
git diff --name-only origin/main HEAD --output=target-diff.txt
27+
cat target-diff.txt
2528
python .actions/assistant.py group-folders --fpath_gitdiff=target-diff.txt
2629
printf "Changed folders:\n"
2730
cat changed-folders.txt
@@ -35,7 +38,7 @@ jobs:
3538
- bash: echo '$(mtrx.dirs)' | python -m json.tool
3639
displayName: "Show matrix"
3740

38-
- job: nbval
41+
- job: ipython
3942
dependsOn: check_diff
4043
strategy:
4144
matrix: $[ dependencies.check_diff.outputs['mtrx.dirs'] ]
@@ -96,4 +99,4 @@ jobs:
9699
env:
97100
KAGGLE_USERNAME: $(KAGGLE_USERNAME)
98101
KAGGLE_KEY: $(KAGGLE_KEY)
99-
displayName: "PyTest notebook"
102+
displayName: "Execute notebook"
File renamed without changes.

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# PytorchLightning Tutorials
22

3-
[![CI internal](https://github.com/Lightning-AI/tutorials/actions/workflows/ci_test-acts.yml/badge.svg?event=push)](https://github.com/Lightning-AI/tutorials/actions/workflows/ci_test-acts.yml)
3+
[![CI internal](https://github.com/Lightning-AI/tutorials/actions/workflows/ci_internal.yml/badge.svg?event=push)](https://github.com/Lightning-AI/tutorials/actions/workflows/ci_internal.yml)
44
[![Build Status](https://dev.azure.com/Lightning-AI/Tutorials/_apis/build/status/Lightning-AI.tutorials%20%5Bpublish%5D?branchName=main)](https://dev.azure.com/Lightning-AI/Tutorials/_build/latest?definitionId=29&branchName=main)
55
[![codecov](https://codecov.io/gh/Lightning-AI/tutorials/branch/main/graph/badge.svg?token=C6T3XOOR56)](https://codecov.io/gh/Lightning-AI/tutorials)
66
[![Deploy Docs](https://github.com/Lightning-AI/tutorials/actions/workflows/docs-deploy.yml/badge.svg)](https://github.com/Lightning-AI/tutorials/actions/workflows/docs-deploy.yml)
@@ -91,7 +91,7 @@ On the back side of publishing workflow you can find in principle these three st
9191
# 1) convert script to notebooks
9292
jupytext --set-formats ipynb,py:percent notebook.py
9393
94-
# 2) testing the created notebook
94+
# 2) [OPTIONAL] testing the created notebook
9595
pytest -v notebook.ipynb --nbval
9696
9797
# 3) generating notebooks outputs

_requirements/default.txt

+1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ setuptools>=68.0.0, <69.1.0
22
matplotlib>=3.0.0, <3.9.0
33
ipython[notebook]>=8.0.0, <8.17.0
44
urllib3 # for ipython
5+
numpy <2.0 # needed for older Torch
56
torch>=1.8.1, <2.1.0
67
pytorch-lightning>=1.4, <2.1.0
78
torchmetrics>=0.7, <1.3

_requirements/devel.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ virtualenv>=20.10
22
jupytext>=1.10, <1.15 # converting
33
pytest>=6.0, <7.0
44
# testing with own fork with extended cell timeout
5-
https://github.com/Borda/nbval/archive/refs/heads/timeout-limit.zip
5+
# https://github.com/Borda/nbval/archive/refs/heads/timeout-limit.zip
66
papermill>=2.3.4, <2.5.0 # render

course_UvA-DL/01-introduction-to-pytorch/.meta.yml

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ author: Phillip Lippe
33
created: 2021-08-27
44
updated: 2023-03-14
55
license: CC BY-SA
6+
build: 1
67
description: |
78
This tutorial will give a short introduction to PyTorch basics, and get you setup for writing your own neural networks.
89
This notebook is part of a lecture series on Deep Learning at the University of Amsterdam.

course_UvA-DL/07-deep-energy-based-generative-models/.meta.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ author: Phillip Lippe
33
created: 2021-07-12
44
updated: 2023-03-14
55
license: CC BY-SA
6-
build: 0
6+
build: 1
77
tags:
88
- Image
99
description: |
@@ -22,7 +22,7 @@ requirements:
2222
- torchvision
2323
- matplotlib
2424
- tensorboard
25-
- lightning>=2.0.0
25+
- pytorch-lightning>=2.0.0
2626
accelerator:
2727
- CPU
2828
- GPU

course_UvA-DL/07-deep-energy-based-generative-models/Deep_Energy_Models.py course_UvA-DL/07-deep-energy-based-generative-models/notebook.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,6 @@
99
import urllib.request
1010
from urllib.error import HTTPError
1111

12-
# PyTorch Lightning
13-
import lightning as L
14-
1512
# Plotting
1613
import matplotlib
1714
import matplotlib.pyplot as plt
@@ -20,6 +17,9 @@
2017
import matplotlib_inline.backend_inline
2118
import numpy as np
2219

20+
# PyTorch Lightning
21+
import pytorch_lightning as pl
22+
2323
# PyTorch
2424
import torch
2525
import torch.nn as nn
@@ -28,7 +28,7 @@
2828

2929
# Torchvision
3030
import torchvision
31-
from lightning.pytorch.callbacks import Callback, LearningRateMonitor, ModelCheckpoint
31+
from pytorch_lightning.callbacks import Callback, LearningRateMonitor, ModelCheckpoint
3232
from torchvision import transforms
3333
from torchvision.datasets import MNIST
3434

@@ -41,7 +41,7 @@
4141
CHECKPOINT_PATH = os.environ.get("PATH_CHECKPOINT", "saved_models/tutorial8")
4242

4343
# Setting the seed
44-
L.seed_everything(42)
44+
pl.seed_everything(42)
4545

4646
# Ensure that all operations are deterministic on GPU (if used) for reproducibility
4747
torch.backends.cudnn.deterministic = True
@@ -465,7 +465,7 @@ def generate_samples(model, inp_imgs, steps=60, step_size=10, return_img_per_ste
465465

466466

467467
# %%
468-
class DeepEnergyModel(L.LightningModule):
468+
class DeepEnergyModel(pl.LightningModule):
469469
def __init__(self, img_shape, batch_size, alpha=0.1, lr=1e-4, beta1=0.0, **CNN_args):
470470
super().__init__()
471471
self.save_hyperparameters()
@@ -640,7 +640,7 @@ def on_epoch_end(self, trainer, pl_module):
640640
# %%
641641
def train_model(**kwargs):
642642
# Create a PyTorch Lightning trainer with the generation callback
643-
trainer = L.Trainer(
643+
trainer = pl.Trainer(
644644
default_root_dir=os.path.join(CHECKPOINT_PATH, "MNIST"),
645645
accelerator="auto",
646646
devices=1,
@@ -660,7 +660,7 @@ def train_model(**kwargs):
660660
print("Found pretrained model, loading...")
661661
model = DeepEnergyModel.load_from_checkpoint(pretrained_filename)
662662
else:
663-
L.seed_everything(42)
663+
pl.seed_everything(42)
664664
model = DeepEnergyModel(**kwargs)
665665
trainer.fit(model, train_loader, test_loader)
666666
model = DeepEnergyModel.load_from_checkpoint(trainer.checkpoint_callback.best_model_path)
@@ -709,7 +709,7 @@ def train_model(**kwargs):
709709

710710
# %%
711711
model.to(device)
712-
L.seed_everything(43)
712+
pl.seed_everything(43)
713713
callback = GenerateCallback(batch_size=4, vis_steps=8, num_steps=256)
714714
imgs_per_step = callback.generate_imgs(model)
715715
imgs_per_step = imgs_per_step.cpu()
@@ -770,7 +770,7 @@ def train_model(**kwargs):
770770
rand_imgs = torch.rand((128,) + model.hparams.img_shape).to(model.device)
771771
rand_imgs = rand_imgs * 2 - 1.0
772772
rand_out = model.cnn(rand_imgs).mean()
773-
print(f"Average score for random images: {rand_out.item():4.2f}")
773+
print(f"Average score for random images: {rand_out.item()}")
774774

775775
# %% [markdown]
776776
# As we hoped, the model assigns very low probability to those noisy images.
@@ -803,8 +803,8 @@ def compare_images(img1, img2):
803803
plt.xticks([(img1.shape[2] + 2) * (0.5 + j) for j in range(2)], labels=["Original image", "Transformed image"])
804804
plt.yticks([])
805805
plt.show()
806-
print(f"Score original image: {score1:4.2f}")
807-
print(f"Score transformed image: {score2:4.2f}")
806+
print(f"Score original image: {score1}")
807+
print(f"Score transformed image: {score2}")
808808

809809

810810
# %% [markdown]

pyproject.toml

-1
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,6 @@ ignore = [
8585
# TODO: we shall format all long comments as it comes from text cells
8686
"E501", # Line too long
8787
]
88-
ignore-init-module-imports = true
8988

9089
[tool.ruff.lint.per-file-ignores]
9190
"setup.py" = ["D100", "SIM115"]

0 commit comments

Comments
 (0)