Skip to content
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

feat: Use torch.inference_mode() for TableQA #3731

Merged
merged 3 commits into from
Dec 19, 2022
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
17 changes: 11 additions & 6 deletions haystack/nodes/reader/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def _predict_tapas(self, inputs: BatchEncoding, document: Document) -> Answer:
table: pd.DataFrame = document.content

# Forward query and table through model and convert logits to predictions
with torch.no_grad():
with torch.inference_mode():
outputs = self.model(**inputs)

inputs.to("cpu")
Expand Down Expand Up @@ -366,8 +366,9 @@ def _calculate_answer_score(
) -> float:
# Calculate answer score
# Values over 88.72284 will overflow when passed through exponential, so logits are truncated.
logits[logits < -88.7] = -88.7
token_probabilities = 1 / (1 + np.exp(-logits)) * inputs.attention_mask
truncated_logits = logits.clone()
truncated_logits[truncated_logits < -88.7] = -88.7
token_probabilities = 1 / (1 + np.exp(-truncated_logits)) * inputs.attention_mask
token_types = [
"segment_ids",
"column_ids",
Expand Down Expand Up @@ -472,7 +473,7 @@ def _predict_tapas_scored(self, inputs: BatchEncoding, document: Document) -> Tu
table: pd.DataFrame = document.content

# Forward pass through model
with torch.no_grad():
with torch.inference_mode():
outputs = self.model.tapas(**inputs)
table_score = self.model.classifier(outputs.pooler_output)

Expand Down Expand Up @@ -765,7 +766,9 @@ def predict(self, query: str, documents: List[Document], top_k: Optional[int] =
padding=True,
)
row_inputs.to(self.devices[0])
row_logits = self.row_model(**row_inputs)[0].detach().cpu().numpy()[:, 1]
with torch.inference_mode():
row_outputs = self.row_model(**row_inputs)
row_logits = row_outputs[0].detach().cpu().numpy()[:, 1]

# Get column logits
column_inputs = self.column_tokenizer(
Expand All @@ -777,7 +780,9 @@ def predict(self, query: str, documents: List[Document], top_k: Optional[int] =
padding=True,
)
column_inputs.to(self.devices[0])
column_logits = self.column_model(**column_inputs)[0].detach().cpu().numpy()[:, 1]
with torch.inference_mode():
column_outputs = self.column_model(**column_inputs)
column_logits = column_outputs[0].detach().cpu().numpy()[:, 1]

# Calculate cell scores
current_answers: List[Answer] = []
Expand Down