API Reference
fitstream
Event
Bases: dict[str, Any]
Per-epoch event emitted by fit/stream utilities.
This is a regular dict with some overloads which exists solely to as a hint for users and IDE autocomplete engines what to expect.
Source code in src/fitstream/events.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
augment(fn)
Create a transform that merges extra keys into each event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[dict[str, Any]], dict[str, Any] | None]
|
Function called for each event. The returned mapping is shallow-merged
into the event. Returning |
required |
Returns:
| Type | Description |
|---|---|
Transform
|
A transform that accepts an event stream and yields augmented events. |
Example
add_error = augment( ... lambda event: {"error": event["pred"] - event["target"]} if "pred" in event else None ... ) events = [{"pred": 3.0, "target": 2.5}, {"target": 1.0}] list(add_error(events)) [{'pred': 3.0, 'target': 2.5, 'error': 0.5}, {'target': 1.0}]
Source code in src/fitstream/fit.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
collect(events, *, include=None, exclude=None)
Collect an event stream into a list of filtered event dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
Iterable[dict[str, Any]]
|
Input event stream. |
required |
include
|
Sequence[str] | None
|
Optional list of keys to keep. When provided, only these keys are
copied into each collected event. |
None
|
exclude
|
Sequence[str] | None
|
Optional list of keys to drop. When |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
A list of shallow-copied event dicts after applying the requested filtering. |
Example
events = [ ... {"step": 1, "train_loss": 0.5, "model": object()}, ... {"step": 2, "train_loss": 0.4, "model": object()}, ... ] collect(events) [{'step': 1, 'train_loss': 0.5}, {'step': 2, 'train_loss': 0.4}] collect(events, include=["step"]) [{'step': 1}, {'step': 2}]
Notes
- Provide only one of
includeorexclude; passing both raisesValueError. - The input iterable is consumed.
- Missing keys named in
includeare ignored.
Source code in src/fitstream/sinks.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
collect_jsonl(events, dest, *, include=None, exclude=None)
Write an event stream to JSON Lines format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
Iterable[dict[str, Any]]
|
Input event stream. |
required |
dest
|
str | Path | TextIO
|
Output destination. May be a filesystem path or an open text-mode file
object with a |
required |
include
|
Sequence[str] | None
|
Optional list of keys to keep in each JSON object. |
None
|
exclude
|
Sequence[str] | None
|
Optional list of keys to drop. When |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
Example
import io buffer = io.StringIO() events = [{"step": 1, "train_loss": 0.5, "model": object()}] collect_jsonl(events, buffer) buffer.getvalue() '{"step": 1, "train_loss": 0.5}\n'
Notes
- Provide only one of
includeorexclude; passing both raisesValueError. - The input iterable is consumed.
- Remaining event values must be JSON-serializable by
json.dumps. - When
destis a path, the file is opened in text write mode and overwritten.
Source code in src/fitstream/sinks.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
collect_pd(events, *, include=None, exclude=None)
Collect an event stream into a pandas DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
events
|
Iterable[dict[str, Any]]
|
Input event stream. |
required |
include
|
Sequence[str] | None
|
Optional list of keys to keep in each row. |
None
|
exclude
|
Sequence[str] | None
|
Optional list of keys to drop. When |
None
|
Returns:
| Type | Description |
|---|---|
|
A pandas |
Example
df = collect_pd( ... [{"step": 1, "train_loss": 0.5, "model": object()}], ... include=["step", "train_loss"], ... ) list(df.columns) ['step', 'train_loss']
Notes
- Provide only one of
includeorexclude; passing both raisesValueError. - The input iterable is consumed.
pandasis an optional dependency; if it is not installed, this function raisesImportError.
Source code in src/fitstream/sinks.py
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
early_stop(key, patience, *, mode='min', min_delta=0.0)
Yield events until the metric stops improving for patience steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Event key containing the monitored metric. |
required |
patience
|
int
|
Number of consecutive non-improving events tolerated before stopping. |
required |
mode
|
Literal['min', 'max']
|
Improvement direction. |
'min'
|
min_delta
|
float
|
Minimum absolute change required to count as an improvement. |
0.0
|
Use as a pipe stage:
pipe(events, early_stop(key="val_loss", patience=10))
Source code in src/fitstream/fit.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
ema(key, *, decay=None, half_life=None, out_key=None, bias_correction=True)
Create a stage that adds an exponential moving average of key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Event key to smooth. Each event in the input stream must contain this key,
and its value must be convertible with |
required |
decay
|
float | None
|
Exponential decay factor in |
None
|
half_life
|
float | None
|
Positive half-life used to derive the decay factor as
|
None
|
out_key
|
str | None
|
Event key used for the smoothed value. Defaults to |
None
|
bias_correction
|
bool
|
Whether to divide by |
True
|
Returns:
| Type | Description |
|---|---|
Transform
|
A transform stage that yields each input event with one additional key containing |
Transform
|
the EMA of |
Example
events = [ ... {"step": 1, "loss": 10.0}, ... {"step": 2, "loss": 20.0}, ... {"step": 3, "loss": 30.0}, ... ] smoothed = list(pipe(events, ema("loss", decay=0.5))) [(event["step"], round(event["loss_ema"], 4)) for event in smoothed][(1, 10.0), (2, 16.6667), (3, 24.2857)]
Notes
- Exactly one of
decayorhalf_lifemust be provided. - The update rule is
m = decay * m + (1 - decay) * xwithminitialized to0. - If an event is missing
key, iteration raisesKeyError. - If
event[key]cannot be converted withfloat(...), iteration raises the corresponding conversion error (typicallyTypeErrororValueError). - The returned event is produced with
event | {out_key: ...}, so an existing value atout_keyis overwritten.
Source code in src/fitstream/fit.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
epoch_stream(train_data, model, optimizer, loss_fn, *, batch_size=1, shuffle=True, last_label=True, generator=None, extra=None, step_offset=0)
Yield per-epoch training events from in-memory tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_data
|
Sequence[Tensor]
|
Tuple of tensors with batch dimension first. When |
required |
model
|
Module
|
PyTorch model to train. |
required |
optimizer
|
Optimizer
|
Optimizer instance constructed with the model parameters. |
required |
loss_fn
|
Callable[..., Tensor]
|
Loss function. Called as |
required |
batch_size
|
int
|
Number of samples per batch. |
1
|
shuffle
|
bool
|
Whether to shuffle samples before batching. |
True
|
last_label
|
bool
|
Whether the last tensor in |
True
|
generator
|
Generator | None
|
Optional torch.Generator forwarded to |
None
|
extra
|
dict[str, Any] | None
|
Optional dict to be added to each event. |
None
|
step_offset
|
int
|
Integer added to the default 1-based epoch index in emitted events.
With |
0
|
Example
x = torch.tensor([[1.0], [2.0]]) y = torch.tensor([[1.0], [2.0]]) model = nn.Linear(1, 1, bias=False) with torch.no_grad(): ... _ = model.weight.zero_() optimizer = torch.optim.SGD(model.parameters(), lr=0.0) stream = epoch_stream((x, y), model, optimizer, nn.MSELoss(), batch_size=2, shuffle=False) event = next(stream) event["step"], event["train_loss"] (1, 2.5)
Notes
This function assumes the model and all tensors are already on the same device. It does not copy tensors or take snapshots of model weights. Moreover, the function assumes that the loss function averages over the batch dimension.
Source code in src/fitstream/fit.py
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
iter_batches(*tensors, batch_size=1, shuffle=True, generator=None)
Yields batches from tensors, optionally shuffled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*tensors
|
Tensor
|
One or more tensors that share the same first dimension (sample axis). Each yielded batch contains slices from each tensor aligned on that axis. |
()
|
batch_size
|
int
|
Number of samples per batch. The final batch may be smaller if the sample count is not divisible by the batch size. |
1
|
shuffle
|
bool
|
Whether to shuffle samples before batching. Shuffling uses the device of the first tensor. |
True
|
generator
|
Generator | None
|
Optional torch.Generator for deterministic shuffling. |
None
|
Yields:
| Type | Description |
|---|---|
Iterable[tuple[Tensor, ...]]
|
Tuples of tensors, one per input tensor, representing a batch. |
Example
features = torch.arange(12).reshape(6, 2) targets = torch.arange(6) batches = iter_batches(features, targets, batch_size=4, shuffle=False) x_batch, y_batch = next(batches) x_batch.shape, y_batch.shape (torch.Size([4, 2]), torch.Size([4]))
Notes
This function assumes all tensors have the same number of samples along dimension 0 and live on the same device. It does not perform explicit validation.
Source code in src/fitstream/batching.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | |
pipe(stream, *stages)
Compose stream transforms left-to-right.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stream
|
Iterable[dict[str, Any]]
|
Input event stream. |
required |
stages
|
Transform
|
Transform functions applied in order. |
()
|
Returns:
| Type | Description |
|---|---|
Iterable[dict[str, Any]]
|
The transformed event stream. |
Example
events = [{"x": 1}, {"x": 2}] add_one = augment(lambda event: {"x": event["x"] + 1}) add_double = augment(lambda event: {"double": 2 * event["x"]}) list(pipe(events, add_one, add_double)) [{'x': 2, 'double': 4}, {'x': 3, 'double': 6}]
stream = pipe( ... [{"loss": 3.0}, {"loss": 2.0}, {"loss": 1.0}], ... ema("loss", decay=0.5, bias_correction=False), ... take(2), ... ) list(stream) [{'loss': 3.0, 'loss_ema': 1.5}, {'loss': 2.0, 'loss_ema': 1.75}]
Source code in src/fitstream/fit.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
print_keys(*keys, precision=4, include_step=True, step_key='step')
Create an event callback that prints selected keys in one compact line.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
str
|
Event keys to print. |
()
|
precision
|
int
|
Number of digits after the decimal for numeric values. |
4
|
include_step
|
bool
|
Whether to include |
True
|
step_key
|
str
|
Event key used for the step prefix. |
'step'
|
Example
events = [ ... {"step": 1, "train_loss": 0.9, "lr": 0.01}, ... {"step": 2, "train_loss": 0.8, "lr": 0.01}, ... ] stream = pipe(events, tap(print_keys("train_loss", "lr", precision=3))) list(stream) step=0001 train_loss=0.900 lr=0.010 step=0002 train_loss=0.800 lr=0.010 [{'step': 1, 'train_loss': 0.9, 'lr': 0.01}, {'step': 2, 'train_loss': 0.8, 'lr': 0.01}]
Notes
- Scalar tensors are detached, moved to CPU, converted to
float, and formatted withprecisiondigits after the decimal point. boolvalues are printed asTrueorFalsewithout numeric formatting.intandfloatvalues are formatted withprecisiondigits after the decimal point.- Other values are printed with
str(value). - Missing requested keys are printed as
key=NA. - When
include_step=Trueandstep_keyis present, it is printed first. If it can be cast toint, it is zero-padded to 4 digits; otherwise its original string form is used.
Source code in src/fitstream/fit.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
take(n)
Limit an event stream to the first n events.
Can be used directly on a stream or as a pipe stage:
take(10)(events)pipe(events, take(10))
Source code in src/fitstream/fit.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
tap(fn, *, every=1, start=1)
Create a stage that performs side effects and yields events unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn
|
Callable[[dict[str, Any]], Any]
|
Callback applied to selected events. |
required |
every
|
int
|
Call |
1
|
start
|
int
|
1-based event index at which callback scheduling starts. |
1
|
Source code in src/fitstream/fit.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
tick(fn)
Create a stage that runs a no-arg callback per event and yields events unchanged.
Source code in src/fitstream/fit.py
198 199 200 201 202 203 204 205 206 207 208 209 210 | |
validation_loss(val_data, loss_fn, *, key='val_loss', last_label=True)
Create an augmentation that computes validation loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
val_data
|
Sequence[Tensor]
|
Tuple of tensors with batch dimension first. When |
required |
loss_fn
|
Callable[..., Tensor]
|
Loss function called as |
required |
key
|
str
|
Name of the key to store the computed loss under. |
'val_loss'
|
last_label
|
bool
|
Whether the last tensor in |
True
|
Notes
Assumes the model and validation tensors are already on the same device. Validation is computed on the full validation set (no batching).
Source code in src/fitstream/augmentations.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |