๐Ÿงฐ Utils๏ƒ

Utilities for Torchmate Library

ProgressBar๏ƒ

class torchmate.utils.ProgressBar(total: int, bar_length: int = 30, fill: str = '=', prefix: str = '')[source]๏ƒ

Bases: object

A progress bar for tracking the progress of iterative tasks.

Displays a progress bar with percentage completion, elapsed time, estimated time remaining, and optional verbose text.

Example usage:

no_iter = 100
pb = ProgressBar(total=no_iter, prefix="Processing", bar_length=50)
for i in range(no_iter):
    pb.update(i + 1, message=f"Processing item {i + 1}")

Initialize the instance of ProgressBar class.

Parameters:
  • total (int) โ€“ Total number of iterations. Defaults to None.

  • bar_length (int, optional) โ€“ Length of the progress bar. Defaults to 30.

  • fill (str, optional) โ€“ Character used to fill the progress bar. Defaults to '='.

  • prefix (str, optional) โ€“ A text to display before the progress bar. Defaults to empty string "".

update(iteration: int, message: str = '') None[source]๏ƒ

Update the progress bar with current iteration and optional message text.

Parameters:
  • iteration (int) โ€“ Current iteration number.

  • message (str, optional) โ€“ Optional text to display. Defaults to empty string.

static format_time(duration_seconds: float) str[source]๏ƒ

Format a duration in seconds into a human-readable string.

Parameters:

duration_seconds (float) โ€“ Duration in seconds.

Returns:

Formatted time string (e.g., โ€œ1m 23sโ€, โ€œ45.67sโ€, โ€œ2h 35mโ€).

Return type:

str

Example usage:

formatted_time = ProgressBar.format_time(65.5)  # Returns "1:05"

RunningAverage๏ƒ

class torchmate.utils.RunningAverage[source]๏ƒ

Bases: object

A simple class that maintains the running average of a quantity

Example usage:

loss_avg = RunningAverage()
loss_avg.update(2)
loss_avg.update(4)
loss_avg() = 3  ## 2+4/2=3
update(val: int) None[source]๏ƒ

HistoryPlotter๏ƒ

class torchmate.utils.HistoryPlotter(trainer=None, history=None)[source]๏ƒ

Bases: object

A class for plotting training and validation metrics, including loss, learning rate, and any additional metrics provided by the training history.

Parameters:
  • trainer (Trainer, optional) โ€“ An instance of torchmate.trainer.Trainer containing the training history to be plotted.

  • history (Dict, optional) โ€“ A dictionary containing the training history data, with keys such as loss, lr, and other metric names.

Raises:

ValueError โ€“ If both trainer and history are None.

Notes

If both trainer and history are provided, the training history from trainer will take precedence.

Example usage:

# Using a Trainer object:
trainer = Trainer(...)
history = trainer.fit()
plotter = Plotter(trainer=trainer)
plotter.plot_all()


# Using a history dictionary returned from trainer.fit()
trainer = Trainer(...)
history = trainer.fit()
plotter = Plotter(history=history)
plotter.plot_all()

# Using a history dictionary:
history = {"loss": [...], "lr": [...], "some_metric": [...]}
plotter = Plotter(history=history)
plotter.plot_all()
static format_to_space_capitalized(text)[source]๏ƒ

Convert a string to space-separated capitalized words, handling various formats.

Parameters:

text โ€“ A string in any format (snake_case, camelCase, space-separated, etc.).

Returns:

A string with words separated by spaces and capitalized.

plot_all()[source]๏ƒ

Plot loss, learning rate and all available metrics.

plot_metrics()[source]๏ƒ

Plot the training and validation metrics.

plot_loss()[source]๏ƒ

Plot the training and validation loss.

plot_lr()[source]๏ƒ

Plot the learning rate over epochs.

COLOR๏ƒ

class torchmate.utils.COLOR[source]๏ƒ

Bases: object

BG = Background

Reference:

https://web.archive.org/web/20201214113226/http://ascii-table.com/ansi-escape-sequences.php

BLACK = '\x1b[30m'๏ƒ
RED = '\x1b[31m'๏ƒ
GREEN = '\x1b[32m'๏ƒ
YELLOW = '\x1b[33m'๏ƒ
BLUE = '\x1b[34m'๏ƒ
MAGENTA = '\x1b[35m'๏ƒ
CYAN = '\x1b[36m'๏ƒ
WHITE = '\x1b[37m'๏ƒ
PURPLE = '\x1b[95m'๏ƒ
BOLD = '\x1b[1m'๏ƒ
UNDERLINE = '\x1b[4m'๏ƒ
INVERSE = '\x1b[7m'๏ƒ
END = '\x1b[0m'๏ƒ
DEFAULT_BG = '\x1b[41m'๏ƒ
BLACK_BG = '\x1b[40m'๏ƒ
RED_BG = '\x1b[41m'๏ƒ
GREEN_BG = '\x1b[42m'๏ƒ
YELLOW_BG = '\x1b[43m'๏ƒ
BLUE_BG = '\x1b[44m'๏ƒ
MAGENTA_BG = '\x1b[45m'๏ƒ
CYAN_BG = '\x1b[46m'๏ƒ
WHITE_BG = '\x1b[47m'๏ƒ

colorize_text๏ƒ

torchmate.utils.colorize_text(text: str, fore_tuple: Tuple[int, int, int] = (0, 0, 0), back_tuple: Tuple[int, int, int] | None = None, bold_text: bool = False) str[source]๏ƒ

Return text formatted with specified foreground color, background color, and optional bold formatting.

Parameters:
  • text (str) โ€“ The text to be colorized.

  • fore_tuple (tuple, optional) โ€“ A tuple of RGB values (0-255) for the foreground color. Defaults to (0, 0, 0).

  • back_tuple (tuple, optional) โ€“ A tuple of RGB values (0-255) for the background color. Defaults to (255, 255, 255).

  • bold_text (bool, optional) โ€“ Whether to apply bold formatting to the text. Defaults to False.

Raises:

ValueError โ€“ If RGB values in fore_tuple or back_tuple are outside the valid range of 0-255.

Returns:

The formatted text with ANSI color codes embedded.

Return type:

Str

model_info๏ƒ

torchmate.utils.model_info(model: torch.nn.Module)[source]๏ƒ

Analyze a PyTorch model and returns a dictionary containing information about its size and parameters.

Parameters:

model (torch.nn.Module) โ€“ The PyTorch model to be analyzed.

Returns:

A dictionary containing the following information:

total_params (int): Total number of parameters in the model. trainable_params (int): Number of parameters that require gradient calculation during training. non_trainable_params (int): Number of parameters that do not require gradient calculation during training. total_size_mb (float): Total size of the model in megabytes. param_size_mb (float): Size of the model parameters in megabytes (excluding buffers). buffer_size_mb (float): Size of the model buffers in megabytes.

Return type:

dict

Prints:

This function also prints human-readable information about the model size and parameters including total, trainable, and non-trainable parameters for better understanding.