CyberNativeAI commited on
Commit
91e56b6
·
verified ·
1 Parent(s): 9bbca17

Fix the dense embedding dimension slice

Browse files

The `dimension` option in the [dense Transformers example](https://huggingface.co/Alibaba-NLP/gte-multilingual-base/blob/9bbca17d9273fd0d03d5725c7a4b0f6b45142062/README.md) currently slices the batch axis after selecting the first token. This one-line change slices the feature axis before the existing normalization.

With `dimension=128`, four inputs still produce `(4, 768)`; 129 inputs produce `(128, 768)`, dropping the last input. The corrected expression produces `(4, 128)` and `(129, 128)`. The example's default `dimension=768` is unchanged for its four-input batch.

Minimal reproduction, without model downloads:

```python
from types import SimpleNamespace
import torch

for batch, dimension in ((4, 128), (129, 128), (4, 256), (4, 768)):
outputs = SimpleNamespace(
last_hidden_state=torch.arange(batch * 2 * 768).reshape(batch, 2, 768)
)
old = outputs.last_hidden_state[:, 0][:dimension]
new = outputs.last_hidden_state[:, 0, :dimension]
assert new.shape == (batch, dimension)
print(batch, dimension, tuple(old.shape), "->", tuple(new.shape))
```

Checked with PyTorch 2.4.0 on CPU. Additional synthetic assertions verified retained values, every input row and normalization after slicing. Model loading, actual embeddings and retrieval quality were not tested.

Submitted by CyberNative AI LLC; AI-assisted.

Files changed (1) hide show
  1. README.md +1 -1
README.md CHANGED
@@ -4684,7 +4684,7 @@ batch_dict = tokenizer(input_texts, max_length=8192, padding=True, truncation=Tr
4684
  outputs = model(**batch_dict)
4685
 
4686
  dimension=768 # The output dimension of the output embedding, should be in [128, 768]
4687
- embeddings = outputs.last_hidden_state[:, 0][:dimension]
4688
 
4689
  embeddings = F.normalize(embeddings, p=2, dim=1)
4690
  scores = (embeddings[:1] @ embeddings[1:].T) * 100
 
4684
  outputs = model(**batch_dict)
4685
 
4686
  dimension=768 # The output dimension of the output embedding, should be in [128, 768]
4687
+ embeddings = outputs.last_hidden_state[:, 0, :dimension]
4688
 
4689
  embeddings = F.normalize(embeddings, p=2, dim=1)
4690
  scores = (embeddings[:1] @ embeddings[1:].T) * 100