Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/transformers/src/utils/tensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -1272,8 +1272,11 @@ export function mean_pooling(last_hidden_state, attention_mask) {
}
}
const outOffset = i * embedDim;
// Clamp the denominator so an all-padding row averages to zero instead of NaN,
// matching sentence-transformers' torch.clamp(..., min=1e-9) behaviour.
const denominator = Math.max(count, 1e-9);
for (let k = 0; k < embedDim; ++k) {
returnedData[outOffset + k] = sums[k] / count;
returnedData[outOffset + k] = sums[k] / denominator;
}
}

Expand Down
8 changes: 4 additions & 4 deletions packages/transformers/tests/utils/tensor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -384,12 +384,12 @@ describe("Tensor operations", () => {
expect(mean_pooling(hidden, mask).data).toEqual(expected);
});

it("currently returns NaN (0/0) for a sequence with no attended tokens", () => {
// Documents current behavior, not a requirement: sentence-transformers
// returns zeros here, and this may change to match it.
it("returns zeros for a sequence with no attended tokens", () => {
// Matches sentence-transformers, which clamps the denominator to 1e-9
// so an all-padding row produces zeros rather than NaN.
const hidden = new Tensor("float32", [1, 2, 3, 4], [1, 2, 2]);
const mask = new Tensor("int64", [0n, 0n], [1, 2]);
expect(Array.from(mean_pooling(hidden, mask).data)).toEqual([NaN, NaN]);
expect(Array.from(mean_pooling(hidden, mask).data)).toEqual([0, 0]);
});

it("should ignore non-finite values at padding positions", () => {
Expand Down