|
| 1 | +"""HuggingFace training example.""" |
| 2 | +import logging |
| 3 | + |
| 4 | +import rich.logging |
| 5 | +import torch |
| 6 | +from torch import nn |
| 7 | +from torch.utils.data import DataLoader |
| 8 | +from tqdm import tqdm |
| 9 | + |
| 10 | +from py_utils import ( |
| 11 | + get_dataset_builder, get_num_workers, get_raw_datasets, get_tokenizer, |
| 12 | + preprocess_datasets |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +def main(): |
| 17 | + training_epochs = 1 |
| 18 | + batch_size = 256 |
| 19 | + |
| 20 | + # Check that the GPU is available |
| 21 | + assert torch.cuda.is_available() and torch.cuda.device_count() > 0 |
| 22 | + device = torch.device("cuda", 0) |
| 23 | + |
| 24 | + # Setup logging (optional, but much better than using print statements) |
| 25 | + logging.basicConfig( |
| 26 | + level=logging.INFO, |
| 27 | + handlers=[rich.logging.RichHandler(markup=True)], # Very pretty, uses the `rich` package. |
| 28 | + ) |
| 29 | + |
| 30 | + logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + # Setup ImageNet |
| 33 | + num_workers = get_num_workers() |
| 34 | + train_dataset, valid_dataset, test_dataset = make_datasets(num_workers) |
| 35 | + train_dataloader = DataLoader( |
| 36 | + train_dataset, |
| 37 | + batch_size=batch_size, |
| 38 | + num_workers=num_workers, |
| 39 | + shuffle=True, |
| 40 | + ) |
| 41 | + valid_dataloader = DataLoader( |
| 42 | + valid_dataset, |
| 43 | + batch_size=batch_size, |
| 44 | + num_workers=num_workers, |
| 45 | + shuffle=False, |
| 46 | + ) |
| 47 | + test_dataloader = DataLoader( # NOTE: Not used in this example. |
| 48 | + test_dataset, |
| 49 | + batch_size=batch_size, |
| 50 | + num_workers=num_workers, |
| 51 | + shuffle=False, |
| 52 | + ) |
| 53 | + |
| 54 | + # Checkout the "checkpointing and preemption" example for more info! |
| 55 | + logger.debug("Starting training from scratch.") |
| 56 | + |
| 57 | + for epoch in range(training_epochs): |
| 58 | + logger.debug(f"Starting epoch {epoch}/{training_epochs}") |
| 59 | + |
| 60 | + # NOTE: using a progress bar from tqdm because it's nicer than using `print`. |
| 61 | + progress_bar = tqdm( |
| 62 | + total=len(train_dataloader), |
| 63 | + desc=f"Train epoch {epoch}", |
| 64 | + ) |
| 65 | + |
| 66 | + # Training loop |
| 67 | + for batch in train_dataloader: |
| 68 | + # Move the batch to the GPU before we pass it to the model |
| 69 | + batch = {k:item.to(device) for k, item in batch.items()} |
| 70 | + |
| 71 | + # [Training of the model goes here] |
| 72 | + |
| 73 | + # Advance the progress bar one step, and update the "postfix" () the progress bar. (nicer than just) |
| 74 | + progress_bar.update(1) |
| 75 | + progress_bar.close() |
| 76 | + |
| 77 | + val_loss, val_accuracy = validation_loop(None, valid_dataloader, device) |
| 78 | + logger.info(f"Epoch {epoch}: Val loss: {val_loss:.3f} accuracy: {val_accuracy:.2%}") |
| 79 | + |
| 80 | + print("Done!") |
| 81 | + |
| 82 | + |
| 83 | +@torch.no_grad() |
| 84 | +def validation_loop(model: nn.Module, dataloader: DataLoader, device: torch.device): |
| 85 | + total_loss = 0.0 |
| 86 | + n_samples = 0 |
| 87 | + correct_predictions = 0 |
| 88 | + |
| 89 | + for batch in dataloader: |
| 90 | + batch = {k:item.to(device) for k, item in batch.items()} |
| 91 | + |
| 92 | + batch_n_samples = batch["input_ids"].data.shape[0] |
| 93 | + |
| 94 | + n_samples += batch_n_samples |
| 95 | + |
| 96 | + accuracy = correct_predictions / n_samples |
| 97 | + return total_loss, accuracy |
| 98 | + |
| 99 | + |
| 100 | +def make_datasets(num_workers:int=None): |
| 101 | + """Returns the training, validation, and test splits for the prepared dataset. |
| 102 | + """ |
| 103 | + builder = get_dataset_builder() |
| 104 | + raw_datasets = get_raw_datasets(builder) |
| 105 | + tokenizer = get_tokenizer() |
| 106 | + preprocessed_datasets = preprocess_datasets(tokenizer, raw_datasets, num_workers=num_workers) |
| 107 | + return ( |
| 108 | + preprocessed_datasets["train"], preprocessed_datasets["validation"], |
| 109 | + preprocessed_datasets["test"] |
| 110 | + ) |
| 111 | + |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + main() |
0 commit comments