Skip to content
This repository was archived by the owner on Aug 28, 2025. It is now read-only.

Commit 57f93b1

Browse files
committed
ci/lint: simplification of used tools
1 parent 37e0798 commit 57f93b1

File tree

19 files changed

+135
-47
lines changed

19 files changed

+135
-47
lines changed

.actions/assistant.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ def _find_meta(folder: str) -> str:
167167
168168
Args:
169169
folder: path to the folder with python script, meta and artefacts
170+
170171
"""
171172
files = glob.glob(os.path.join(folder, AssistantCLI._META_FILE_REGEX), flags=glob.BRACE)
172173
if len(files) == 1:
@@ -180,6 +181,7 @@ def _load_meta(folder: str, strict: bool = False) -> Optional[dict]:
180181
Args:
181182
folder: path to the folder with python script, meta and artefacts
182183
strict: raise error if meta is missing required fields
184+
183185
"""
184186
fpath = AssistantCLI._find_meta(folder)
185187
assert fpath, f"Missing meta file in folder: {folder}"
@@ -197,6 +199,7 @@ def _valid_conf_folder(folder: str) -> Tuple[str, str]:
197199
198200
Args:
199201
folder: path to the folder with python script, meta and artefacts
202+
200203
"""
201204
meta_files = [os.path.join(folder, f".meta.{ext}") for ext in ("yml", "yaml")]
202205
meta_files = [pf for pf in meta_files if os.path.isfile(pf)]
@@ -217,6 +220,7 @@ def _valid_folder(folder: str, ext: str) -> Tuple[str, str, str]:
217220
Args:
218221
folder: path to the folder with python script, meta and artefacts
219222
ext: extension determining the stage - ".py" for python script nad ".ipynb" for notebook
223+
220224
"""
221225
files = glob.glob(os.path.join(folder, f"*{ext}"))
222226
if len(files) != 1:
@@ -231,6 +235,7 @@ def _valid_accelerator(folder: str) -> bool:
231235
232236
Args:
233237
folder: path to the folder with python script, meta and artefacts
238+
234239
"""
235240
meta = AssistantCLI._load_meta(folder)
236241
meta_accels = [acc.lower() for acc in meta.get("accelerator", AssistantCLI._META_ACCEL_DEFAULT)]
@@ -243,6 +248,7 @@ def _parse_requirements(folder: str) -> Tuple[str, str]:
243248
244249
Args:
245250
folder: path to the folder with python script, meta and artefacts
251+
246252
"""
247253
meta = AssistantCLI._load_meta(folder)
248254
reqs = meta.get("requirements", [])
@@ -268,6 +274,7 @@ def _bash_download_data(folder: str) -> List[str]:
268274
269275
Args:
270276
folder: path to the folder with python script, meta and artefacts
277+
271278
"""
272279
meta = AssistantCLI._load_meta(folder)
273280
datasets = meta.get("datasets", {})
@@ -299,6 +306,7 @@ def bash_render(folder: str, output_file: str = PATH_SCRIPT_RENDER) -> Optional[
299306
300307
Returns:
301308
string with nash script content
309+
302310
"""
303311
cmd = list(AssistantCLI._BASH_SCRIPT_BASE) + [f"# Rendering: {folder}"]
304312
if not AssistantCLI.DRY_RUN:
@@ -348,6 +356,7 @@ def bash_test(folder: str, output_file: str = PATH_SCRIPT_TEST) -> Optional[str]
348356
349357
Returns:
350358
string with nash script content
359+
351360
"""
352361
cmd = list(AssistantCLI._BASH_SCRIPT_BASE) + [f"# Testing: {folder}"]
353362
cmd += AssistantCLI._bash_download_data(folder)
@@ -395,6 +404,7 @@ def convert_ipynb(folder: str) -> None:
395404
396405
Args:
397406
folder: folder with python script
407+
398408
"""
399409
fpath, _, _ = AssistantCLI._valid_folder(folder, ext=".py")
400410
with open(fpath) as fopen:
@@ -426,6 +436,7 @@ def _replace_images(lines: list, local_dir: str) -> list:
426436
Args:
427437
lines: string lines from python script
428438
local_dir: relative path to the folder with script
439+
429440
"""
430441
md = os.linesep.join([ln.rstrip() for ln in lines])
431442
p_imgs = []
@@ -488,6 +499,7 @@ def group_folders(
488499
Example:
489500
$ python assistant.py group-folders ../target-diff.txt \
490501
--fpath_actual_dirs "['../dirs-main.txt', '../dirs-publication.txt']"
502+
491503
"""
492504
with open(fpath_gitdiff) as fopen:
493505
changed = [ln.strip() for ln in fopen.readlines()]
@@ -534,6 +546,7 @@ def generate_matrix(fpath_change_folders: str, json_indent: Optional[int] = None
534546
Args:
535547
fpath_change_folders: output of previous ``group_folders``
536548
json_indent: makes the json more readable, recommendation is 4
549+
537550
"""
538551
with open(fpath_change_folders) as fopen:
539552
folders = [ln.strip() for ln in fopen.readlines()]
@@ -623,6 +636,7 @@ def copy_notebooks(
623636
path_docs_images: destination path to the images' location relative to ``docs_root``
624637
patterns: patterns to use when glob-ing notebooks
625638
ignore: ignore some specific notebooks even when the given string is in path
639+
626640
"""
627641
all_ipynb = []
628642
for pattern in patterns:
@@ -694,6 +708,7 @@ def update_env_details(folder: str, base_path: str = DIR_NOTEBOOKS) -> str:
694708
Args:
695709
folder: path to the folder
696710
base_path:
711+
697712
"""
698713
meta = AssistantCLI._load_meta(folder)
699714
# default is COU runtime

.pre-commit-config.yaml

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,6 @@ repos:
2222
- id: check-docstring-first
2323
- id: detect-private-key
2424

25-
- repo: https://github.com/asottile/pyupgrade
26-
rev: v3.15.0
27-
hooks:
28-
- id: pyupgrade
29-
args: ["--py38-plus"]
30-
name: Upgrade code
31-
3225
- repo: https://github.com/codespell-project/codespell
3326
rev: v2.2.6
3427
hooks:
@@ -40,29 +33,17 @@ repos:
4033
rev: v1.7.5
4134
hooks:
4235
- id: docformatter
43-
args:
44-
- "--in-place"
45-
- "--wrap-summaries=119"
46-
- "--wrap-descriptions=120"
36+
additional_dependencies: [tomli]
37+
args: ["--in-place"]
4738

4839
- repo: https://github.com/pre-commit/mirrors-prettier
4940
rev: v3.1.0
5041
hooks:
5142
- id: prettier
43+
files: \.(json|yml|yaml|toml)
5244
# https://prettier.io/docs/en/options.html#print-width
5345
args: ["--print-width=120"]
5446

55-
- repo: https://github.com/psf/black
56-
rev: 23.12.1
57-
hooks:
58-
- id: black
59-
name: Format code
60-
61-
- repo: https://github.com/asottile/yesqa
62-
rev: v1.5.0
63-
hooks:
64-
- id: yesqa
65-
6647
- repo: https://github.com/executablebooks/mdformat
6748
rev: 0.7.17
6849
hooks:
@@ -73,7 +54,12 @@ repos:
7354
- mdformat_frontmatter
7455

7556
- repo: https://github.com/astral-sh/ruff-pre-commit
76-
rev: v0.1.9
57+
rev: v0.3.5
7758
hooks:
59+
# try to fix what is possible
7860
- id: ruff
7961
args: ["--fix"]
62+
# perform formatting updates
63+
- id: ruff-format
64+
# validate if all is fine with preview mode
65+
- id: ruff

.prettierignore

Lines changed: 0 additions & 2 deletions
This file was deleted.

course_UvA-DL/01-introduction-to-pytorch/Introduction_to_PyTorch.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,6 +606,7 @@ def __init__(self, size, std=0.1):
606606
Args:
607607
size: Number of data points we want to generate
608608
std: Standard deviation of the noise (see generate_continuous_xor function)
609+
609610
"""
610611
super().__init__()
611612
self.size = size

course_UvA-DL/02-activation-functions/Activation_Functions.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ def get_grads(act_fn, x):
218218
219219
Returns:
220220
A tensor with the same size of x containing the gradients of act_fn at x.
221+
221222
"""
222223
x = x.clone().requires_grad_() # Mark the input as tensor for which we want to store gradients
223224
out = act_fn(x)
@@ -287,6 +288,7 @@ def __init__(self, act_fn, input_size=784, num_classes=10, hidden_sizes=[512, 25
287288
input_size: Size of the input images in pixels
288289
num_classes: Number of classes we want to predict
289290
hidden_sizes: A list of integers specifying the hidden layer sizes in the NN
291+
290292
"""
291293
super().__init__()
292294

@@ -338,6 +340,7 @@ def load_model(model_path, model_name, net=None):
338340
model_path: Path of the checkpoint directory
339341
model_name: Name of the model (str)
340342
net: (Optional) If given, the state dict is loaded into this model. Otherwise, a new model is created.
343+
341344
"""
342345
config_file, model_file = _get_config_file(model_path, model_name), _get_model_file(model_path, model_name)
343346
assert os.path.isfile(
@@ -363,6 +366,7 @@ def save_model(model, model_path, model_name):
363366
model: Network object to save parameters from
364367
model_path: Path of the checkpoint directory
365368
model_name: Name of the model (str)
369+
366370
"""
367371
config_dict = model.config
368372
os.makedirs(model_path, exist_ok=True)
@@ -438,6 +442,7 @@ def visualize_gradients(net, color="C0"):
438442
Args:
439443
net: Object of class BaseNetwork
440444
color: Color in which we want to visualize the histogram (for easier separation of activation functions)
445+
441446
"""
442447
net.eval()
443448
small_loader = data.DataLoader(train_set, batch_size=256, shuffle=False)
@@ -519,6 +524,7 @@ def train_model(net, model_name, max_epochs=50, patience=7, batch_size=256, over
519524
patience: If the performance on the validation set has not improved for #patience epochs, we stop training early
520525
batch_size: Size of batches used in training
521526
overwrite: Determines how to handle the case when there already exists a checkpoint. If True, it will be overwritten. Otherwise, we skip training.
527+
522528
"""
523529
file_exists = os.path.isfile(_get_model_file(CHECKPOINT_PATH, model_name))
524530
if file_exists and not overwrite:
@@ -591,6 +597,7 @@ def test_model(net, data_loader):
591597
Args:
592598
net: Trained model of type BaseNetwork
593599
data_loader: DataLoader object of the dataset to test on (validation or test)
600+
594601
"""
595602
net.eval()
596603
true_preds, count = 0.0, 0
@@ -717,6 +724,7 @@ def measure_number_dead_neurons(net):
717724
718725
For each neuron, we create a boolean variable initially set to 1. If it has an activation unequals 0 at any time, we
719726
set this variable to 0. After running through the whole training set, only dead neurons will have a 1.
727+
720728
"""
721729
neurons_dead = [
722730
torch.ones(layer.weight.shape[0], device=device, dtype=torch.bool)

course_UvA-DL/03-initialization-and-optimization/Initialization_and_Optimization.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ def __init__(self, act_fn, input_size=784, num_classes=10, hidden_sizes=[512, 25
158158
input_size: Size of the input images in pixels
159159
num_classes: Number of classes we want to predict
160160
hidden_sizes: A list of integers specifying the hidden layer sizes in the NN
161+
161162
"""
162163
super().__init__()
163164

@@ -618,6 +619,7 @@ def train_model(net, model_name, optim_func, max_epochs=50, batch_size=256, over
618619
patience: If the performance on the validation set has not improved for #patience epochs, we stop training early
619620
batch_size: Size of batches used in training
620621
overwrite: Determines how to handle the case when there already exists a checkpoint. If True, it will be overwritten. Otherwise, we skip training.
622+
621623
"""
622624
file_exists = os.path.isfile(_get_model_file(CHECKPOINT_PATH, model_name))
623625
if file_exists and not overwrite:
@@ -718,6 +720,7 @@ def test_model(net, data_loader):
718720
Args:
719721
net: Trained model of type BaseNetwork
720722
data_loader: DataLoader object of the dataset to test on (validation or test)
723+
721724
"""
722725
net.eval()
723726
true_preds, count = 0.0, 0

course_UvA-DL/04-inception-resnet-densenet/Inception_ResNet_DenseNet.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,7 @@ def __init__(self, model_name, model_hparams, optimizer_name, optimizer_hparams)
224224
model_hparams: Hyperparameters for the model, as dictionary.
225225
optimizer_name: Name of the optimizer to use. Currently supported: Adam, SGD
226226
optimizer_hparams: Hyperparameters for the optimizer, as dictionary. This includes learning rate, weight decay, etc.
227+
227228
"""
228229
super().__init__()
229230
# Exports the hyperparameters to a YAML file, and create "self.hparams" namespace
@@ -343,6 +344,7 @@ def train_model(model_name, save_name=None, **kwargs):
343344
Args:
344345
model_name: Name of the model you want to run. Is used to look up the class in "model_dict"
345346
save_name (optional): If specified, this name will be used for creating the checkpoint and logging directory.
347+
346348
"""
347349
if save_name is None:
348350
save_name = model_name
@@ -426,6 +428,7 @@ def __init__(self, c_in, c_red: dict, c_out: dict, act_fn):
426428
c_red: Dictionary with keys "3x3" and "5x5" specifying the output of the dimensionality reducing 1x1 convolutions
427429
c_out: Dictionary with keys "1x1", "3x3", "5x5", and "max"
428430
act_fn: Activation class constructor (e.g. nn.ReLU)
431+
429432
"""
430433
super().__init__()
431434

@@ -676,6 +679,7 @@ def __init__(self, c_in, act_fn, subsample=False, c_out=-1):
676679
act_fn: Activation class constructor (e.g. nn.ReLU)
677680
subsample - If True, we want to apply a stride inside the block and reduce the output shape by 2 in height and width
678681
c_out - Number of output features. Note that this is only relevant if subsample is True, as otherwise, c_out = c_in
682+
679683
"""
680684
super().__init__()
681685
if not subsample:
@@ -722,6 +726,7 @@ def __init__(self, c_in, act_fn, subsample=False, c_out=-1):
722726
act_fn - Activation class constructor (e.g. nn.ReLU)
723727
subsample - If True, we want to apply a stride inside the block and reduce the output shape by 2 in height and width
724728
c_out - Number of output features. Note that this is only relevant if subsample is True, as otherwise, c_out = c_in
729+
725730
"""
726731
super().__init__()
727732
if not subsample:
@@ -793,6 +798,7 @@ def __init__(
793798
c_hidden - List with the hidden dimensionalities in the different blocks. Usually multiplied by 2 the deeper we go.
794799
act_fn_name - Name of the activation function to use, looked up in "act_fn_by_name"
795800
block_name - Name of the ResNet block, looked up in "resnet_blocks_by_name"
801+
796802
"""
797803
super().__init__()
798804
assert block_name in resnet_blocks_by_name
@@ -962,6 +968,7 @@ def __init__(self, c_in, bn_size, growth_rate, act_fn):
962968
bn_size - Bottleneck size (factor of growth rate) for the output of the 1x1 convolution. Typically between 2 and 4.
963969
growth_rate - Number of output channels of the 3x3 convolution
964970
act_fn - Activation class constructor (e.g. nn.ReLU)
971+
965972
"""
966973
super().__init__()
967974
self.net = nn.Sequential(
@@ -995,6 +1002,7 @@ def __init__(self, c_in, num_layers, bn_size, growth_rate, act_fn):
9951002
bn_size - Bottleneck size to use in the dense layers
9961003
growth_rate - Growth rate to use in the dense layers
9971004
act_fn - Activation function to use in the dense layers
1005+
9981006
"""
9991007
super().__init__()
10001008
layers = []

course_UvA-DL/05-transformers-and-MH-attention/Transformers_MHAttention.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,7 @@ def __init__(self, input_dim, num_heads, dim_feedforward, dropout=0.0):
470470
num_heads: Number of heads to use in the attention block
471471
dim_feedforward: Dimensionality of the hidden layer in the MLP
472472
dropout: Dropout probability to use in the dropout layers
473+
473474
"""
474475
super().__init__()
475476

@@ -578,6 +579,7 @@ def __init__(self, d_model, max_len=5000):
578579
Args:
579580
d_model: Hidden dimensionality of the input.
580581
max_len: Maximum length of a sequence to expect.
582+
581583
"""
582584
super().__init__()
583585

@@ -773,6 +775,7 @@ def __init__(
773775
max_iters: Number of maximum iterations the model is trained for. This is needed for the CosineWarmup scheduler
774776
dropout: Dropout to apply inside the model
775777
input_dropout: Dropout to apply on the input features
778+
776779
"""
777780
super().__init__()
778781
self.save_hyperparameters()
@@ -822,6 +825,7 @@ def get_attention_maps(self, x, mask=None, add_positional_encoding=True):
822825
"""Function for extracting the attention matrices of the whole Transformer for a single batch.
823826
824827
Input arguments same as the forward pass.
828+
825829
"""
826830
x = self.input_net(x)
827831
if add_positional_encoding:
@@ -1314,6 +1318,7 @@ def sample_img_set(self, anomaly_label):
13141318
"""Samples a new set of images, given the label of the anomaly.
13151319
13161320
The sampled images come from a different class than anomaly_label
1321+
13171322
"""
13181323
# Sample class from 0,...,num_classes-1 while skipping anomaly_label as class
13191324
set_label = np.random.randint(self.num_labels - 1)

0 commit comments

Comments
 (0)