florch 0.3.0__py3-none-any.whl

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.
florch/__init__.py ADDED
@@ -0,0 +1,34 @@
1
+ """Florch: Training framework with precise resume and stream-based data loading."""
2
+
3
+ from florch.config import TrainingConfig
4
+ from florch.training.job import TrainingJob, DataLoaders
5
+ from florch.model_trainer import ModelTrainer
6
+ from florch.checkpointing import CheckpointManager
7
+ from florch.grad_clipping import AdaptiveGradientClipper
8
+ from florch.streams import DataStream, RoundRobinStream, MultiStream, stream_to_loader
9
+ from florch.exceptions import UnexpectedValueDuringTrainingError
10
+ from florch import callbacks
11
+
12
+ __all__ = [
13
+ 'TrainingConfig',
14
+ 'TrainingJob',
15
+ 'DataLoaders',
16
+ 'ModelTrainer',
17
+ 'CheckpointManager',
18
+ 'AdaptiveGradientClipper',
19
+ 'DataStream',
20
+ 'RoundRobinStream',
21
+ 'MultiStream',
22
+ 'stream_to_loader',
23
+ 'BarecatReader',
24
+ 'UnexpectedValueDuringTrainingError',
25
+ 'callbacks',
26
+ ]
27
+
28
+
29
+ def __getattr__(name):
30
+ # BarecatReader needs the optional barecat package; import it only on use.
31
+ if name == 'BarecatReader':
32
+ from florch.barecat_reader import BarecatReader
33
+ return BarecatReader
34
+ raise AttributeError(f'module {__name__!r} has no attribute {name!r}')
florch/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.3.0'
22
+ __version_tuple__ = version_tuple = (0, 3, 0)
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,88 @@
1
+ """Worker-safe barecat reader for multi-process data loading."""
2
+
3
+ import os
4
+ from typing import Any, Optional
5
+
6
+ import barecat
7
+
8
+
9
+ class BarecatReader:
10
+ """Worker-safe barecat reader that auto-reinitializes per process.
11
+
12
+ When using multi-process data loading (fork or spawn), each worker process
13
+ needs its own file handles and database connections. This class automatically
14
+ detects when it's in a new process and reinitializes the underlying Barecat instance.
15
+
16
+ Example:
17
+ from barecat import DecodedView
18
+
19
+ images = BarecatReader('images.barecat')
20
+ annos = BarecatReader('annos.barecat')
21
+
22
+ def load_item(key, *, rng, group_rng):
23
+ d = DecodedView(annos)[key]
24
+ image = DecodedView(images)[d['impath']]
25
+ return dict(image=image, label=d['label'])
26
+ """
27
+
28
+ def __init__(self, path: str, **kwargs):
29
+ self.path = path
30
+ self.kwargs = kwargs
31
+ self._bc: Optional[barecat.Barecat] = None
32
+ self._pid: Optional[int] = None
33
+
34
+ def _ensure_open(self) -> barecat.Barecat:
35
+ """Open barecat if not open or if we're in a new process."""
36
+ pid = os.getpid()
37
+ if self._bc is None or self._pid != pid:
38
+ if self._bc is not None:
39
+ try:
40
+ self._bc.close()
41
+ except Exception:
42
+ pass
43
+ self._bc = barecat.Barecat(self.path, readonly=True, threadsafe=True, **self.kwargs)
44
+ self._pid = pid
45
+ return self._bc
46
+
47
+ def __getitem__(self, key: str) -> Any:
48
+ return self._ensure_open()[key]
49
+
50
+ def __contains__(self, key: str) -> bool:
51
+ return key in self._ensure_open()
52
+
53
+ def get(self, key: str, default: Any = None) -> Any:
54
+ bc = self._ensure_open()
55
+ try:
56
+ return bc[key]
57
+ except KeyError:
58
+ return default
59
+
60
+ def keys(self):
61
+ # Files only: iter_all_paths() is dirs UNION files, so it also yields the
62
+ # root '' and every directory, and reader[dirpath] then fails.
63
+ return self._ensure_open().index.iter_all_filepaths()
64
+
65
+ def __len__(self) -> int:
66
+ # num_files is a property; calling it raised TypeError on every len().
67
+ return self._ensure_open().index.num_files
68
+
69
+ def close(self):
70
+ if self._bc is not None:
71
+ self._bc.close()
72
+ self._bc = None
73
+ self._pid = None
74
+
75
+ def __del__(self):
76
+ self.close()
77
+
78
+ def __repr__(self):
79
+ return f"BarecatReader({self.path!r})"
80
+
81
+ def __getstate__(self):
82
+ return {'path': self.path, 'kwargs': self.kwargs}
83
+
84
+ def __setstate__(self, state):
85
+ self.path = state['path']
86
+ self.kwargs = state['kwargs']
87
+ self._bc = None
88
+ self._pid = None
florch/callbacks.py ADDED
@@ -0,0 +1,300 @@
1
+ from typing import Optional, Sequence, TYPE_CHECKING, Union
2
+
3
+ import florch.checkpointing
4
+ import florch.layers.batch_renorm
5
+ import simplepyutils as spu
6
+ import torch.distributed
7
+ import torch.nn as nn
8
+ if TYPE_CHECKING:
9
+ from florch.training.job import TrainingJob
10
+
11
+
12
+ class Callback:
13
+ def __init__(self):
14
+ self.job: Optional['TrainingJob'] = None
15
+ self.device = None
16
+
17
+ def on_train_batch_begin(self, step: int):
18
+ pass
19
+
20
+ def on_train_batch_end(self, step: int, logs: dict[str, float]):
21
+ pass
22
+
23
+ def on_train_begin(self, initial_step: int):
24
+ pass
25
+
26
+ def on_train_end(self, step: int):
27
+ pass
28
+
29
+ def needs_to_run_on_all_devices(self):
30
+ return False
31
+
32
+
33
+ class Checkpoint(Callback):
34
+ def __init__(self, ckpt_manager: florch.checkpointing.CheckpointManager):
35
+ super().__init__()
36
+ self.ckpt_manager = ckpt_manager
37
+
38
+ def on_train_batch_end(self, step, logs):
39
+ self.ckpt_manager.save(step + 1, check_interval=True)
40
+
41
+
42
+ class Progbar(Callback):
43
+ def __init__(self, total):
44
+ super().__init__()
45
+ self.total = total
46
+
47
+ def on_train_begin(self, initial_step):
48
+ self.pbar = spu.progressbar(initial=initial_step, total=self.total)
49
+
50
+ def on_train_batch_end(self, step, logs):
51
+ self.pbar.n = step
52
+ self.pbar.update(0)
53
+ self.pbar.set_postfix(logs)
54
+
55
+
56
+ class Wandb(Callback):
57
+ def __init__(self, logdir, config_dict, project_name, every_n_steps=30):
58
+ super().__init__()
59
+ self.every_n_steps = every_n_steps
60
+ self.logdir = logdir
61
+ self.config_dict = config_dict
62
+ self.project_name = project_name
63
+ self.accum_metrics = {}
64
+ self.n_accumulated = 0
65
+
66
+ def on_train_begin(self, initial_step):
67
+ import wandb.util
68
+
69
+ id_path = f"{self.logdir}/run_id"
70
+ try:
71
+ with open(id_path) as f:
72
+ run_id = f.read()
73
+ except FileNotFoundError:
74
+ run_id = wandb.util.generate_id()
75
+ with open(id_path, "w") as f:
76
+ f.write(str(run_id))
77
+ f.flush()
78
+
79
+ wandb.init(
80
+ name=self.logdir.split("/")[-1],
81
+ project=self.project_name,
82
+ config=self.config_dict,
83
+ dir=self.logdir,
84
+ id=run_id,
85
+ resume="allow",
86
+ settings=wandb.Settings(_service_wait=300, init_timeout=300),
87
+ )
88
+
89
+ def on_train_batch_end(self, step, logs):
90
+ import wandb
91
+
92
+ for key, value in logs.items():
93
+ if key not in self.accum_metrics:
94
+ self.accum_metrics[key] = 0.0
95
+ self.accum_metrics[key] += value
96
+ self.n_accumulated += 1
97
+
98
+ val_metrics = {k: v for k, v in logs.items() if k.startswith("val_")}
99
+
100
+ if step % self.every_n_steps == 0:
101
+ logs = {k: v / self.n_accumulated for k, v in self.accum_metrics.items()} | val_metrics
102
+ self.accum_metrics.clear()
103
+ self.n_accumulated = 0
104
+ else:
105
+ logs = val_metrics
106
+
107
+ if logs:
108
+ wandb.log(logs, step=int(step), commit=True)
109
+
110
+
111
+ class SyncBNStats(Callback):
112
+ def __init__(self):
113
+ super().__init__()
114
+
115
+ def on_train_batch_end(self, step, logs):
116
+ self.job.model.apply(self.sync_running_stats)
117
+
118
+ def needs_to_run_on_all_devices(self):
119
+ return True
120
+
121
+ @staticmethod
122
+ def has_any_bn_layers(module):
123
+ for m in module.modules():
124
+ if isinstance(
125
+ m,
126
+ (
127
+ nn.BatchNorm1d,
128
+ nn.BatchNorm2d,
129
+ nn.BatchNorm3d,
130
+ nn.LazyBatchNorm1d,
131
+ nn.LazyBatchNorm2d,
132
+ nn.LazyBatchNorm3d,
133
+ florch.layers.batch_renorm.BatchRenorm1d,
134
+ florch.layers.batch_renorm.BatchRenorm2d,
135
+ florch.layers.batch_renorm.BatchRenorm3d,
136
+ ),
137
+ ):
138
+ return True
139
+ return False
140
+
141
+ @staticmethod
142
+ def sync_running_stats(module):
143
+ if isinstance(
144
+ module,
145
+ (
146
+ nn.BatchNorm1d,
147
+ nn.BatchNorm2d,
148
+ nn.BatchNorm3d,
149
+ nn.LazyBatchNorm1d,
150
+ nn.LazyBatchNorm2d,
151
+ nn.LazyBatchNorm3d,
152
+ florch.layers.batch_renorm.BatchRenorm1d,
153
+ florch.layers.batch_renorm.BatchRenorm2d,
154
+ florch.layers.batch_renorm.BatchRenorm3d,
155
+ ),
156
+ ):
157
+ torch.distributed.all_reduce(module.running_mean, op=torch.distributed.ReduceOp.AVG)
158
+ torch.distributed.all_reduce(module.running_var, op=torch.distributed.ReduceOp.AVG)
159
+
160
+
161
+ class SwitchToInferenceModeCallback(Callback):
162
+ def __init__(self, step_to_switch_to_inference_mode, ckpt_manager):
163
+ super().__init__()
164
+ self.step_to_switch_to_inference_mode = step_to_switch_to_inference_mode
165
+ self.ckpt_manager = ckpt_manager
166
+
167
+ def on_train_batch_end(self, batch, logs):
168
+ if (
169
+ batch >= self.step_to_switch_to_inference_mode
170
+ and not self.job.train_in_inference_mode
171
+ ):
172
+ self.ckpt_manager.save(
173
+ batch + 1, name="ckpt_before_switch_to_inference_mode", check_interval=False
174
+ )
175
+ self.job.train_in_inference_mode = True
176
+
177
+ def needs_to_run_on_all_devices(self):
178
+ return True
179
+
180
+
181
+ class ConvMinMaxNormConstraint(Callback):
182
+ def __init__(
183
+ self, rate: float = 1.0, min_value: float = 0.0, max_value: float = 1.0, eps: float = 1e-7
184
+ ):
185
+ super().__init__()
186
+ self.rate = rate
187
+ self.min_value = min_value
188
+ self.max_value = max_value
189
+ self.eps = eps
190
+
191
+ def on_train_batch_end(self, step, logs):
192
+ with torch.no_grad():
193
+ self.job.model.apply(self.apply_constraint)
194
+
195
+ def apply_constraint(self, module: nn.Module):
196
+ if isinstance(module, nn.Conv2d) and module.weight is not None:
197
+ if module.groups == module.in_channels: # Depthwise Conv2D
198
+ module.weight.copy_(
199
+ self.minmax_norm(module.weight, dim=[-1, -2])
200
+ ) # Norm over h, w
201
+ else: # Standard Conv2D
202
+ module.weight.copy_(
203
+ self.minmax_norm(module.weight, dim=[-1, -2, -3])
204
+ ) # Norm over c_in, h, w
205
+
206
+ def minmax_norm(self, w: torch.Tensor, dim: Union[int, Sequence[int]]):
207
+ norms = torch.sqrt(torch.sum(torch.square(w), dim=dim, keepdim=True)) # Compute L2 norm
208
+ desired = (
209
+ self.rate * torch.clamp(norms, self.min_value, self.max_value)
210
+ + (1.0 - self.rate) * norms
211
+ )
212
+ return w * (desired / (norms + self.eps))
213
+
214
+ def needs_to_run_on_all_devices(self):
215
+ return True
216
+
217
+
218
+ class MinMaxNormConstraint(Callback):
219
+ def __init__(
220
+ self,
221
+ parameters: Sequence[nn.Parameter],
222
+ rate: float = 1.0,
223
+ min_value: float = 0.0,
224
+ max_value: float = 1.0,
225
+ dim: Optional[Union[int, Sequence[int]]] = None,
226
+ eps: float = 1e-7,
227
+ ):
228
+ super().__init__()
229
+ self.parameters = parameters
230
+ self.rate = rate
231
+ self.min_value = min_value
232
+ self.max_value = max_value
233
+ self.eps = eps
234
+ self.dim = dim
235
+
236
+ def on_train_batch_end(self, step, logs):
237
+ with torch.no_grad():
238
+ for p in self.parameters:
239
+ p.copy_(self.minmax_norm(p, dim=self.dim))
240
+
241
+ def minmax_norm(self, w: torch.Tensor, dim: Union[int, Sequence[int]]):
242
+ norms = torch.sqrt(torch.sum(torch.square(w), dim=dim, keepdim=True)) # Compute L2 norm
243
+ desired = (
244
+ self.rate * torch.clamp(norms, self.min_value, self.max_value)
245
+ + (1.0 - self.rate) * norms
246
+ )
247
+ return w * (desired / (norms + self.eps))
248
+
249
+ def needs_to_run_on_all_devices(self):
250
+ return True
251
+
252
+
253
+ class FreezeLayers(Callback):
254
+ def __init__(self, trainables: Sequence[Union[nn.Module, nn.Parameter]], unfreeze_step: int):
255
+ super().__init__()
256
+ self.unfreeze_step = unfreeze_step
257
+ self.trainables = trainables
258
+
259
+ def on_train_begin(self, initial_step: int):
260
+ requires_grad = initial_step >= self.unfreeze_step
261
+ for t in self.trainables:
262
+ t.requires_grad_(requires_grad)
263
+
264
+ def on_train_batch_begin(self, step, logs=None):
265
+ if step == self.unfreeze_step:
266
+ for t in self.trainables:
267
+ t.requires_grad_(True)
268
+
269
+ def needs_to_run_on_all_devices(self):
270
+ return True
271
+
272
+
273
+ class TransitionBatchNorm(Callback):
274
+ def __init__(
275
+ self,
276
+ transition_start: int,
277
+ transition_end: int,
278
+ ):
279
+ super().__init__()
280
+ self.transition_start = transition_start
281
+ self.transition_end = transition_end
282
+
283
+ def on_train_batch_begin(self, step: int):
284
+ from florch.util.misc import smootherstep
285
+ blend = smootherstep(
286
+ step, self.transition_start, x1=self.transition_end
287
+ )
288
+ for m in self.job.model.modules():
289
+ if isinstance(m, florch.layers.TransitionBatchNorm2d):
290
+ m.blend = blend
291
+
292
+ if step == self.transition_start:
293
+ for m in self.job.model.modules():
294
+ if isinstance(m, florch.layers.TransitionBatchNorm2d):
295
+ m.weight.requires_grad_(False)
296
+ m.bias.requires_grad_(False)
297
+
298
+
299
+ def needs_to_run_on_all_devices(self):
300
+ return True
@@ -0,0 +1,139 @@
1
+ import os
2
+ import os.path as osp
3
+ import time
4
+
5
+ import torch
6
+ from simplepyutils import logger
7
+
8
+
9
+ class CheckpointManager:
10
+ def __init__(
11
+ self,
12
+ model,
13
+ optimizer,
14
+ grad_clipper,
15
+ directory,
16
+ max_to_keep,
17
+ checkpoint_interval,
18
+ truncate_before_delete=False,
19
+ fsdp=False,
20
+ ):
21
+ self.fsdp = fsdp
22
+ self.model = model
23
+ self.optimizer = optimizer
24
+ self.grad_clipper = grad_clipper
25
+ self.directory = directory
26
+ self.max_to_keep = max_to_keep
27
+ os.makedirs(directory, exist_ok=True)
28
+ self.checkpoints = sorted(self._get_existing_checkpoints())
29
+ self.checkpoint_interval = checkpoint_interval
30
+ self.truncate_before_delete = truncate_before_delete
31
+ self._consecutive_failed_saves = 0
32
+
33
+ def _get_existing_checkpoints(self):
34
+ """Retrieve existing checkpoint paths sorted by modification time."""
35
+ return sorted(
36
+ [
37
+ osp.join(self.directory, ckpt)
38
+ for ckpt in os.listdir(self.directory)
39
+ if ckpt.endswith(".pth") and os.stat(osp.join(self.directory, ckpt)).st_size > 0
40
+ ],
41
+ key=osp.getmtime,
42
+ )
43
+
44
+ def save(self, step, name=None, check_interval=True, overwrite=False):
45
+ """Save a new checkpoint and remove old ones if exceeding max_to_keep."""
46
+
47
+ if check_interval and step % self.checkpoint_interval != 0:
48
+ return
49
+
50
+ if name is None:
51
+ name = f"ckpt-{step:07d}"
52
+
53
+ checkpoint_path = osp.join(self.directory, f"{name}.pth")
54
+ if not overwrite and osp.exists(checkpoint_path):
55
+ return
56
+
57
+ if self.fsdp:
58
+ from torch.distributed.checkpoint.state_dict import get_state_dict
59
+
60
+ model_state_dict, optimizer_state_dict = get_state_dict(self.model, self.optimizer)
61
+ else:
62
+ model_state_dict = self.model.state_dict()
63
+ optimizer_state_dict = self.optimizer.state_dict()
64
+
65
+ state = {
66
+ 'n_completed_steps': step,
67
+ 'model_state_dict': model_state_dict,
68
+ 'optimizer_state_dict': optimizer_state_dict,
69
+ 'grad_clipper_state_dict': self.grad_clipper.state_dict(),
70
+ }
71
+ # Write to a temp file and rename, so a failed save (e.g. transient Lustre I/O
72
+ # error) never leaves a truncated .pth behind as the "latest" checkpoint. Retry a
73
+ # few times; a periodic checkpoint that still fails is not worth killing the run.
74
+ tmp_path = checkpoint_path + '.tmp'
75
+ for i_attempt in range(3):
76
+ try:
77
+ torch.save(state, tmp_path)
78
+ os.replace(tmp_path, checkpoint_path)
79
+ self._consecutive_failed_saves = 0
80
+ break
81
+ except (OSError, RuntimeError) as e:
82
+ logger.warning(f'Checkpoint save attempt {i_attempt + 1} failed: {e}')
83
+ try:
84
+ os.remove(tmp_path)
85
+ except OSError:
86
+ pass
87
+ time.sleep(10)
88
+ else:
89
+ # A transient blip (e.g. group quota briefly exceeded) should not kill a
90
+ # long run, but persistently failing saves mean training can no longer be
91
+ # persisted at all - then burning compute is pointless: stop.
92
+ self._consecutive_failed_saves += 1
93
+ logger.warning(f'Giving up on saving checkpoint {checkpoint_path}.')
94
+ if self._consecutive_failed_saves >= 3:
95
+ raise RuntimeError(
96
+ f'{self._consecutive_failed_saves} consecutive checkpoint saves '
97
+ 'failed - storage appears persistently unavailable.'
98
+ )
99
+ return
100
+
101
+ self.checkpoints.append(checkpoint_path)
102
+ self.remove_old_checkpoints()
103
+
104
+ def remove_old_checkpoints(self):
105
+ while len(self.checkpoints) > self.max_to_keep:
106
+ path_to_delete = self.checkpoints.pop(0)
107
+ if self.truncate_before_delete:
108
+ # Truncate the checkpoint file before deleting it
109
+ with open(path_to_delete, 'wb') as f:
110
+ f.truncate()
111
+
112
+ os.remove(path_to_delete)
113
+
114
+ def load_latest(self):
115
+ """Load the latest checkpoint if available."""
116
+ if not self.checkpoints:
117
+ return None, 0 # No checkpoint found
118
+ latest_checkpoint = self.checkpoints[-1]
119
+ checkpoint = torch.load(latest_checkpoint)
120
+ self.model.load_state_dict(checkpoint['model_state_dict'])
121
+ self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
122
+ self.grad_clipper.load_state_dict(checkpoint['grad_clipper_state_dict'])
123
+ return latest_checkpoint, checkpoint['n_completed_steps']
124
+
125
+
126
+ def latest_checkpoint(directory):
127
+ """Retrieve the latest checkpoint in a directory."""
128
+ if directory is None or not osp.isdir(directory):
129
+ return None
130
+ checkpoints = sorted(
131
+ [
132
+ osp.join(directory, ckpt)
133
+ for ckpt in os.listdir(directory)
134
+ if osp.basename(ckpt).startswith('ckpt-')
135
+ and ckpt.endswith(".pth")
136
+ and os.stat(osp.join(directory, ckpt)).st_size > 0
137
+ ],
138
+ )
139
+ return checkpoints[-1] if checkpoints else None