Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
38 lines
2.5 KiB
Python
38 lines
2.5 KiB
Python
"""Decode a fixed bounded set of concepts together on one image embedding.
|
|
|
|
This uses the pinned SAM3 model's FindStage batch interface. All confidence,
|
|
presence, interpolation and mask thresholds match Sam3Processor. No proposal
|
|
is accepted by this helper: downstream independent geometric checks remain.
|
|
"""
|
|
import torch
|
|
from sam3.model.data_misc import FindStage,interpolate
|
|
|
|
class ConceptDecoder:
|
|
def __init__(self,processor,batch_size=3):
|
|
if batch_size not in [1,2,3]:raise ValueError('Unqualified batch size')
|
|
self.processor=processor;self.batch_size=batch_size;self._text={}
|
|
self.text_encodings=0;self.decoder_calls=0
|
|
|
|
@torch.inference_mode()
|
|
def __call__(self,image,prompts):
|
|
if len(prompts)!=len(set(prompts)):raise ValueError('Duplicate concept')
|
|
result={};p=self.processor;model=p.model
|
|
with torch.autocast('cuda',dtype=torch.bfloat16):
|
|
state=p.set_image(image)
|
|
for offset in range(0,len(prompts),self.batch_size):
|
|
concepts=tuple(prompts[offset:offset+self.batch_size]);n=len(concepts)
|
|
if concepts not in self._text:
|
|
if len(self._text)>=16:raise ValueError('Exceeded fixed concept vocabulary')
|
|
self._text[concepts]=model.backbone.forward_text(list(concepts),device=p.device)
|
|
self.text_encodings+=1
|
|
backbone={**state['backbone_out'],**{k:v.clone()if isinstance(v,torch.Tensor)else v for k,v in self._text[concepts].items()}}
|
|
find=FindStage(img_ids=torch.zeros(n,device=p.device,dtype=torch.long),text_ids=torch.arange(n,device=p.device,dtype=torch.long),input_boxes=None,input_boxes_mask=None,input_boxes_label=None,input_points=None,input_points_mask=None)
|
|
outputs=model.forward_grounding(backbone_out=backbone,find_input=find,find_target=None,geometric_prompt=model._get_dummy_prompt(num_prompts=n))
|
|
probabilities=(outputs['pred_logits'].sigmoid()*outputs['presence_logit_dec'].sigmoid().unsqueeze(1)).squeeze(-1)
|
|
for i,concept in enumerate(concepts):
|
|
keep=probabilities[i]>p.confidence_threshold
|
|
masks=interpolate(outputs['pred_masks'][i][keep].unsqueeze(1),(image.height,image.width),mode='bilinear',align_corners=False).sigmoid()
|
|
result[concept]=dict(masks=(masks>.5).reshape(-1,image.height,image.width).cpu().numpy(),scores=probabilities[i][keep].float().cpu().numpy().reshape(-1))
|
|
self.decoder_calls+=1
|
|
return result
|