Skip to content

[Example] RA-DIT Implement retrieval-augmented instruction finetuning trainer #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
39 changes: 39 additions & 0 deletions examples/ra-dit/ra_dit/trainers_and_testers/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,51 @@

from fed_rag.decorators import federate
from fed_rag.types import TestResult, TrainResult
from fed_rag.types.rag_system import RAGSystem

# Dataset
train_dataset = load_dataset("stanfordnlp/imdb", split="train[:20]")
val_dataset = load_dataset("stanfordnlp/imdb", split="test[:10]")


# Custom SFTTrainer to implement RA-IT
class RetrievalAugmentedSFTTrainer(SFTTrainer):
"""A custom SFTTrainer to implement retrieval-augmented instruction fine-tuning."""

def compute_loss(self, model: PreTrainedModel, inputs, return_outputs=False):
try:
rag_system: RAGSystem = model.__associated_rag_system
except AttributeError:
raise ValueError(
"Unable to get associated RAGSystem with supplied `BaseGenerator`."
)
questions = inputs.pop("questions")
answers = inputs.pop("answers")

# retrieve
for q in questions:
source_nodes = rag_system.retrieve(query=q)
# parallel in-context retrieval augmentation
proba_tensors = []
for n in source_nodes:
context = n.node.text_content
# prepare prompt
prompt = rag_system.generator.prompt_template.format(
question=q, context=context
)
# probas
outputs = model(prompt)
logits = outputs.logits
probas = ...
proba_tensors.append(probas)
weighted_probas = ...

# loss
loss = ... # masked language model

return (loss, outputs) if return_outputs else loss


@federate.trainer.huggingface
def generator_train_loop(
model: PreTrainedModel,
Expand Down
Loading