Add Dense
, DenseLayer
and DenseConfig
to handle 2_Dense/
#660
+127
−11
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR do?
This PR adds support for
2_Dense/
modules, since some models as e.g. https://huggingface.co/sentence-transformers/LaBSE require the extraDense
module i.e., an extraLinear
layer on top of the pooled embeddings, when generating the embeddings.So on, this PR introduces the
DenseLayer
trait, impl forDense
and addsDenseConfig
, which are models with basically a singleLinear
layer, pulling the configuration from2_Dense/config.json
and the model weights from2_Dense/model.safetensors
.Note
The
2_Dense/
is only required when generating embeddings, meaning that it will only apply to theEmbedding
model type, whereas theReranker
andClassifier
are not affected by this addition, so on, neither therank
orpredict
methods for the given backend.This PR solves the issue recently reported at https://discuss.huggingface.co/t/inference-result-not-aligned-with-local-version-of-same-model-and-revision/160514.
Additionally, this PR also fixes a shape mismatch issue produced when performing matrix multiplication of 2D tensors on Metal devices due to the
candle
Metal kernels expecting the tensors to be contiguous. It seems that the error only arises on Metal for 2D tensors, where as for e.g. 3D tensors it seems to be working just fine without having to use.contiguous()
(which is expensive as it needs to clone the tensor).What's missing?
activation_function
from the2_Dense/config.json
(apparently mainly set totanh
, but more may be required)pytorch_model.bin
) weights too (even ifmodel.safetensors
is preferred)Reproduce
To ensure that the implementation was working fine and producing successful results i.e.,
allclose
like checks are true, and the cosine similarity is 1.0 (or as close as possible), the following test has been run:torch
,transformers
,sentence-transformers
,accelerate
andnumpy
):It should produce the following on any combination of device (CPU, MPS, CUDA) and dtype (float32, float16):
Before submitting
Who can review?
@Narsil