Repository navigation
🚨 fix(sam3): invoke geometry encoder for text-only prompts to include learned cls token (#49592) - #49614
🚨 fix(sam3): invoke geometry encoder for text-only prompts to include learned cls token (#49592)#49614devtyagi3909 wants to merge 1 commit into
Conversation
|
Thank you for your contribution 🤗! CI Security Gate — waiting for maintainer approvalCI is approved automatically only for authors who already have a contribution merged in this repository. A maintainer will review this PR and approve CI to run on it. |
ju-ius
left a comment
There was a problem hiding this comment.
Thanks for picking this up!
Two small things:
- Please run
make fix-repoand push the result to this branch (no new PR needed).Sam3LiteTextModelinheritsSam3Model.forwardthrough modular, so its generatedmodeling_sam3_lite_text.pystill contains the oldhas_geometry_promptsgate.make fix-reporegenerates that file from the modular source; until thenutils/check_modular_conversion.pywill fail on CI, and LiteText keeps the old behaviour. - Since this changes the outputs of existing checkpoints for text-only prompts, it is a breaking change in the numbers even though no API changes. A 🚨 in the title would mark it as such for the release notes.
|
@ju-ius added the breaking change marker to the title and ran modular conversion to sync modeling_sam3_lite_text.py with tests added for both models. ready for ci. |
molbap
left a comment
There was a problem hiding this comment.
the fixes seem correct, some issues with existing exports + slow tests
| ) | ||
| box_labels = torch.where(box_labels == -10, 0, box_labels) | ||
| else: | ||
| box_embeddings = torch.zeros(batch_size, 0, 4, dtype=text_features.dtype, device=device) |
There was a problem hiding this comment.
running _encode_boxes on these empty boxes makes the OpenVINO export abort (test_openvino_export_* in sam3 and sam3_lite_text). can you skip it in Sam3GeometryEncoder.forward when there are no boxes?
if box_embeddings.shape[1] == 0:
prompt_embeds, prompt_mask = box_embeddings.new_zeros(batch_size, 0, self.hidden_size), box_mask
else:
prompt_embeds, prompt_mask = self._encode_boxes(box_embeddings, box_mask, box_labels, normalized_img_feats)| box_labels = torch.zeros(batch_size, 0, dtype=torch.long, device=device) | ||
| box_mask = torch.zeros(batch_size, 0, dtype=torch.bool, device=device) | ||
|
|
||
| geometry_outputs = self.geometry_encoder( |
There was a problem hiding this comment.
this changes every text-only output, so the slow tests that still expect the old values now fail: test_inference_text_prompt_only and test_inference_batched_images in sam3 and sam3_lite_text, test_inference_video_propagate_with_text_prompt and test_inference_video_streaming_with_text_prompt in sam3_video. can you update their expected values?
| geometry_prompt_features = geometry_outputs.last_hidden_state | ||
| geometry_prompt_mask = geometry_outputs.attention_mask | ||
|
|
||
| if geometry_prompt_features is not None: |
There was a problem hiding this comment.
the geometry features and mask can't be None anymore, so this if, its else and two of the mask branches below are dead. can you flatten it to this (down to combined_prompt_mask = text_mask), then make fix-repo for lite_text?
# Repeat text_features for all geometry prompts
if text_features.shape[0] == 1 and geometry_prompt_features.shape[0] > 1:
text_features = text_features.repeat(geometry_prompt_features.shape[0], 1, 1)
combined_prompt_features = torch.cat([text_features, geometry_prompt_features], dim=1)
if text_mask is None:
text_mask = torch.ones(batch_size, text_features.shape[1], dtype=torch.bool, device=device)
elif text_mask.shape[0] == 1 and geometry_prompt_mask.shape[0] > 1:
text_mask = text_mask.repeat(geometry_prompt_mask.shape[0], 1)
combined_prompt_mask = torch.cat([text_mask, geometry_prompt_mask], dim=1)| # The geometry encoder is always invoked, even for text-only prompts. Meta's reference | ||
| # implementation always concatenates a learned "CLS" prompt token to the text features | ||
| # (regardless of whether geometric prompts are provided), and the downstream DETR | ||
| # encoder/decoder expects this extra token. Skipping the call for text-only prompts | ||
| # produces a different prompt structure than the pretrained checkpoint was trained with. |
There was a problem hiding this comment.
can we drop this comment? the new test already guards it
| # The geometry encoder is always invoked, even for text-only prompts. Meta's reference | |
| # implementation always concatenates a learned "CLS" prompt token to the text features | |
| # (regardless of whether geometric prompts are provided), and the downstream DETR | |
| # encoder/decoder expects this extra token. Skipping the call for text-only prompts | |
| # produces a different prompt structure than the pretrained checkpoint was trained with. |
| def test_text_only_prompt_includes_cls_token(self): | ||
| config_and_inputs = self.model_tester.prepare_config_and_inputs() | ||
| config, pixel_values, input_ids, attention_mask = config_and_inputs | ||
| model = Sam3Model(config=config) | ||
| model.to(torch_device) | ||
| model.eval() | ||
|
|
||
| geo_calls = [] | ||
| detr_prompt_lens = [] | ||
|
|
||
| model.geometry_encoder.register_forward_hook(lambda m, a, o: geo_calls.append(1)) | ||
| model.detr_encoder.register_forward_pre_hook( | ||
| lambda m, a, kw: detr_prompt_lens.append(kw["text_features"].shape[1]), | ||
| with_kwargs=True, | ||
| ) | ||
|
|
||
| with torch.no_grad(): | ||
| outputs = model(pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask) | ||
|
|
||
| # Geometry encoder must run even for text-only prompts to provide the learned CLS token | ||
| self.assertEqual(len(geo_calls), 1) | ||
| self.assertEqual(detr_prompt_lens[0], input_ids.shape[1] + 1) | ||
| self.assertIsNotNone(outputs.pred_masks) | ||
|
|
There was a problem hiding this comment.
one hook is enough here, a prompt one token longer already means the geometry encoder ran. can you do the same in the lite_text test?
| def test_text_only_prompt_includes_cls_token(self): | |
| config_and_inputs = self.model_tester.prepare_config_and_inputs() | |
| config, pixel_values, input_ids, attention_mask = config_and_inputs | |
| model = Sam3Model(config=config) | |
| model.to(torch_device) | |
| model.eval() | |
| geo_calls = [] | |
| detr_prompt_lens = [] | |
| model.geometry_encoder.register_forward_hook(lambda m, a, o: geo_calls.append(1)) | |
| model.detr_encoder.register_forward_pre_hook( | |
| lambda m, a, kw: detr_prompt_lens.append(kw["text_features"].shape[1]), | |
| with_kwargs=True, | |
| ) | |
| with torch.no_grad(): | |
| outputs = model(pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask) | |
| # Geometry encoder must run even for text-only prompts to provide the learned CLS token | |
| self.assertEqual(len(geo_calls), 1) | |
| self.assertEqual(detr_prompt_lens[0], input_ids.shape[1] + 1) | |
| self.assertIsNotNone(outputs.pred_masks) | |
| def test_text_only_prompt_includes_cls_token(self): | |
| config, pixel_values, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs() | |
| model = Sam3Model(config=config).to(torch_device).eval() | |
| prompt_lengths = [] | |
| model.detr_encoder.register_forward_pre_hook( | |
| lambda module, args, kwargs: prompt_lengths.append(kwargs["text_features"].shape[1]), with_kwargs=True | |
| ) | |
| with torch.no_grad(): | |
| model(pixel_values=pixel_values, input_ids=input_ids, attention_mask=attention_mask) | |
| self.assertEqual(prompt_lengths, [input_ids.shape[1] + 1]) |
…earned cls token (huggingface#49592) Ensure learned CLS prompt token is included in DETR inputs for text-only prompts, skip empty box encoding in OpenVINO export, and sync sam3_lite_text modular conversion. Signed-off-by: DEV TYAGI <[email protected]>
29c41ec to
38d414b
Compare
|
@molbap updated with the requested changes:
for the slow integration tests, i hit 401 unauthorized locally since facebook/sam3 is gated. could you paste the new outputs from your slow test run or kick off the runner so i can update the assertions? |
|
[For maintainers] Suggested jobs to run (before merge) run-slow: sam3, sam3_lite_text |
|
hey, I think your last push didn't include the changes, the branch has the exact same code as before ( |
What does this PR do?
Fixes #49592
in
Sam3Model.forward, the geometry encoder call was wrapped inif has_geometry_prompts:. for text-only prompts (input_boxesis none or empty), the geometry encoder was completely skipped and never invoked.meta's reference implementation (
facebookresearch/sam3) always invokes the geometry encoder even when no boxes are passed: it runs on dummy/empty coordinates and appends its learnedcls_embedtoken to the prompt features. the detr encoder/decoder expects this extra token (seq_len + 1 tokens total). skipping it for text-only prompts drops the cls token, causing degraded detection scores and ghost masks on text queries.the inner
elseblock inforwardalready constructed dummy zero-embeddings (box_embeddings = torch.zeros(batch_size, 0, 4, ...)), but was previously unreachable because of the outerhas_geometry_promptsgate. this pr removes the gate so the geometry encoder runs with the empty box placeholder on text-only prompts and passes the cls token through to detr.added a unit test verifying
geometry_encoderis called and the cls token is concatenated when calling with text only.Code Agent Policy
Before submitting
Who can review?
@molbap @guarin