Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
207 changes: 198 additions & 9 deletions examples/eeg/eeg_models/labram_tuh_finetuning.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,23 @@
is the test set, as in the paper. Label processors are fitted on the
training part only.

The optimizer follows the official recipe (``run_class_finetuning.py``
and its README): AdamW, learning rate 5e-4, weight decay 0.05, layer-wise
learning-rate decay 0.65, stochastic depth 0.1. Known differences with
the official run, which may change the scores: no learning-rate warm-up
and cosine schedule (the PyHealth ``Trainer`` keeps the rate constant),
no label smoothing, a two-logit softmax head on TUAB instead of one
sigmoid logit, and a validation part drawn with this script's seed.
The optimizer follows the official recipe (``run_class_finetuning.py``,
its README and Table 5 of the paper): AdamW, peak learning rate 5e-4,
weight decay 0.05, layer-wise learning-rate decay 0.65, stochastic depth
0.1, an effective batch size of 512, a 5-epoch linear warm-up then a
cosine decay to 1e-6, and label smoothing 0.1 on TUEV. The PyHealth
``Trainer`` keeps the rate constant and updates after every batch, so the
warm-up, the cosine decay and the batch size of 512 come from
:class:`AccumulatingAdamW`, which accumulates 8 batches of 64 per update.
Known differences with the official run: no mixed precision, a two-logit
softmax head on TUAB instead of one sigmoid logit, and a validation part
drawn with this script's seed.

Test scores with seed 0 on one RTX 3060 Laptop GPU (paper, Tables 1 and

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Reported scores come from a wrapper, not from this script

The PR description says the 50-epoch runs used the same optimizer through a wrapper around the example. The docstring presents the scores as results of this script with seed 0. Say which script produced them, or rerun the committed script and report that.

2, mean of five seeds, in brackets): TUAB balanced accuracy 0.8316
(0.8140), AUROC 0.9098 (0.9022); TUEV balanced accuracy 0.6134 (0.6409),
Cohen's kappa 0.5274 (0.6637), weighted F1 0.7632 (0.8312). With a
constant rate of 5e-4 and updates every 64 samples, TUEV reached 0.5826.

Data: TUAB v3.0.x and TUEV v2.0.x from the Temple University EEG Corpus
(https://isip.piconepress.com/projects/nedc/html/tuh_eeg/). Access is
Expand Down Expand Up @@ -55,6 +65,13 @@
EPOCHS = 50
BATCH_SIZE = 64
ADAM_EPS = 1e-8
# Paper, Table 5: batch size 512 (reached here by gradient accumulation),
# warm-up epochs, minimal rate of the cosine decay, and label smoothing for
# the multi-class task only.
EFFECTIVE_BATCH_SIZE = 512
WARMUP_EPOCHS = 5
MIN_LEARNING_RATE = 1e-6
LABEL_SMOOTHING = {"tuab": 0.0, "tuev": 0.1}
# Embeddings the official code exempts from weight decay (``no_weight_decay``).
NO_DECAY_NAMES = ("encoder.pos_embed", "encoder.cls_token", "encoder.time_embed")
DATASETS = {
Expand Down Expand Up @@ -85,7 +102,14 @@ def parse_args() -> argparse.Namespace:
)
parser.add_argument("--epochs", type=int, default=EPOCHS)
parser.add_argument("--batch-size", type=int, default=BATCH_SIZE)
parser.add_argument(
"--effective-batch-size",
type=int,
default=EFFECTIVE_BATCH_SIZE,
help="Samples per update, a multiple of --batch-size.",
)
parser.add_argument("--lr", type=float, default=LEARNING_RATE)
parser.add_argument("--warmup-epochs", type=int, default=WARMUP_EPOCHS)
parser.add_argument("--layer-decay", type=float, default=LAYER_DECAY)
parser.add_argument("--seed", type=int, default=SEED)
parser.add_argument("--device", default=None, help="Default: cuda if available.")
Expand Down Expand Up @@ -160,6 +184,148 @@ def layer_decay_param_groups(
return [groups[key] for key in sorted(groups)]


def cosine_schedule(
peak_lr: float,
min_lr: float,
epochs: int,
updates_per_epoch: int,
warmup_epochs: int,
) -> np.ndarray:
"""Learning rate of each update: linear warm-up, then cosine decay.

Same values as ``cosine_scheduler`` in the official ``utils.py``: the
rate rises linearly from 0 to ``peak_lr`` over the warm-up epochs, then
follows a half cosine from ``peak_lr`` down towards ``min_lr``.

Args:
peak_lr: Rate at the end of the warm-up.
min_lr: Rate the cosine decays towards.
epochs: Number of epochs, more than ``warmup_epochs``.
updates_per_epoch: Number of optimizer updates per epoch.
warmup_epochs: Number of warm-up epochs.

Returns:
One rate per update, ``epochs * updates_per_epoch`` values.

Example:
>>> rates = cosine_schedule(5e-4, 1e-6, 10, 4, 2)
>>> len(rates), float(rates[0]), float(rates[8])
(40, 0.0, 0.0005)
"""
if epochs <= warmup_epochs:
raise ValueError(f"{epochs} epochs: need more than {warmup_epochs}")
warmup_updates = warmup_epochs * updates_per_epoch
warmup = np.linspace(0.0, peak_lr, warmup_updates)
decay_updates = epochs * updates_per_epoch - warmup_updates
steps = np.arange(decay_updates)
decay = min_lr + 0.5 * (peak_lr - min_lr) * (
1 + np.cos(np.pi * steps / decay_updates)
)
return np.concatenate((warmup, decay))


class AccumulatingAdamW(torch.optim.AdamW):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] New optimizer and LR schedule have no tests

AccumulatingAdamW (update counting, skipped steps, gradient averaging, zero_grad gating) and cosine_schedule are new non-trivial logic that decides the reported scores. The only checks are the doctests in this file, and I found no doctest collection in the repo's pytest or CI configuration, so nothing runs them. The author's 6-epoch equivalence test against the wrapper and the 587-updates check are not in the repository. tests/core/test_tcga_rna_seq.py already loads an example script by path for tests, so the pattern exists. Add a test that loads this example and checks the schedule values and the update count, and that accumulated batches give the same weights as one batch of the effective size.

"""AdamW with gradient accumulation and a per-update learning rate.

The PyHealth ``Trainer`` calls ``step()`` and ``zero_grad()`` after every
batch and keeps the rate constant. This optimizer updates the weights
once every ``accumulation`` batches, with the mean gradient of these
batches, so that 8 batches of 64 act as the paper's batch of 512. Before
each update it sets every group's rate to the scheduled rate times the
group's layer-decay factor, like ``lr_scale`` in the official code.
Batches at the end of an epoch that do not fill a whole update are
dropped: their gradients are cleared by the ``Trainer`` at the start of
the next epoch.

Args:
params: Parameter groups, whose ``lr`` is ``peak_lr`` times their
layer-decay factor.
schedule: Rate of each update, from :func:`cosine_schedule`.
peak_lr: The rate the group factors are relative to.
accumulation: Batches per update.
batches_per_epoch: Batches the ``Trainer`` runs per epoch.
**kwargs: Passed to :class:`torch.optim.AdamW`.

Example:
>>> layer = torch.nn.Linear(2, 1)
>>> opt = AccumulatingAdamW(
... layer.parameters(), np.full(4, 1e-3), 1e-3, 2, 4
... )
>>> for _ in range(2):
... layer(torch.ones(1, 2)).sum().backward()
... opt.step()
... opt.zero_grad()
>>> opt.updates
1
"""

def __init__(
self,
params,
schedule: np.ndarray,
peak_lr: float,
accumulation: int,
batches_per_epoch: int,
**kwargs,
) -> None:
super().__init__(params, lr=peak_lr, **kwargs)
self.schedule = schedule
self.accumulation = accumulation
self.batches_per_epoch = batches_per_epoch
self.used_batches = batches_per_epoch // accumulation * accumulation
self.factors = [group["lr"] / peak_lr for group in self.param_groups]
self.calls = 0
self.updates = 0
self.updated = False

def step(self, closure=None):
"""Update the weights after the last batch of each group of batches."""
position = self.calls % self.batches_per_epoch
self.calls += 1
if position >= self.used_batches or (position + 1) % self.accumulation:
return None
for group, factor in zip(self.param_groups, self.factors):
group["lr"] = float(self.schedule[self.updates]) * factor
for param in group["params"]:
if param.grad is not None:
# Mean over the batches, as the official run divides the
# loss by its update frequency.
param.grad.div_(self.accumulation)
self.updates += 1
self.updated = True
return super().step(closure)

def zero_grad(self, set_to_none: bool = True) -> None:
"""Clear the gradients only once they have been used by an update."""
if self.updated:
super().zero_grad(set_to_none=set_to_none)
self.updated = False


def smooth_training_loss(model: LaBraM, smoothing: float) -> None:
"""Add label smoothing to the training loss of a multi-class model.

The official code trains with a label-smoothed cross-entropy and
evaluates with the plain one. The ``Trainer`` evaluates without
gradients, which tells the two apart.

Args:
model: The model, whose label processor computes the loss.
smoothing: Label smoothing factor; 0 leaves the loss unchanged.
"""
if smoothing == 0:
return
processor = model.label_processor
plain_loss = processor.loss

def loss(logits: torch.Tensor, y_true: torch.Tensor, **kwargs) -> torch.Tensor:
if torch.is_grad_enabled():
kwargs.setdefault("label_smoothing", smoothing)
return plain_loss(logits, y_true, **kwargs)

processor.loss = loss

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Label smoothing wraps the library processor's loss; the description does not name this link

smooth_training_loss replaces the loss method of the model's label processor (processor.loss = loss). On TUEV that processor is a MultiClassLabelProcessor from pyhealth/processors/label_processor.py:353, a concrete library component, so the example now wraps its method and depends on its **kwargs pass-through to F.cross_entropy. The PR description says TUEV trains with label smoothing 0.1 but does not say the example wraps a shared processor. Either state in the description that the example wraps the processor's loss and why, or keep the example self-contained and say so. This is the author's choice.



def main() -> None:
"""Fine-tune and evaluate LaBraM on the chosen dataset."""
args = parse_args()
Expand Down Expand Up @@ -207,13 +373,36 @@ def main() -> None:
else:
print("no checkpoint given: training from scratch")

def optimizer_class(_trainer_groups: list, **params: float) -> torch.optim.AdamW:
smooth_training_loss(model, LABEL_SMOOTHING[args.dataset])

if args.effective_batch_size % args.batch_size:
raise ValueError("--effective-batch-size must be a multiple of --batch-size")
accumulation = args.effective_batch_size // args.batch_size
updates_per_epoch = len(train_loader) // accumulation
if updates_per_epoch == 0:
raise ValueError("fewer training batches than one update needs")
schedule = cosine_schedule(
args.lr, MIN_LEARNING_RATE, args.epochs, updates_per_epoch, args.warmup_epochs
)
print(
f"{accumulation} batches of {args.batch_size} per update, "
f"{updates_per_epoch} updates per epoch"
)

def optimizer_class(_trainer_groups: list, **params: float) -> AccumulatingAdamW:
# The Trainer builds its own two parameter groups; they are replaced
# by the layer-wise groups, which carry their own rates and decays.
groups = layer_decay_param_groups(
model, params["lr"], args.layer_decay, WEIGHT_DECAY
)
return torch.optim.AdamW(groups, eps=params["eps"])
return AccumulatingAdamW(
groups,
schedule,
params["lr"],
accumulation,
len(train_loader),
eps=params["eps"],
)

trainer = Trainer(model=model, metrics=metrics, device=args.device)
trainer.train(
Expand Down
Loading