torchness 2.1.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {torchness-2.1.0 → torchness-2.2.0}/PKG-INFO +1 -1
  2. {torchness-2.1.0 → torchness-2.2.0}/setup.py +1 -1
  3. torchness-2.2.0/tests/test_batcher.py +174 -0
  4. torchness-2.2.0/tests/test_ckpt.py +63 -0
  5. torchness-2.2.0/tests/test_devices.py +166 -0
  6. torchness-2.2.0/tests/test_encoders.py +550 -0
  7. torchness-2.2.0/tests/test_grad_clipping.py +66 -0
  8. torchness-2.2.0/tests/test_initialize.py +10 -0
  9. torchness-2.2.0/tests/test_layers.py +86 -0
  10. torchness-2.2.0/tests/test_motorch.py +452 -0
  11. torchness-2.2.0/tests/test_scaled.py +106 -0
  12. torchness-2.2.0/tests/test_tbwr.py +30 -0
  13. torchness-2.2.0/tests/test_tools.py +18 -0
  14. torchness-2.2.0/tests/test_zeroes_processor.py +45 -0
  15. torchness-2.2.0/torchness/base.py +26 -0
  16. torchness-2.2.0/torchness/batcher.py +450 -0
  17. {torchness-2.1.0 → torchness-2.2.0}/torchness/ckpt.py +3 -5
  18. {torchness-2.1.0 → torchness-2.2.0}/torchness/devices.py +35 -49
  19. {torchness-2.1.0 → torchness-2.2.0}/torchness/encoders.py +13 -14
  20. torchness-2.2.0/torchness/grad_clipping.py +87 -0
  21. {torchness-2.1.0 → torchness-2.2.0}/torchness/layers.py +2 -3
  22. {torchness-2.1.0 → torchness-2.2.0}/torchness/models/simple_feats_classifier.py +8 -7
  23. {torchness-2.1.0 → torchness-2.2.0}/torchness/models/simple_text_classifier.py +15 -14
  24. {torchness-2.1.0 → torchness-2.2.0}/torchness/models/text_embbeder.py +12 -10
  25. {torchness-2.1.0 → torchness-2.2.0}/torchness/motorch.py +118 -166
  26. {torchness-2.1.0 → torchness-2.2.0}/torchness/nnmodule.py +32 -54
  27. {torchness-2.1.0 → torchness-2.2.0}/torchness/onnx_export.py +10 -11
  28. torchness-2.2.0/torchness/scaled.py +112 -0
  29. {torchness-2.1.0 → torchness-2.2.0}/torchness/tbwr.py +3 -4
  30. {torchness-2.1.0 → torchness-2.2.0}/torchness/tools.py +31 -11
  31. {torchness-2.1.0 → torchness-2.2.0}/torchness/zeroes_processor.py +9 -10
  32. {torchness-2.1.0 → torchness-2.2.0}/torchness.egg-info/PKG-INFO +1 -1
  33. {torchness-2.1.0 → torchness-2.2.0}/torchness.egg-info/SOURCES.txt +2 -2
  34. torchness-2.1.0/tests/test_batcher.py +0 -187
  35. torchness-2.1.0/tests/test_ckpt.py +0 -77
  36. torchness-2.1.0/tests/test_devices.py +0 -159
  37. torchness-2.1.0/tests/test_encoders.py +0 -552
  38. torchness-2.1.0/tests/test_grad_clipping.py +0 -74
  39. torchness-2.1.0/tests/test_initialize.py +0 -16
  40. torchness-2.1.0/tests/test_layers.py +0 -92
  41. torchness-2.1.0/tests/test_motorch.py +0 -624
  42. torchness-2.1.0/tests/test_scaled_LR.py +0 -19
  43. torchness-2.1.0/tests/test_tbwr.py +0 -33
  44. torchness-2.1.0/tests/test_tools.py +0 -27
  45. torchness-2.1.0/tests/test_zeroes_processor.py +0 -48
  46. torchness-2.1.0/torchness/base.py +0 -19
  47. torchness-2.1.0/torchness/batcher.py +0 -461
  48. torchness-2.1.0/torchness/grad_clipping.py +0 -152
  49. torchness-2.1.0/torchness/scaled_LR.py +0 -59
  50. {torchness-2.1.0 → torchness-2.2.0}/README.md +0 -0
  51. {torchness-2.1.0 → torchness-2.2.0}/setup.cfg +0 -0
  52. {torchness-2.1.0 → torchness-2.2.0}/torchness/__init__.py +0 -0
  53. {torchness-2.1.0 → torchness-2.2.0}/torchness/initialize.py +0 -0
  54. {torchness-2.1.0 → torchness-2.2.0}/torchness/models/__init__.py +0 -0
  55. {torchness-2.1.0 → torchness-2.2.0}/torchness.egg-info/dependency_links.txt +0 -0
  56. {torchness-2.1.0 → torchness-2.2.0}/torchness.egg-info/requires.txt +0 -0
  57. {torchness-2.1.0 → torchness-2.2.0}/torchness.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: torchness
3
- Version: 2.1.0
3
+ Version: 2.2.0
4
4
  Summary: PyTorch tools
5
5
  Home-page: https://github.com/piteren/torchness.git
6
6
  Author: Piotr Niewinski
@@ -5,7 +5,7 @@ from pypaq.lipytools.files import get_requirements
5
5
 
6
6
  setup(
7
7
  name= 'torchness',
8
- version= 'v2.1.0',
8
+ version= 'v2.2.0',
9
9
  url= 'https://github.com/piteren/torchness.git',
10
10
  author= 'Piotr Niewinski',
11
11
  author_email= 'pioniewinski@gmail.com',
@@ -0,0 +1,174 @@
1
+ from pathlib import Path
2
+ from typing import Any
3
+
4
+ import numpy as np
5
+ import pytest
6
+ from ompr.runner import RunningWorker
7
+ from pypaq.lipytools.files import prep_folder, w_pickle, r_pickle, get_files
8
+ from pypaq.lipytools.stats import msmx
9
+
10
+ from torchness.batcher import DataBatcher, FilesBatcher, FilesBatcherMP, BATCHING_TYPES
11
+
12
+ TMP_DIR = Path(__file__).parent / '_tmp_batcher'
13
+ DATA_DIR = TMP_DIR / 'datafiles'
14
+
15
+
16
+ @pytest.fixture(autouse=True, scope='module')
17
+ def tmp_dir():
18
+ prep_folder(TMP_DIR, flush_non_empty=True)
19
+
20
+
21
+ def test_base_init():
22
+ data = {'input': np.random.rand(1000, 3)}
23
+ batcher = DataBatcher(data_TR=data) # type: ignore
24
+ nTR, nTS = batcher.get_data_size()
25
+ assert (nTR, nTS) == (1000, 0)
26
+ assert batcher.keys == ['input']
27
+
28
+ batcher = DataBatcher(data_TR=data, split_factor=0.2) # type: ignore
29
+ nTR, nTS = batcher.get_data_size()
30
+ assert (nTR, nTS) == (800, 200)
31
+
32
+ data_TS = {'input': np.random.rand(300, 3)}
33
+ batcher = DataBatcher(data_TR=data, data_TS=data_TS) # type: ignore
34
+ nTR, nTS = batcher.get_data_size()
35
+ assert (nTR, nTS) == (1000, 300)
36
+
37
+
38
+ def test_TS_batches():
39
+ data = {'input': np.random.rand(1000, 3)}
40
+ data_TS = {'input': np.random.rand(300, 3)}
41
+ batcher = DataBatcher(data_TR=data, data_TS=data_TS, batch_size=15, batch_size_TS_mul=2) # type: ignore
42
+ batches_TS = batcher.get_TS_batches()
43
+ assert len(batches_TS) == 10
44
+
45
+ data = {'input': np.random.rand(1000, 3)}
46
+ data_TS_named = {
47
+ 'test_A': {'input': np.random.rand(300, 3)},
48
+ 'test_B': {'input': np.random.rand(200, 3)},
49
+ }
50
+ batcher = DataBatcher(data_TR=data, data_TS=data_TS_named, batch_size=10, batch_size_TS_mul=2) # type: ignore
51
+ nTR, nTS = batcher.get_data_size()
52
+ assert (nTR, nTS) == (1000, 500)
53
+ batches_TS = batcher.get_TS_batches('test_B')
54
+ assert len(batches_TS) == 10
55
+
56
+
57
+ def test_coverage(
58
+ num_samples: int = 1000,
59
+ batch_size: int = 64,
60
+ num_batches: int = 1000):
61
+
62
+ for btype in BATCHING_TYPES:
63
+ print(f'\nstarts coverage tests of {btype}')
64
+
65
+ samples = np.arange(num_samples)
66
+ np.random.shuffle(samples)
67
+ data = {'samples': samples}
68
+ batcher = DataBatcher(data_TR=data, batch_size=batch_size, batching_type=btype)
69
+
70
+ sL = []
71
+ n_b = 0
72
+ s_counter = {s: 0 for s in range(num_samples)}
73
+ for _ in range(num_batches):
74
+ sL += batcher.get_batch()['samples'].tolist()
75
+ n_b += 1
76
+ if len(set(sL)) == num_samples:
77
+ print(f'got full coverage with {n_b} batches')
78
+ for s in sL: s_counter[s] += 1
79
+ sL = []
80
+ n_b = 0
81
+
82
+ print(msmx(list(s_counter.values()))['string'])
83
+ print('*** finished coverage tests')
84
+
85
+
86
+ def test_seed():
87
+ c_size = 1000
88
+ b_size = 64
89
+
90
+ samples = np.arange(c_size)
91
+ np.random.shuffle(samples)
92
+ data = {'samples': samples}
93
+
94
+ batcher = DataBatcher(data, batch_size=b_size, batching_type='random')
95
+ sA = []
96
+ while len(sA) < 10000:
97
+ sA += batcher.get_batch()['samples'].tolist()
98
+ np.random.seed(len(sA))
99
+
100
+ batcher = DataBatcher(data, batch_size=b_size, batching_type='random')
101
+ sB = []
102
+ while len(sB) < 10000:
103
+ sB += batcher.get_batch()['samples'].tolist()
104
+ np.random.seed(10000000 - len(sB))
105
+
106
+ seed_is_fixed = all(sA[ix] == sB[ix] for ix in range(len(sA)))
107
+ print(f'seed is fixed: {seed_is_fixed}!')
108
+ assert seed_is_fixed
109
+
110
+
111
+ def _prepare_data_files(n_files: int = 10, nf_samples: int = 10_000):
112
+ prep_folder(DATA_DIR, flush_non_empty=True)
113
+ for n in range(n_files):
114
+ data = {
115
+ 'x': np.random.rand(nf_samples, 1000),
116
+ 'y': np.arange(nf_samples) + n * nf_samples}
117
+ w_pickle(data, f'{DATA_DIR}/f{n}.npp')
118
+
119
+
120
+ def test_FilesBatcher():
121
+ n_files = 10
122
+ nf_samples = 10_000
123
+ batch_size = 1_000
124
+ n_epochs = 5
125
+
126
+ def chunk_builder(file: str):
127
+ return r_pickle(file)
128
+
129
+ print('Preparing data files for FilesBatcher ..')
130
+ _prepare_data_files(n_files, nf_samples)
131
+
132
+ fb = FilesBatcher(
133
+ data_TR_chunk_fp= get_files(str(DATA_DIR)),
134
+ chunk_builder= chunk_builder,
135
+ batch_size= batch_size)
136
+
137
+ ys = []
138
+ for _ in range(int(n_files * nf_samples / batch_size * n_epochs)):
139
+ batch = fb.get_batch()
140
+ ys += batch['y'].tolist()
141
+
142
+ print(len(ys))
143
+ assert len(ys) == n_files * nf_samples * n_epochs
144
+ fb.exit()
145
+
146
+
147
+ def test_FilesBatcherMP():
148
+ n_files = 10
149
+ nf_samples = 10_000
150
+ batch_size = 1_000
151
+ n_epochs = 5
152
+
153
+ class CB(RunningWorker):
154
+ def process(self, file) -> Any:
155
+ return r_pickle(file)
156
+
157
+ print('Preparing data files for FilesBatcherMP ..')
158
+ _prepare_data_files(n_files, nf_samples)
159
+
160
+ fb = FilesBatcherMP(
161
+ data_TR_chunk_fp= get_files(str(DATA_DIR)),
162
+ data_TS_chunk_fp= None,
163
+ chunk_processor_class= CB,
164
+ n_workers= 10,
165
+ batch_size= batch_size)
166
+
167
+ ys = []
168
+ for _ in range(int(n_files * nf_samples / batch_size * n_epochs)):
169
+ batch = fb.get_batch()
170
+ ys += batch['y'].tolist()
171
+
172
+ print(len(ys))
173
+ assert len(ys) == n_files * nf_samples * n_epochs
174
+ fb.exit()
@@ -0,0 +1,63 @@
1
+ from pathlib import Path
2
+ import pytest
3
+ import torch
4
+ from pypaq.lipytools.files import prep_folder
5
+
6
+ from torchness.ckpt import mrg_ckpts, ckpt_nfo
7
+ from torchness.layers import LayDense
8
+ from torchness.motorch import Module, MOTorch
9
+
10
+ TMP_DIR = Path(__file__).parent / '_tmp_ckpt'
11
+ MOTORCH_DIR = TMP_DIR / 'motorch'
12
+
13
+
14
+ @pytest.fixture(autouse=True)
15
+ def tmp_dir():
16
+ prep_folder(MOTORCH_DIR, flush_non_empty=True)
17
+ MOTorch.SAVE_TOPDIR = str(MOTORCH_DIR)
18
+
19
+
20
+ class LinModel(Module):
21
+
22
+ def __init__(
23
+ self,
24
+ in_drop: float,
25
+ in_shape= 784,
26
+ out_shape= 10,
27
+ loss_func= torch.nn.functional.cross_entropy,
28
+ device= None,
29
+ dtype= None,
30
+ seed= 121,
31
+ **kwargs,
32
+ ):
33
+ Module.__init__(self, **kwargs)
34
+ self.in_drop_lay = torch.nn.Dropout(p=in_drop) if in_drop > 0 else None
35
+ self.lin = LayDense(in_features=in_shape, out_features=out_shape)
36
+ self.loss_func = loss_func
37
+
38
+ def forward(self, inp) -> dict:
39
+ if self.in_drop_lay is not None: inp = self.in_drop_lay(inp)
40
+ logits = self.lin(inp)
41
+ return {'logits': logits}
42
+
43
+ def loss(self, inp, lbl) -> dict:
44
+ out = self(inp)
45
+ out['loss'] = self.loss_func(out['logits'], lbl)
46
+ out['acc'] = self.accuracy(out['logits'], lbl)
47
+ return out
48
+
49
+
50
+ def test_mrg_ckpts():
51
+ model = MOTorch(name='modA', module_type=LinModel, in_drop=0.1, device=None)
52
+ model.save()
53
+ model = MOTorch(name='modB', module_type=LinModel, in_drop=0.1, device=-1)
54
+ model.save()
55
+
56
+ mrg_ckpts(
57
+ ckptA= f'{MOTORCH_DIR}/modA/modA.pt',
58
+ ckptB= f'{MOTORCH_DIR}/modB/modB.pt',
59
+ ckptM= f'{MOTORCH_DIR}/ckptM.pt',
60
+ ratio= 0.4,
61
+ noise= 0.1)
62
+
63
+ ckpt_nfo(f'{MOTORCH_DIR}/ckptM.pt')
@@ -0,0 +1,166 @@
1
+ import pytest
2
+ import torch
3
+
4
+ from torchness.devices import get_cuda_mem, get_available_cuda_id, report_cuda, _get_devices_torchness, get_devices, mask_cuda, mask_cuda_devices
5
+
6
+
7
+ def test_get_cuda_mem():
8
+ mem = get_cuda_mem()
9
+ print(mem)
10
+
11
+
12
+ def test_get_available_cuda_id():
13
+ av_cuda = get_available_cuda_id()
14
+ print(av_cuda)
15
+ av_cuda = get_available_cuda_id(mem_free=16000)
16
+ print(av_cuda)
17
+ av_cuda = get_available_cuda_id(load_max=0.5)
18
+ print(av_cuda)
19
+
20
+
21
+ def test_report_cuda():
22
+ print(report_cuda())
23
+
24
+
25
+ def test_get_devices_torchness():
26
+
27
+ d = _get_devices_torchness(0)
28
+ print(d)
29
+ assert d == [0]
30
+
31
+ d = _get_devices_torchness(1)
32
+ print(d)
33
+ assert d == [1]
34
+
35
+ d = _get_devices_torchness(13)
36
+ print(d)
37
+ assert d == [13]
38
+
39
+ d = _get_devices_torchness(-1)
40
+ print(d)
41
+ assert type(d) is list and (not d or len(d) == 1 and ((type(d[0]) is int and d[0] >= 0) or d[0] is None))
42
+
43
+ d = _get_devices_torchness([])
44
+ print(d)
45
+ assert d == [] or list(set([type(e) for e in d]))[0] in [int, None]
46
+
47
+ d = _get_devices_torchness(None)
48
+ print(d)
49
+ assert d == [None]
50
+
51
+ d = _get_devices_torchness(0.7)
52
+ print(len(d), d)
53
+ assert type(d) is list and len(d) >= 1 and d[0] is None
54
+
55
+ d = _get_devices_torchness(-0.5)
56
+ print(d)
57
+ assert d == [None]
58
+
59
+ d = _get_devices_torchness('all')
60
+ print(len(d), d)
61
+ assert type(d) is list and len(d) >= 1 and d[0] is None
62
+
63
+ d = _get_devices_torchness('cuda')
64
+ print(d)
65
+ assert d == [0]
66
+
67
+ d = _get_devices_torchness('cuda:0')
68
+ print(d)
69
+ assert d == [0]
70
+
71
+ d = _get_devices_torchness('cuda:1')
72
+ print(d)
73
+ assert d == [1]
74
+
75
+ d = torch.device('cpu')
76
+ d = _get_devices_torchness(d)
77
+ print(d)
78
+ assert d == [None]
79
+
80
+ d = torch.device('cuda')
81
+ d = _get_devices_torchness(d)
82
+ print(d)
83
+ assert d == [0]
84
+
85
+ d = torch.device('cuda:1')
86
+ d = _get_devices_torchness(d)
87
+ print(d)
88
+ assert d == [1]
89
+
90
+ d = torch.device('cuda:8')
91
+ d = _get_devices_torchness(d)
92
+ print(d)
93
+ assert d == [8]
94
+
95
+ d = _get_devices_torchness([0, 'all'])
96
+ print(d)
97
+ assert None in d and 0 in d and len(d) > 1
98
+
99
+ d = _get_devices_torchness([0, [], None])
100
+ print(len(d), d)
101
+ assert None in d and 0 in d and len(d) > 1
102
+
103
+ d = _get_devices_torchness([0, 2, [], None, -1])
104
+ print(len(d), d)
105
+ assert None in d and 0 in d and -1 not in d and len(d) > 1
106
+
107
+ d = _get_devices_torchness([1, 2, [], None, -1, 'all', 'cuda:0'])
108
+ print(len(d), d)
109
+ assert None in d and 0 in d and -1 not in d and len(d) > 3
110
+
111
+
112
+ def test_get_devices():
113
+ devices = get_devices()
114
+ print(devices)
115
+ devices = get_devices(devices=[])
116
+ print(devices)
117
+ devices = get_devices(devices=[], eventually_cpu=True)
118
+ print(devices)
119
+ devices = get_devices(devices=[0, 1])
120
+ print(devices)
121
+ devices = get_devices(devices=-1, eventually_cpu=True)
122
+ print(devices)
123
+ devices = get_devices(devices=[], mem_free=24000)
124
+ print(devices)
125
+
126
+
127
+ def test_get_devices_exceptions():
128
+ with pytest.raises(Exception):
129
+ get_devices('alll')
130
+ with pytest.raises(Exception):
131
+ get_devices((0, 1)) # type: ignore
132
+
133
+
134
+ def test_get_devices_torch():
135
+
136
+ d = get_devices(0)
137
+ print(d)
138
+ assert d == [] or 'cuda' in d[0]
139
+
140
+ d = get_devices(-1)
141
+ print(d)
142
+ assert d == [] or 'cuda' in d[0]
143
+
144
+ d = get_devices([])
145
+ print(d)
146
+ assert type(d) is list and (not d or type(d[0]) is str)
147
+
148
+ d = get_devices(None)
149
+ print(d)
150
+ assert d == ['cpu']
151
+
152
+ d = get_devices([0, 1, 'cuda:0', None])
153
+ print(d)
154
+ assert d == ['cuda:0', 'cuda:1', 'cuda:0', 'cpu']
155
+
156
+
157
+ def test_mask_cuda():
158
+ av_cuda = get_available_cuda_id()
159
+ print(av_cuda)
160
+ mask_cuda(av_cuda)
161
+
162
+
163
+ def test_mask_cuda_devices():
164
+ d = get_devices([None, 0, 0, 'cuda', None], torch_namespace=True)
165
+ print(d)
166
+ mask_cuda_devices(d)