In fairseq.tasks, a Task is a central abstraction that manages dictionaries, handles dataset loading/iteration, and provides helpers for initializing models and calculating loss.
To use a task, you typically follow this lifecycle:
- Setup: Initialize the task using
setup_task(args). - Initialization: Build the
model and criterion using the task's build_model and build_criterion methods. - Data Loading: Load datasets (e.g., 'train', 'valid') using
load_dataset. - Iteration: Create a batch iterator via
get_batch_iterator. - Training Loop: For each batch, compute the loss using
get_loss(model, criterion, batch) and perform backpropagation.
# setup the task (e.g., load dictionaries)
task = fairseq.tasks.setup_task(args)
# build model and criterion
model = task.build_model(args)
criterion = task.build_criterion(args)
# load datasets
task.load_dataset('train')
task.load_dataset('valid')
# iterate over mini-batches of data
batch_itr = task.get_batch_iterator(
task.dataset('train'), max_tokens=4096,
)
for batch in batch_itr:
# compute the loss
loss, sample_size, logging_output = task.get_loss(
model, criterion, batch,
)
loss.backward()