Skip to content

Commit edddaa2

Browse files
authored
Rename tensors to tensornames (aws#49)
* Rename tensors to tensornames * rename method * Trial tensor_names method logs warning, and disallows both regex and collection * add test * change first arg of static method * fix test * trigger CI
1 parent a99e163 commit edddaa2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+289
-274
lines changed

examples/mxnet/notebooks/MNISTSimpleInteractiveAnalysis.ipynb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@
324324
"metadata": {},
325325
"outputs": [],
326326
"source": [
327-
"good_trial.tensors()"
327+
"good_trial.tensor_names()"
328328
]
329329
},
330330
{
@@ -419,7 +419,7 @@
419419
"outputs": [],
420420
"source": [
421421
"def plot_gradients( lt ):\n",
422-
" for tname in lt.tensors():\n",
422+
" for tname in lt.tensor_names():\n",
423423
" if not 'gradient' in tname: continue\n",
424424
" steps, data = get_data(lt, tname)\n",
425425
" plt.plot( steps, data, label=tname)\n",

examples/mxnet/notebooks/mxnet-realtime-analysis.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@
355355
"outputs": [],
356356
"source": [
357357
"# feel free to inspect all tensors logged by uncommenting below line\n",
358-
"# trial.tensors()"
358+
"# trial.tensor_names()"
359359
]
360360
},
361361
{

examples/mxnet/notebooks/tensor_plot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,15 @@ def load_tensors(self):
6363

6464
# input image into the neural network
6565
if self.label is not None:
66-
for tname in self.trial.tensors(regex=self.label):
66+
for tname in self.trial.tensor_names(regex=self.label):
6767
tensor = self.trial.tensor(tname).value(step)
6868
if self.color_channel == 1:
6969
self.input[step] = tensor[0, 0, :, :]
7070
elif self.color_channel == 3:
7171
self.input[step] = tensor[0, :, :, 3]
7272

7373
# iterate over tensors that match the regex
74-
for tname in self.trial.tensors(regex=self.regex):
74+
for tname in self.trial.tensor_names(regex=self.regex):
7575
tensor = self.trial.tensor(tname).value(step)
7676
# get max value of tensors to set axis dimension accordingly
7777
for dim in tensor.shape:
@@ -119,7 +119,7 @@ def load_tensors(self):
119119

120120
# model output
121121
if self.prediction is not None:
122-
for tname in self.trial.tensors(regex=self.prediction):
122+
for tname in self.trial.tensor_names(regex=self.prediction):
123123
tensor = self.trial.tensor(tname).value(step)
124124
# predicted class (batch size, propabilities per clas)
125125
if len(tensor.shape) == 2:

examples/pytorch/notebooks/PyTorch-SimpleInteractiveAnalysis.ipynb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -736,7 +736,7 @@
736736
}
737737
],
738738
"source": [
739-
"good_trial.tensors()"
739+
"good_trial.tensor_names()"
740740
]
741741
},
742742
{
@@ -874,7 +874,7 @@
874874
"outputs": [],
875875
"source": [
876876
"def plot_gradients( lt ):\n",
877-
" for tname in lt.tensors():\n",
877+
" for tname in lt.tensor_names():\n",
878878
" if not 'gradient' in tname: continue\n",
879879
" steps, data = get_data(lt, tname)\n",
880880
" plt.plot( steps, data, label=tname)\n",

examples/rules/scripts/my_custom_rule.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ def __init__(self, base_trial, threshold=10.0):
88
self.threshold = float(threshold)
99

1010
def set_required_tensors(self, step):
11-
for tname in self.base_trial.tensors(collection="gradients"):
11+
for tname in self.base_trial.tensor_names(collection="gradients"):
1212
self.req_tensors.add(tname, steps=[step])
1313

1414
def invoke_at_step(self, step):

smdebug/rules/req_tensors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def _add_steps_for_tensor(self, name, steps):
5757

5858
def add(self, name, steps, should_match_regex=False):
5959
if should_match_regex:
60-
names = self.trial.tensors(regex=[name])
60+
names = self.trial.tensor_names(regex=[name])
6161
for name in names:
6262
self._add_steps_for_tensor(name, steps)
6363
else:

smdebug/trials/trial.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ def __repr__(self):
121121
f" path={self.path},\n"
122122
f" steps={self.steps()},\n"
123123
f" collections={list(self.collections().keys())},\n"
124-
f" tensors={self.tensors()},\n"
124+
f" tensor_names={self.tensor_names()},\n"
125125
f")"
126126
)
127127

@@ -314,21 +314,25 @@ def _tensors_matching_regex(self, regex_list) -> set:
314314
matched_tensornames.add(tensorname)
315315
return matched_tensornames
316316

317-
def _tensors_in_collection(self, collection) -> set:
317+
@staticmethod
318+
def _parse_collection_name(collection):
318319
if isinstance(collection, Collection):
319320
coll_name = collection.name
320321
elif type(collection) is str:
321322
coll_name = collection
322323
else:
323324
raise TypeError(f"Invalid argument type for collection {collection.__class__}")
325+
return coll_name
324326

327+
def _tensors_in_collection(self, collection) -> set:
328+
coll_name = self._parse_collection_name(collection)
325329
rval = set(self.collection(coll_name).tensor_names)
326330
regex = self.collection(coll_name).include_regex
327331
if regex:
328332
rval.update(self._tensors_matching_regex(regex))
329333
return rval
330334

331-
def tensors(self, *, step=None, mode=ModeKeys.GLOBAL, regex=None, collection=None) -> list:
335+
def tensor_names(self, *, step=None, mode=ModeKeys.GLOBAL, regex=None, collection=None) -> list:
332336
self.maybe_refresh()
333337
ts = set()
334338
if step is None and mode == ModeKeys.GLOBAL:
@@ -340,17 +344,21 @@ def tensors(self, *, step=None, mode=ModeKeys.GLOBAL, regex=None, collection=Non
340344

341345
if regex is None and collection is None:
342346
return sorted(list(ts))
347+
elif regex is not None and collection is not None:
348+
raise ValueError("Only one of `regex` or `collection` can be passed to this method")
343349
else:
344-
xs = set()
345-
if regex is not None:
346-
xs.update(self._tensors_matching_regex(regex))
347350
if collection is not None:
348-
collection_tensors_saved = set(self._tensors.keys()).intersection(
349-
self._tensors_in_collection(collection)
350-
)
351-
xs.update(collection_tensors_saved)
352-
353-
return sorted(list(ts.intersection(xs)))
351+
xs = set(self._tensors.keys()).intersection(self._tensors_in_collection(collection))
352+
matching_tensors_saved = ts.intersection(xs)
353+
if len(matching_tensors_saved) == 0:
354+
coll_name = self._parse_collection_name(collection)
355+
self.logger.warning(f"No tensors from the collection {coll_name} were saved")
356+
else:
357+
xs = self._tensors_matching_regex(regex)
358+
matching_tensors_saved = ts.intersection(xs)
359+
if len(matching_tensors_saved) == 0:
360+
self.logger.warning(f"No tensors matching the regex pattern given were saved")
361+
return sorted(list(matching_tensors_saved))
354362

355363
def _tensors_for_step(self, step, mode=ModeKeys.GLOBAL) -> list:
356364
step = self._mode_to_global[mode][step] if mode != ModeKeys.GLOBAL else step

tests/analysis/rules/test_rule_no_refresh.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def __init__(self, base_trial):
1717
super().__init__(base_trial=base_trial)
1818

1919
def set_required_tensors(self, step):
20-
for t in self.base_trial.tensors():
20+
for t in self.base_trial.tensor_names():
2121
self.req_tensors.add(t, steps=[step])
2222

2323
def invoke_at_step(self, step):

tests/analysis/trials/test_has_passed_step_scenarios.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -480,14 +480,14 @@ def test_override_if_too_many_steps_skipped():
480480
trial.last_index_token
481481
== "has_step_scenarios/too-many-steps-skipped/index/000000000/000000000009_worker_2.json"
482482
)
483-
trial.tensors()
483+
trial.tensor_names()
484484
assert trial.last_complete_step == 9
485485
assert (
486486
trial.last_index_token
487487
== "has_step_scenarios/too-many-steps-skipped/index/000000000/000000000009_worker_2.json"
488488
)
489-
trial.tensors()
490-
trial.tensors()
489+
trial.tensor_names()
490+
trial.tensor_names()
491491
assert trial.last_complete_step == 9
492492
assert (
493493
trial.last_index_token

tests/analysis/trials/test_modes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def test_mode_data():
5757
assert tr.has_passed_step(s + 1) == StepState.NOT_YET_AVAILABLE
5858
assert tr.has_passed_step(s + 1, mode=modes.TRAIN) == StepState.NOT_YET_AVAILABLE
5959

60-
assert len(tr.tensors()) == 1
60+
assert len(tr.tensor_names()) == 1
6161
assert len(tr.steps()) == 10
6262
assert len(tr.steps(mode=modes.TRAIN)) == 5
6363
assert len(tr.steps(mode=modes.EVAL)) == 5

tests/analysis/trials/test_refresh.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ def help_test_refresh(path):
5656
)
5757
tr = create_trial(path + trial_name)
5858

59-
assert "foo_" + str(num_tensors + 1) not in tr.tensors()
60-
assert "foo_1" in tr.tensors()
59+
assert "foo_" + str(num_tensors + 1) not in tr.tensor_names()
60+
assert "foo_1" in tr.tensor_names()
6161
assert len(tr.steps()) == num_steps
6262
assert len(tr.tensor("foo_1").steps()) == num_steps
6363

@@ -117,8 +117,8 @@ def help_test_no_refresh(path):
117117
)
118118
tr = create_trial(path + trial_name)
119119

120-
assert "foo_" + str(num_tensors + 1) not in tr.tensors()
121-
assert "foo_1" in tr.tensors()
120+
assert "foo_" + str(num_tensors + 1) not in tr.tensor_names()
121+
assert "foo_1" in tr.tensor_names()
122122
assert len(tr.steps()) == num_steps
123123
assert len(tr.tensor("foo_1").steps()) == num_steps
124124

tests/analysis/trials/test_tensors_api.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
# Third Party
66
import numpy as np
7+
import pytest
78
from tests.analysis.utils import generate_data
89

910
# First Party
@@ -42,11 +43,14 @@ def test_tensors(out_dir):
4243
tr.collection("test").add_tensor_name("boo_5")
4344
tr.collection("test").add_tensor_name("boo_6")
4445
tr.collection("test").add_tensor_name("boo_17") # missing tensor
45-
print(tr.tensors())
46-
assert len(tr.tensors()) == num_tensors * 2
47-
assert len(tr.tensors(regex="foo")) == num_tensors
48-
assert len(tr.tensors(collection="test")) == num_tensors + 2
49-
assert len(tr.tensors(collection=tr.collection("test"))) == num_tensors + 2
46+
print(tr.tensor_names())
47+
assert len(tr.tensor_names()) == num_tensors * 2
48+
assert len(tr.tensor_names(regex="foo")) == num_tensors
49+
assert len(tr.tensor_names(collection="test")) == num_tensors + 2
50+
assert len(tr.tensor_names(collection=tr.collection("test"))) == num_tensors + 2
51+
52+
with pytest.raises(ValueError):
53+
tr.tensor_names(collection=tr.collection("test"), regex="a")
5054

5155

5256
def test_mode_data():
@@ -78,11 +82,11 @@ def test_mode_data():
7882
)
7983
fw.close()
8084

81-
assert trial.tensors() == ["arr_1", "arr_2"]
82-
assert trial.tensors(step=0) == ["arr_1"]
83-
assert trial.tensors(step=1) == ["arr_2"]
84-
assert trial.tensors(step=0, mode=modes.TRAIN) == ["arr_1"]
85-
assert trial.tensors(step=0, mode=modes.EVAL) == ["arr_2"]
85+
assert trial.tensor_names() == ["arr_1", "arr_2"]
86+
assert trial.tensor_names(step=0) == ["arr_1"]
87+
assert trial.tensor_names(step=1) == ["arr_2"]
88+
assert trial.tensor_names(step=0, mode=modes.TRAIN) == ["arr_1"]
89+
assert trial.tensor_names(step=0, mode=modes.EVAL) == ["arr_2"]
8690

87-
assert trial.tensors(mode=modes.TRAIN) == ["arr_1"]
88-
assert trial.tensors(mode=modes.EVAL) == ["arr_2"]
91+
assert trial.tensor_names(mode=modes.TRAIN) == ["arr_1"]
92+
assert trial.tensor_names(mode=modes.EVAL) == ["arr_2"]

tests/analysis/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ def generate_data(
4343

4444

4545
def check_trial(trial_obj, num_steps, num_tensors):
46-
assert len(trial_obj.tensors()) == num_tensors
47-
for t in trial_obj.tensors():
46+
assert len(trial_obj.tensor_names()) == num_tensors
47+
for t in trial_obj.tensor_names():
4848
assert len(trial_obj.tensor(t).steps()) == num_steps
4949
for s in trial_obj.tensor(t).steps():
5050
v = trial_obj.tensor(t).value(s)

tests/core/test_handler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self):
2929
)
3030
]
3131

32-
# input to get_index_for_tensors is a dict {path:{tensornames:[step_nums]}}
32+
# input to get_index_for_tensors is a dict {path:{tensor_names:[step_nums]}}
3333
# output of that fn is dict {path:{tname:[(step_num, TensorLocation)]}}
3434
def get_index_for_tensors(self, t_dict):
3535
dict_to_return = dict()

tests/core/test_hook_save_scalar.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,11 +179,11 @@ def check_trials(out_dir, save_steps, coll_name, saved_scalars=None):
179179
"""
180180
trial = create_trial(path=out_dir, name="test output")
181181
assert trial
182-
tensor_list = set(trial.tensors()) & set(trial.tensors(collection=coll_name))
182+
tensor_list = set(trial.tensor_names()) & set(trial.tensor_names(collection=coll_name))
183183
for tname in tensor_list:
184184
if tname not in saved_scalars:
185185
assert len(trial.tensor(tname).steps()) == len(save_steps)
186-
scalar_list = trial.tensors(regex="^scalar")
186+
scalar_list = trial.tensor_names(regex="^scalar")
187187
if scalar_list:
188188
assert len(set(saved_scalars) & set(scalar_list)) == len(saved_scalars)
189189

tests/mxnet/test_hook_all_zero.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ def test_hook_all_zero(hook=None, out_dir=None):
3535
assert tr
3636
assert len(tr.steps()) == 4
3737

38-
tnames = tr.tensors(regex="conv._input")
38+
tnames = tr.tensor_names(regex="conv._input")
3939
print(tnames)
40-
tname = tr.tensors(regex="conv._input")[0]
40+
tname = tr.tensor_names(regex="conv._input")[0]
4141
print(tname)
4242
print(tr.tensor(tname).steps())
4343
conv_tensor_value = tr.tensor(tname).value(step_num=0)

tests/mxnet/test_hook_loss_collection.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ def test_loss_collection_default():
2727
assert tr
2828
assert len(tr.steps()) == 4
2929

30-
print(tr.tensors())
31-
tname = tr.tensors(regex=".*loss")[0]
30+
print(tr.tensor_names())
31+
tname = tr.tensor_names(regex=".*loss")[0]
3232
loss_tensor = tr.tensor(tname)
3333
loss_val = loss_tensor.value(step_num=1)
3434
assert len(loss_val) > 0
@@ -51,8 +51,8 @@ def test_loss_collection_with_no_other_collections():
5151
assert tr
5252
assert len(tr.steps()) == 4
5353

54-
print(tr.tensors())
55-
tname = tr.tensors(regex=".*loss")[0]
54+
print(tr.tensor_names())
55+
tname = tr.tensor_names(regex=".*loss")[0]
5656
loss_tensor = tr.tensor(tname)
5757
loss_val = loss_tensor.value(step_num=1)
5858
assert len(loss_val) > 0

tests/mxnet/test_hook_reduce_config.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ def test_save_config(hook=None, out_dir=None):
5454
assert tr
5555
assert len(tr.steps()) == 7
5656

57-
print(tr.tensors())
58-
tname = tr.tensors(regex="conv\d+_weight")[0]
57+
print(tr.tensor_names())
58+
tname = tr.tensor_names(regex="conv\d+_weight")[0]
5959
# Global reduction with max and mean
6060
weight_tensor = tr.tensor(tname)
6161
max_val = weight_tensor.reduction_value(step_num=1, abs=False, reduction_name="max")
@@ -64,15 +64,15 @@ def test_save_config(hook=None, out_dir=None):
6464
assert mean_val != None
6565

6666
# custom reduction at step 4 with reduction = 'min' and abs reduction = 'max'
67-
tname = tr.tensors(regex="conv\d+_relu_input_0")[0]
67+
tname = tr.tensor_names(regex="conv\d+_relu_input_0")[0]
6868
relu_input = tr.tensor(tname)
6969
min_val = relu_input.reduction_value(step_num=4, abs=False, reduction_name="min")
7070
assert min_val != None
7171
abs_max_val = relu_input.reduction_value(step_num=4, abs=True, reduction_name="max")
7272
assert abs_max_val != None
7373

7474
# Custom reduction with normalization
75-
tname = tr.tensors(regex="flatten\d+_input_0")[0]
75+
tname = tr.tensor_names(regex="flatten\d+_input_0")[0]
7676
flatten_input = tr.tensor(tname)
7777
l1_norm = flatten_input.reduction_value(step_num=4, abs=False, reduction_name="l1")
7878
assert l1_norm != None

tests/mxnet/test_hook_save_all.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,10 @@ def test_save_all(hook=None, out_dir=None):
2121
print("Registering the hook with out_dir {}".format(out_dir))
2222
hook = t_hook(out_dir=out_dir, save_config=save_config, save_all=True)
2323
run_mnist_gluon_model(hook=hook, num_steps_train=7, num_steps_eval=5)
24-
# assert for steps and tensornames
24+
# assert for steps and tensor_names
2525
print("Created the trial with out_dir {}".format(out_dir))
2626
tr = create_trial(out_dir)
27-
tensor_list = tr.tensors()
27+
tensor_list = tr.tensor_names()
2828
assert tr
2929
assert len(tr.steps()) == 4
3030
# some tensor names, like input and output, can't be retrieved from training session, so here we only assert for tensor numbers

tests/mxnet/test_modes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,15 @@ def test_modes(hook=None, path=None):
3636
assert len(tr.steps(mode=modes.EVAL)) == 2, tr.steps()
3737

3838
# Ensure that the gradients are available in TRAIN modes only.
39-
grad_tns_name = tr.tensors(regex="^gradient.")[0]
39+
grad_tns_name = tr.tensor_names(regex="^gradient.")[0]
4040
grad_tns = tr.tensor(grad_tns_name)
4141
grad_train_steps = grad_tns.steps(mode=modes.TRAIN)
4242
grad_eval_steps = grad_tns.steps(mode=modes.EVAL)
4343
assert len(grad_train_steps) == 3
4444
assert grad_eval_steps == []
4545

4646
# Ensure that the weights are available in TRAIN and EVAL modes.
47-
wt_tns_name = tr.tensors(regex="conv\d+_weight")[0]
47+
wt_tns_name = tr.tensor_names(regex="conv\d+_weight")[0]
4848
wt_tns = tr.tensor(wt_tns_name)
4949
wt_train_steps = wt_tns.steps(mode=modes.TRAIN)
5050
wt_eval_steps = wt_tns.steps(mode=modes.EVAL)

0 commit comments

Comments
 (0)