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

Fixing image segmentation with inference mode. #14204

Merged
merged 2 commits into from
Oct 29, 2021
Merged
Show file tree
Hide file tree
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
12 changes: 7 additions & 5 deletions src/transformers/pipelines/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,17 +862,19 @@ def postprocess(self, model_outputs: ModelOutput, **postprocess_parameters: Dict
"""
raise NotImplementedError("postprocess not implemented")

def get_inference_context(self):
inference_context = (
torch.inference_mode if version.parse(torch.__version__) >= version.parse("1.9.0") else torch.no_grad
)
return inference_context

def forward(self, model_inputs, **forward_params):
with self.device_placement():
if self.framework == "tf":
model_inputs["training"] = False
model_outputs = self._forward(model_inputs, **forward_params)
elif self.framework == "pt":
inference_context = (
torch.inference_mode
if version.parse(torch.__version__) >= version.parse("1.9.0")
else torch.no_grad
)
inference_context = self.get_inference_context()
with inference_context():
model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
model_outputs = self._forward(model_inputs, **forward_params)
Expand Down
3 changes: 3 additions & 0 deletions src/transformers/pipelines/image_segmentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ def __call__(self, *args, **kwargs) -> Union[Predictions, List[Prediction]]:

return super().__call__(*args, **kwargs)

def get_inference_context(self):
return torch.no_grad

def preprocess(self, image):
image = self.load_image(image)
target_size = torch.IntTensor([[image.height, image.width]])
Expand Down