Skip to content

🚨 fix(sam3): invoke geometry encoder for text-only prompts to include learned cls token (#49592) - #49614

Open
devtyagi3909 wants to merge 1 commit into
huggingface:mainfrom
devtyagi3909:fix/sam3-text-prompt-cls-token
Open

devtyagi3909 wants to merge 1 commit into
huggingface:mainfrom
devtyagi3909:fix/sam3-text-prompt-cls-token

Conversation

@devtyagi3909

@devtyagi3909 devtyagi3909 commented Oct 14, 2026 •

Copy link
Copy Markdown

What does this PR do?

Fixes #49592

in Sam3Model.forward, the geometry encoder call was wrapped in if has_geometry_prompts:. for text-only prompts (input_boxes is 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 learned cls_embed token 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 else block in forward already constructed dummy zero-embeddings (box_embeddings = torch.zeros(batch_size, 0, 4, ...)), but was previously unreachable because of the outer has_geometry_prompts gate. 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_encoder is called and the cls token is concatenated when calling with text only.

Code Agent Policy

  • (First-time contributors only): I confirm that this PR description and code is not written by an LLM or code agent

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline and the Pull Request checks?
  • Was this discussed/approved via a Github issue or the forum? Please add a link to it if that's the case.
  • Did you make sure to update the documentation with your changes according to the guidelines?
  • Did you write any new necessary tests?

Who can review?

@molbap @guarin

@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your contribution 🤗!

CI Security Gate — waiting for maintainer approval

CI 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 ju-ius left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up!

Two small things:

  1. Please run make fix-repo and push the result to this branch (no new PR needed). Sam3LiteTextModel inherits Sam3Model.forward through modular, so its generated modeling_sam3_lite_text.py still contains the old has_geometry_prompts gate. make fix-repo regenerates that file from the modular source; until then utils/check_modular_conversion.py will fail on CI, and LiteText keeps the old behaviour.
  2. 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.

@devtyagi3909 devtyagi3909 changed the title fix(sam3): invoke geometry encoder for text-only prompts to include learned cls token (#49592) 🚨 fix(sam3): invoke geometry encoder for text-only prompts to include learned cls token (#49592) Oct 15, 2026
@devtyagi3909

Copy link
Copy Markdown
Author

@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 molbap left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment on lines +2371 to +2375
# 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.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we drop this comment? the new test already guards it

Suggested change
# 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.

Comment on lines +937 to +960
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Suggested change
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]>
@devtyagi3909
devtyagi3909 force-pushed the fix/sam3-text-prompt-cls-token branch from 29c41ec to 38d414b Compare November 24, 2026 16:38
@devtyagi3909

Copy link
Copy Markdown
Author

@molbap updated with the requested changes:

  • skipped _encode_boxes when box_embeddings.shape[1] == 0 to fix the openvino export
  • flattened the prompt/mask combination and dropped the comment
  • simplified the prompt length hook in both sam3 and sam3_lite_text tests
  • ran modular conversion to sync modeling_sam3_lite_text.py

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?

@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: sam3, sam3_lite_text

@molbap

molbap commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

hey, I think your last push didn't include the changes, the branch has the exact same code as before (_encode_boxes still runs on empty boxes, the comment and both test hooks are still there). can you check and push again?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SAM 3: text-only prompts drop the geometry CLS token that Meta's implementation always adds

3 participants