"""Generate and validate the Transformers.js three-graph SAM 3 fixture from seeded random weights. Tested with Python 3.13, torch 2.8.0, torchvision 0.23.0, transformers 5.24.1, tokenizers 0.23.3, onnx 1.19.1, and onnxruntime 1.32.0. """ import argparse import json from hashlib import file_digest from pathlib import Path import numpy as np import onnx import onnxruntime as ort from PIL import Image from tokenizers import Tokenizer, models, pre_tokenizers, processors import torch from torch import nn from transformers import Sam3Config, Sam3ImageProcessor, Sam3Model, Sam3Processor from transformers.modeling_outputs import BaseModelOutputWithPooling from transformers.models.sam3.modeling_sam3 import Sam3VisionEncoderOutput SEED = 1800 IMAGE_SIZE = 28 TEXT_LENGTH = 32 NAMES = ("pred_masks", "pred_boxes", "pred_logits", "presence_logits", "semantic_seg") FPN = tuple(f"fpn_hidden_state_{i}" for i in range(3)) TRANSFORMERS_REVISION = "e68083bdf4035ba6d75976a3b7ce15c98a61f278" def config(): transformer = dict(hidden_size=16, num_attention_heads=2, intermediate_size=32) detr = dict(**transformer, num_layers=1) result = Sam3Config( architectures=["Sam3Model"], vision_config=dict( backbone_config=dict( model_type="sam3_vit_model", **transformer, num_hidden_layers=1, global_attn_indexes=[0], image_size=IMAGE_SIZE, pretrain_image_size=IMAGE_SIZE, patch_size=7, window_size=2, ), fpn_hidden_size=16, backbone_feature_sizes=[[16, 16], [8, 8], [4, 4]], ), text_config=dict( model_type="clip_text_model", **transformer, vocab_size=5, projection_dim=8, num_hidden_layers=1, max_position_embeddings=TEXT_LENGTH, bos_token_id=1, eos_token_id=2, pad_token_id=2, ), geometry_encoder_config=detr, detr_encoder_config=detr, detr_decoder_config=dict(**detr, num_queries=3), mask_decoder_config=dict(hidden_size=16, num_attention_heads=2), ) result._attn_implementation = "eager" return result class Vision(nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, pixel_values): return self.model.get_vision_features(pixel_values).fpn_hidden_states[:-1] class Text(nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, input_ids, attention_mask): return self.model.get_text_features(input_ids, attention_mask, return_dict=True).pooler_output class Decoder(nn.Module): def __init__(self, model, position): super().__init__() self.model = model self.register_buffer("position", position) def forward(self, level0, level1, level2, text_features, attention_mask): # Original text-only forward discards the fourth level and uses the third position encoding. vision = Sam3VisionEncoderOutput( fpn_hidden_states=(level0, level1, level2, level2), fpn_position_encoding=(None, None, self.position, None), ) output = self.model( vision_embeds=vision, text_embeds=BaseModelOutputWithPooling(pooler_output=text_features), attention_mask=attention_mask, ) return tuple(getattr(output, name) for name in NAMES) def save_processor(output): vocab = {"[UNK]": 0, "[START]": 1, "[END]": 2, "cat": 3, "truck": 4} tokenizer = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]")) tokenizer.pre_tokenizer = pre_tokenizers.Whitespace() tokenizer.post_processor = processors.TemplateProcessing( single="[START] $A [END]", special_tokens=[("[START]", 1), ("[END]", 2)], ) tokenizer.save(str(output / "tokenizer.json")) (output / "tokenizer_config.json").write_text(json.dumps({ "tokenizer_class": "PreTrainedTokenizerFast", "model_max_length": TEXT_LENGTH, "unk_token": "[UNK]", "bos_token": "[START]", "eos_token": "[END]", "pad_token": "[END]", }, indent=2) + "\n") image_processor = Sam3ImageProcessor( size={"height": IMAGE_SIZE, "width": IMAGE_SIZE}, mask_size={"height": 16, "width": 16}, ) image_processor.save_pretrained(output) image_config_path = output / "preprocessor_config.json" image_config = json.loads(image_config_path.read_text()) image_config["processor_class"] = "Sam3Processor" image_config_path.write_text(json.dumps(image_config, indent=2) + "\n") return Sam3Processor.from_pretrained(output, local_files_only=True) def export_graph(output, name, model, inputs, input_names, output_names): path = output / "onnx" / f"{name}.onnx" torch.onnx.export( model, inputs, str(path), opset_version=18, dynamo=False, input_names=list(input_names), output_names=list(output_names), ) graph = onnx.load(path, load_external_data=False) onnx.checker.check_model(graph) assert [v.name for v in graph.graph.input] == list(input_names) assert [v.name for v in graph.graph.output] == list(output_names) assert not any(v.external_data for v in graph.graph.initializer) return ort.InferenceSession(str(path), providers=["CPUExecutionProvider"]) def validate(model, processor, image, sessions): vision, text, decoder = sessions rows = [] cached_vision = None for prompt in ("cat", "truck"): inputs = processor(images=image, text=prompt, return_tensors="pt") expected = model(**inputs) raw = {name: inputs[name].numpy() for name in ("pixel_values", "input_ids", "attention_mask")} if cached_vision is None: cached_vision = dict(zip(FPN, vision.run(None, {"pixel_values": raw["pixel_values"]}), strict=True)) features, = text.run(None, {key: raw[key] for key in ("input_ids", "attention_mask")}) feeds = {**cached_vision, "text_features": features, "attention_mask": raw["attention_mask"]} actual = decoder.run(None, feeds) errors = {} for name, value in zip(NAMES, actual, strict=True): target = getattr(expected, name).numpy() np.testing.assert_allclose(value, target, atol=1e-5, rtol=1e-4) errors[name] = float(np.max(np.abs(value - target))) scores = processor.post_process_instance_segmentation( expected, threshold=0.1, mask_threshold=0.5, target_sizes=[(IMAGE_SIZE, IMAGE_SIZE)], )[0]["scores"] rows.append({ "prompt": prompt, "token_prefix": raw["input_ids"][0, :3].tolist(), "shapes": {name: list(getattr(expected, name).shape) for name in NAMES}, "slices": {name: getattr(expected, name).flatten()[:6].tolist() for name in NAMES}, "scores_at_threshold_0_1": scores.tolist(), "onnx_max_absolute_errors": errors, }) assert rows[0]["slices"]["pred_logits"] != rows[1]["slices"]["pred_logits"] return rows @torch.no_grad() def main(output): torch.manual_seed(SEED) torch.set_num_threads(1) (output / "onnx").mkdir(parents=True, exist_ok=True) model = Sam3Model(config()).eval() model.config.save_pretrained(output) processor = save_processor(output) pixels = (np.arange(IMAGE_SIZE * IMAGE_SIZE * 3) % 256).astype(np.uint8) image = Image.fromarray(pixels.reshape(IMAGE_SIZE, IMAGE_SIZE, 3)) inputs = processor(images=image, text="cat", return_tensors="pt") vision = Vision(model).eval() text = Text(model).eval() fpn = model.get_vision_features(inputs.pixel_values) decoder = Decoder(model, fpn.fpn_position_encoding[2]).eval() text_features = text(inputs.input_ids, inputs.attention_mask) sessions = [ export_graph(output, "vision_encoder", vision, (inputs.pixel_values,), ("pixel_values",), FPN), export_graph( output, "text_encoder", text, (inputs.input_ids, inputs.attention_mask), ("input_ids", "attention_mask"), ("text_features",), ), export_graph( output, "prompt_decoder", decoder, (*fpn.fpn_hidden_states[:-1], text_features, inputs.attention_mask), (*FPN, "text_features", "attention_mask"), NAMES, ), ] rows = validate(model, processor, image, sessions) files = {} for graph in sorted((output / "onnx").glob("*.onnx")): with graph.open("rb") as file: files[str(graph.relative_to(output))] = { "size": graph.stat().st_size, "sha256": file_digest(file, "sha256").hexdigest(), } evidence = { "seed": SEED, "transformers_revision": TRANSFORMERS_REVISION, "parameter_count": sum(param.numel() for param in model.parameters()), "image_size": IMAGE_SIZE, "text_length": TEXT_LENGTH, "outputs": rows, "graphs": files, } (output.parent / "expected.json").write_text(json.dumps(evidence, indent=2) + "\n") print(json.dumps(evidence, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", type=Path) main(parser.parse_args().output.resolve())