Use TrainingWrapper to process documents and train RETRO
mainThe TrainingWrapper automates the pipeline of converting a folder of text documents into memmapped numpy arrays and provides a high-level interface for training and generation.
Workflow:
- Instantiate
RETRO. - Initialize
TrainingWrapperwith yourRETROinstance and paths for memmapped files. - Use
wrapper.get_dataloader()to get a PyTorch DataLoader. - Use
wrapper.get_optimizer()to get an AdamW optimizer with correct settings. - Use
wrapper.generate()for top-k sampling or prompt-based generation.
Environment Variable:
To force a reprocessing of the training data, run your script with REPROCESS=1.
$ REPROCESS=1 python train.pyimport torch
from retro_pytorch import RETRO, TrainingWrapper
retro = RETRO(
max_seq_len = 2048,
enc_dim = 896,
enc_depth = 3,
dec_dim = 768,
dec_depth = 12,
dec_cross_attn_layers = (1, 3, 6, 9),
heads = 8,
dim_head = 64,
dec_attn_dropout = 0.25,
dec_ff_dropout = 0.25
).cuda()
wrapper = TrainingWrapper(
retro = retro,
knn = 2,
chunk_size = 64,
documents_path = './text_folder',
glob = '**/*.txt',
chunks_memmap_path = './train.chunks.dat',
seqs_memmap_path = './train.seq.dat',
doc_ids_memmap_path = './train.doc_ids.dat',
max_chunks = 1_000_000,
max_seqs = 100_000,
knn_extra_neighbors = 100,
max_index_memory_usage = '100m',
current_memory_available = '1G'
)
train_dl = iter(wrapper.get_dataloader(batch_size = 2, shuffle = True))
optim = wrapper.get_optimizer(lr = 3e-4, wd = 0.01)
# Training step
seq, retrieved = map(lambda t: t.cuda(), next(train_dl))
loss = retro(seq, retrieved, return_loss = True)
loss.backward()
optim.step()
optim.zero_grad()
# Generation
sampled = wrapper.generate(filter_thres = 0.9, temperature = 1.0)
# Or with a prompt
prompt = torch.randint(0, 1000, (1, 128))
sampled = wrapper.generate(prompt, filter_thres = 0.9, temperature = 1.0)