Skip to content

Commit 6e5f6d4

Browse files
committed
Merge branch 'master' into moritz-shard-mgpu
2 parents 1011ace + 0baf1d9 commit 6e5f6d4

82 files changed

Lines changed: 722 additions & 719 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: black
1+
name: ruff
22

33
on:
44
push:
@@ -11,15 +11,14 @@ on:
1111
- master
1212

1313
jobs:
14-
check-black-formatting:
14+
check-ruff-formatting:
1515
runs-on: ubuntu-latest
1616
steps:
1717
- uses: actions/checkout@v4
1818
- uses: actions/setup-python@v5
1919
with:
2020
python-version: 3.8
2121
cache: 'pip'
22-
cache-dependency-path: '.github/workflows/black.yml'
23-
- run: pip install black==22.3.0
24-
- run: black --diff .
25-
- run: black --check .
22+
cache-dependency-path: '.github/workflows/ruff.yml'
23+
- run: pip install ruff==0.11.8
24+
- run: ruff format --diff .

CONTRIBUTING.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ General rules when contributing to the code of RETURNN:
1818
Our code style uses most common Python conventions.
1919
If you are not an expert in Python, use PyCharm,
2020
and follow [our PyCharm configuration guide](https://github.com/rwth-i6/returnn/wiki/PyCharm-Configuration).
21-
Apply [black](https://black.readthedocs.io/).
21+
Apply [ruff](https://github.com/astral-sh/ruff).
2222
* Make sure all [tests](https://returnn.readthedocs.io/en/latest/advanced/test_suite.html) pass.
2323
* At the time being, we want to support earlier versions of TF 1
2424
(consider at least TF 1.8, but maybe even TF 1.4)

__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
We want to support the same code.
88
"""
99

10-
1110
from __future__ import annotations
1211
import os
1312
import sys

demos/demo-tf-search-compiled-graph.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,12 @@
88

99
# No RETURNN dependency needed for the basic search. Just TF itself.
1010

11-
import typing
1211
import os
1312
import json
1413
import argparse
1514
import tensorflow as tf
1615
import numpy
16+
from typing import List, Optional, Tuple
1717

1818

1919
class Hyp:
@@ -26,7 +26,7 @@ def __init__(self, idx):
2626
:param int idx: hyp idx (to identify it in a beam)
2727
"""
2828
self.idx = idx
29-
self.source_idx = None # type: typing.Optional[int] # source hyp idx
29+
self.source_idx: Optional[int] = None # source hyp idx
3030
self.score = 0.0
3131
self.seq = [] # label seq
3232

@@ -91,7 +91,6 @@ def make_initial_feed_dict():
9191
# Now loop over decoder steps.
9292
max_dec_len = 100 # TODO better default... depending on input len. or configurable...
9393
for i in range(max_dec_len):
94-
9594
# Loop over all stochastic variables.
9695
for stochastic_var in info["stochastic_var_order"]:
9796
assert isinstance(stochastic_var, str)
@@ -108,9 +107,7 @@ def make_initial_feed_dict():
108107
# TODO: length norm here?
109108

110109
# Select new hypotheses.
111-
best_possibilities = sorted(all_possibilities)[
112-
: args.beam_size
113-
] # type: typing.List[typing.Tuple[float,int,Hyp]]
110+
best_possibilities: List[Tuple[float, int, Hyp]] = sorted(all_possibilities)[: args.beam_size]
114111
assert len(best_possibilities) == args.beam_size
115112
hyps = [
116113
hyp.expand(idx=i, label=label, score=score)
@@ -121,8 +118,9 @@ def make_initial_feed_dict():
121118
session.run(
122119
info["state_vars"]["stochastic_var_scores_%s" % stochastic_var] + "/Assign...?", # TODO...
123120
feed_dict={
124-
info["state_vars"]["stochastic_var_scores_%s" % stochastic_var]
125-
+ "/Initial...?": [[hyp.seq[-1] for hyp in hyps]] # TODO...
121+
info["state_vars"]["stochastic_var_scores_%s" % stochastic_var] + "/Initial...?": [
122+
[hyp.seq[-1] for hyp in hyps]
123+
] # TODO...
126124
},
127125
)
128126

docs/conf.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@
7777
]
7878

7979
# See https://github.com/rtfd/readthedocs.org/issues/283
80-
mathjax_path = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?" "config=TeX-AMS-MML_HTMLorMML"
80+
mathjax_path = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"
8181

8282
# see https://stackoverflow.com/q/12206334/562769
8383
numpydoc_show_class_members = False
@@ -151,6 +151,7 @@
151151
# If true, keep warnings as "system message" paragraphs in the built documents.
152152
# keep_warnings = False
153153

154+
154155
# Resolve function for the linkcode extension.
155156
def linkcode_resolve(domain, info):
156157
def find_source():

pyproject.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,9 @@ extend-exclude = '''
1313
)/
1414
'''
1515

16+
[tool.ruff]
17+
line-length = 120
18+
target-version = "py38" # https://github.com/rwth-i6/returnn/issues/1326
19+
1620
[build-system]
1721
requires = ["setuptools", "numpy"]

requirements-dev

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
black==22.3.0
21
pytest
2+
ruff==0.11.8

returnn/datasets/basic.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import numpy
2121
import functools
2222
import typing
23-
from typing import TYPE_CHECKING, Optional, Any, Tuple, Union, Type, Dict, Sequence, List, Callable
23+
from typing import TYPE_CHECKING, Optional, Any, Set, Tuple, Union, Type, Dict, Sequence, List, Callable
2424

2525
from returnn.log import log
2626
from returnn.engine.batch import Batch, BatchSetGenerator
@@ -147,12 +147,10 @@ def __init__(
147147
:param shard_index: local shard index, when sharding is enabled
148148
"""
149149
self.name = name or ("dataset_id%s" % id(self))
150-
self.lock = None # type: Optional[RLock] # Used when manipulating our data potentially from multiple threads.
151-
self.rnd_seq_drop = None # type: typing.Optional[Random]
150+
self.lock: Optional[RLock] = None # Used when manipulating our data potentially from multiple threads.
151+
self.rnd_seq_drop: Optional[Random] = None
152152
self.num_inputs = 0 # usually not used, but num_outputs instead, which is more generic
153-
self.num_outputs = (
154-
None
155-
) # type: typing.Optional[typing.Dict[str,typing.Tuple[int,int]]] # tuple is num-classes, len(shape). # nopep8
153+
self.num_outputs: Optional[Dict[str, Tuple[int, int]]] = None # tuple is num-classes, len(shape).
156154
self.window = window
157155
self.seq_ordering = seq_ordering # "default", "sorted" or "random". See self.get_seq_order_for_epoch().
158156
self.fixed_random_seed = fixed_random_seed
@@ -165,10 +163,10 @@ def __init__(
165163
self._seq_order_seq_lens_file = seq_order_seq_lens_file
166164
self._seq_order_seq_lens_by_idx = None
167165
# There is probably no use case for combining the two, so avoid potential misconfiguration.
168-
assert (
169-
self.partition_epoch == 1 or self.repeat_epoch == 1
170-
), "Combining partition_epoch and repeat_epoch is prohibited."
171-
self.labels = {} # type: typing.Dict[str,typing.List[str]]
166+
assert self.partition_epoch == 1 or self.repeat_epoch == 1, (
167+
"Combining partition_epoch and repeat_epoch is prohibited."
168+
)
169+
self.labels: Dict[str, List[str]] = {}
172170
self.weights = {}
173171
self._num_timesteps = 0
174172
self._num_seqs = 0
@@ -219,8 +217,8 @@ def __repr__(self):
219217
getattr(self, "epoch", "<unknown>"),
220218
)
221219

222-
_getnewargs_exclude_attrs = set() # type: typing.Set[str]
223-
_getnewargs_remap = {} # type: typing.Dict[str,str]
220+
_getnewargs_exclude_attrs: Set[str] = set()
221+
_getnewargs_remap: Dict[str, str] = {}
224222

225223
@staticmethod
226224
def _create_from_reduce(cls, kwargs, state) -> Dataset:
@@ -697,12 +695,13 @@ def get_seq_order_for_epoch(
697695
)
698696
old_seq_index = seq_index
699697
seq_index = [i for i in seq_index if all_seq_tags[i] in self.seq_tags_filter]
700-
assert (
701-
seq_index
702-
), "%s: empty after applying seq_list_filter_file. Example filter tags: %r, used tags: %r" % (
703-
self,
704-
sorted(self.seq_tags_filter)[:3],
705-
[all_seq_tags[i] for i in old_seq_index[:3]],
698+
assert seq_index, (
699+
"%s: empty after applying seq_list_filter_file. Example filter tags: %r, used tags: %r"
700+
% (
701+
self,
702+
sorted(self.seq_tags_filter)[:3],
703+
[all_seq_tags[i] for i in old_seq_index[:3]],
704+
)
706705
)
707706
return seq_index
708707

@@ -773,9 +772,9 @@ def init_seq_order(self, epoch=None, seq_list=None, seq_order=None):
773772
"""
774773
self.epoch = epoch
775774
self.rnd_seq_drop = Random(self._get_random_seed_for_epoch(epoch=epoch))
776-
assert (
777-
self.num_shards == 1 or self.supports_sharding()
778-
), f"{self}: does not support sharding, but got num_shards == {self.num_shards}"
775+
assert self._num_shards == 1 or self.supports_sharding(), (
776+
f"{self}: does not support sharding, but got num_shards == {self._num_shards}"
777+
)
779778
return False
780779

781780
def finish_epoch(self, *, free_resources: bool = False):
@@ -1007,16 +1006,16 @@ def get_complete_frac(self, sorted_seq_idx: int, *, allow_only_lr_suitable: bool
10071006
except Exception: # also not always available
10081007
num_seqs = None # ignore
10091008

1010-
if math.isinf(num_seqs):
1009+
if num_seqs is not None and math.isinf(num_seqs):
10111010
if allow_only_lr_suitable:
10121011
# cannot compute meaningful complete_frac for infinite num_seqs
10131012
return None
10141013
else:
10151014
num_seqs = None
10161015

1017-
assert (
1018-
num_seqs is None or 0 <= sorted_seq_idx < num_seqs
1019-
), f"{self}: invalid seq indices: 0 <= seq_idx ({sorted_seq_idx}) < num_seqs ({num_seqs}) violated"
1016+
assert num_seqs is None or 0 <= sorted_seq_idx < num_seqs, (
1017+
f"{self}: invalid seq indices: 0 <= seq_idx ({sorted_seq_idx}) < num_seqs ({num_seqs}) violated"
1018+
)
10201019
return self.generic_complete_frac(sorted_seq_idx, num_seqs)
10211020

10221021
@property

returnn/datasets/cached.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,10 @@ def __init__(self, cache_byte_size=0, **kwargs):
4646
self._index_map = range(len(self._seq_index)) # sorted seq idx -> seq_index idx
4747
self._tag_idx = {} # type: typing.Dict[str,int] # map of tag -> real-seq-idx. call _update_tag_idx
4848
self.targets = {}
49-
self.target_keys = (
50-
[]
51-
) # the keys for which we provide data; we may have labels for additional keys in self.labels
49+
# the keys for which we provide data;
50+
# we may have labels for additional keys in self.labels
51+
self.target_keys = []
52+
5253
self.timestamps = None
5354

5455
def initialize(self):

returnn/datasets/distrib_files.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -442,8 +442,7 @@ def _distribute_evenly_by_size(
442442
# We need to decide where to add this file, to the current or the next sub epoch.
443443
if not files_per_bin[bin_idx] or (
444444
# Better to add this file to the current sub epoch?
445-
abs((size_taken + size) - avg_size_per_sub_epoch)
446-
<= abs(size_taken - avg_size_per_sub_epoch)
445+
abs((size_taken + size) - avg_size_per_sub_epoch) <= abs(size_taken - avg_size_per_sub_epoch)
447446
):
448447
files_per_bin[bin_idx].append(f_tree)
449448
size_taken = 0

0 commit comments

Comments
 (0)