Instructions to use nomic-ai/nomic-bert-2048 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nomic-ai/nomic-bert-2048 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="nomic-ai/nomic-bert-2048", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForMaskedLM tokenizer = AutoTokenizer.from_pretrained("nomic-ai/nomic-bert-2048", trust_remote_code=True) model = AutoModelForMaskedLM.from_pretrained("nomic-ai/nomic-bert-2048", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Add transformers v5 compatibility while preserving v4 support
Hello!
Pull Request overview
- Fix loading
nomic-ai/nomic-embed-vision-v1.5withtransformersv5+
Details
With transformers v5+, from_pretrained initializes models on torch.device("meta"), which causes several issues in the vision model code:
NomicVisionModeldoesn't callpost_init(), which is required in v5+ to setall_tied_weights_keysand other static properties. Without it,from_pretrainedraises anAttributeError.NomicVisionRotaryEmbeddingCatregisterspos_embedas a non-persistent buffer, so it's never materialized when initialized on the meta device. I've added logic to recompute it on first use and pass the correct device through fromforward.NomicBertAttentionandNomicAttentionPoolingreferenceself.norm_factorwhich isn't available afterfrom_pretrainedloading. Replaced with inlinemath.sqrt(self.head_dim).
You can load and run the vision model with this using both revision (for https://huggingface.co/nomic-ai/nomic-embed-vision-v1.5/discussions/10) and code_revision to test it out:
from transformers import AutoModel, AutoImageProcessor
from PIL import Image
import requests
processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5")
model = AutoModel.from_pretrained(
"nomic-ai/nomic-embed-vision-v1.5",
trust_remote_code=True,
revision="refs/pr/10",
code_revision="refs/pr/23",
)
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(image, return_tensors="pt")
outputs = model(**inputs)
print(outputs.last_hidden_state.shape)
torch.Size([1, 197, 768])
Whereas if you don't use code_revision to use this PR, you get:
Traceback (most recent call last):
File "d:\models\st_v54\nomic-bert-2048\demo_test.py", line 6, in <module>
model = AutoModel.from_pretrained(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\models\auto\auto_factory.py", line 380, in from_pretrained
return model_class.from_pretrained(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\modeling_utils.py", line 4133, in from_pretrained
loading_info = cls._finalize_model_loading(model, load_config, loading_info)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\modeling_utils.py", line 4275, in _finalize_model_loading
model.mark_tied_weights_as_initialized(loading_info)
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\modeling_utils.py", line 4615, in mark_tied_weights_as_initialized
for tied_param in self.all_tied_weights_keys.keys():
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\torch\nn\modules\module.py", line 1965, in __getattr__
raise AttributeError(
AttributeError: 'NomicVisionModel' object has no attribute 'all_tied_weights_keys'. Did you mean: '_tied_weights_keys'?
As the self.post_init() wasn't called. If you use neither PR (i.e. no revision or code_revision), then you get:
Traceback (most recent call last):
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 144, in __strict_setattr__
validator(value)
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 625, in validator
type_validator(field.name, value, field.type)
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 470, in type_validator
validator(name, value, args)
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 507, in _validate_union
raise TypeError(
TypeError: Field 'n_inner' with value 2048.0 doesn't match any type in (<class 'int'>, <class 'NoneType'>). Errors: Field 'n_inner' expected int, got float (value: 2048.0); Field 'n_inner' expected NoneType, got float (value: 2048.0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\models\st_v54\nomic-bert-2048\demo_test.py", line 6, in <module>
model = AutoModel.from_pretrained(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\models\auto\auto_factory.py", line 329, in from_pretrained
config, kwargs = AutoConfig.from_pretrained(
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\models\auto\configuration_auto.py", line 1504, in from_pretrained
return config_class.from_pretrained(pretrained_model_name_or_path, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\configuration_utils.py", line 647, in from_pretrained
return cls.from_dict(config_dict, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\configuration_utils.py", line 824, in from_dict
config = cls(**config_dict)
^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.cache\huggingface\modules\transformers_modules\nomic_hyphen_ai\nomic_hyphen_bert_hyphen_2048\7710840340a098cfb869c4f65e87cf2b1b70caca\configuration_hf_nomic_bert.py", line 56, in __init__
super().__init__(**kwargs)
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 275, in init_with_validate
initial_init(self, *args, **kwargs) # type: ignore [call-arg]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\transformers\configuration_utils.py", line 95, in __init__
setattr(self, f.name, standard_kwargs[f.name])
File "C:\Users\tom\.conda\envs\sentence-transformers\Lib\site-packages\huggingface_hub\dataclasses.py", line 146, in __strict_setattr__
raise StrictDataclassFieldValidationError(field=name, cause=e) from e
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'n_inner':
TypeError: Field 'n_inner' with value 2048.0 doesn't match any type in (<class 'int'>, <class 'NoneType'>). Errors: Field 'n_inner' expected int, got float (value: 2048.0); Field 'n_inner' expected NoneType, got float (value: 2048.0)
In short: with the 2 PRs, the vision model should work again.
- Tom Aarsen
Related to the NaNs in https://huggingface.co/nomic-ai/nomic-embed-vision-v1.5/discussions/10 (with a lot of help from Codex):
I tracked the NaNs down to the RoPE buffer in NomicVisionRotaryEmbeddingCat.
Using the model revision from PR10 and code revision from PR23, the buffer reports:
rope = model.embeddings.rope
p = rope.pos_embed
print(p.device, p.shape, torch.isfinite(p).all().item(), p.abs().max().item(), p.sum().item())
cpu torch.Size([196, 128]) True, 7.488904521570712e+36, 1.741317881148069e+38
The values are technically finite, but they are clearly uninitialized; valid sine/cosine RoPE values should be bounded by approximately [-1, 1]. Transformers v5 materializes missing non-persistent buffers with torch.empty_like. PR23 only recomputes pos_embed when it is still on meta or when its sum is zero. In this case the buffer is on CPU and contains nonzero garbage, so recomputation is skipped. The huge values then cause NaNs in the first attention layer.
As a temporary workaround, I zero the buffer immediately after loading and before the first forward pass:
with torch.no_grad():
model.embeddings.rope.pos_embed.zero_()
PR23 then detects the zero sum and rebuilds the RoPE tensor during the first forward pass. After this workaround, the RoPE values are bounded and the model output is finite.
The permanent fix should lazily initialize pos_embed (for example, register it as None or use an explicit initialization flag), rather than detecting uninitialized memory by checking its sum. The actual patch-embedding call site should also pass the runtime device:
rot_pos_embed = self.rope.get_embed(device=x.device)
The current PR passes the device through NomicVisionRotaryEmbeddingCat.forward, but the vision model directly calls get_embed() instead.
Yess, perhaps https://huggingface.co/jinaai/xlm-roberta-flash-implementation/discussions/63 is related! Or perhaps adding post_init() at the end of the init would help.
Separate from the vision fixes in this PR, the text model also breaks on transformers 5.17.0 and later. NomicBertModel.forward calls self.get_extended_attention_mask(...) (modeling_hf_nomic_bert.py, line 1914), and 5.17.0 removed that method from ModuleUtilsMixin. Loading nomic-ai/nomic-embed-text-v1.5 with sentence-transformers 6.3.0 and transformers 5.23.0 fails with:
AttributeError: 'NomicBertModel' object has no attribute 'get_extended_attention_mask'
This PR doesn't change that call. Defining the method on the model restores it, and the embeddings on 5.23.0 match unpatched 5.16.0 exactly (max abs difference 0.0 on three test sentences):
def get_extended_attention_mask(self, attention_mask, input_shape, dtype=None):
dtype = dtype or self.dtype
mask = attention_mask[:, None, :, :] if attention_mask.dim() == 3 else attention_mask[:, None, None, :]
return (1.0 - mask.to(dtype=dtype)) * torch.finfo(dtype).min
I'm happy to add it to this PR or open a separate one.
AI disclosure: an AI coding agent (Claude Code) found this, ran the reproduction and drafted this comment at my direction. I reviewed it.