hyrax.verbs.train_stream#
Attributes#
Classes#
Streaming training verb — loads the model once, trains on batches on demand. |
|
Context manager for streaming training. |
Module Contents#
- class TrainStream(config)[source]#
Bases:
hyrax.verbs.verb_registry.VerbStreaming training verb — loads the model once, trains on batches on demand.
Overall initialization for all verbs that saves the config
- description = 'Run streaming training: load the model once and train on batches interactively.'[source]#
- run() TrainStreamSession[source]#
Set up the model and return a session for streaming training.
- with hy.train_stream() as session:
- for batch, metrics in session:
print(metrics[“loss”])
Because a live stream is open-ended (no epochs, no length, no train/validate/test splits), this verb does not use the Ignite
create_trainer/trainer.run(..., max_epochs=...)path. Instead it reuses the same per-batch function the trainer’s engine calls (create_process_func()with"train_batch"), which already runs the model’s self-contained optimizer step, and drives it from the session loop.- Returns:
A context manager / session object. Iterate it (data-source driven) or call
session.train_batch(batch)(manual); callsession.close()when done to persist the final weights and get the trained model back.- Return type:
- Raises:
ValueError – If no
[data_request.train_stream]is configured.
- class TrainStreamSession(process_func, model, config, results_dir, data_loader=None, provider=None)[source]#
Context manager for streaming training.
Holds a loaded model and its optimizer. When constructed with a
data_loader(the data-source-driven path), the session is iterable and yields(batch, metrics)pairs as data arrives; otherwise feed batches yourself withtrain_batch().Each processed batch runs the model’s self-contained training step (
zero_grad→ forward → loss →backward→optimizer.step) and returns its metrics dict. Model weights are persisted periodically (save_weights_every) and always onclose().Warning
train_batch()/process()are not thread-safe. Do not call them concurrently.- __iter__()[source]#
Iterate the configured data source, training on each batch as it arrives.
- Yields:
tuple[dict, dict | None] – The collated input
batchand the trainingmetricsfor it (orNoneif the batch was skipped for being empty / smaller thanmin_batch_size).- Raises:
RuntimeError – If the session was created without a data source (no
[data_request.train_stream]configuration).
- _batch_num_samples(batch) int | None[source]#
Return the number of samples in a collated batch, or
Noneif unknown. batch should always be a dictionary at this point in the pipeline. And the key"object_id"is added by Hyrax to track the primary IDs of the samples, so it should always be present as well.
- process(batch: dict) dict | None[source]#
Run one training step on a single batch.
The batch is passed through the model’s
train_batch(which performs the full optimizer step) unless it is empty or smaller than the configuredmin_batch_size, in which case it is skipped.- Parameters:
batch (dict) – Must contain
"object_id"(list of str) and model-specific data fields.- Returns:
The training metrics (e.g.
{"loss": ...}), orNoneif the batch was skipped.- Return type:
dict | None
- Raises:
RuntimeError – If the session has already been closed.
- _log_metrics(result) None[source]#
Log per-batch metrics to TensorBoard and (if a run is active) MLflow.
- save_weights(file_name_suffix='') None[source]#
Persist the current model weights to the results directory.
- close()[source]#
Persist final weights, end logging, and return the trained model.
- Returns:
The trained model.
- Return type:
torch.nn.Module