fastembed 7.7.0

Library for generating vector embeddings, reranking locally.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! candle's fused attention, writing its output as `[B, T, H, D]`.
//!
//! `candle_nn::ops::sdpa` hands its kernel the strides of a contiguous `[B, H, T, D]` output, so
//! the attention transposes it back and copies it before `o_proj`. The kernel itself
//! (`candle_metal_kernels::call_sdpa_full`) writes through whatever output strides it is given;
//! [`sdpa_bthd`] gives it those of `[B, T, H, D]`, and the copy goes away.

use candle_core::{Result, Tensor};

/// `sdpa(q, k, v, mask, do_causal, scale, 1.0).transpose(1, 2)`, contiguous: q `[B, H, T, D]`,
/// k and v `[B, Hkv, S, D]` (any strides with the head dim contiguous), the mask
/// `[B, H, T, S]`. On Metal this is candle's full attention kernel writing `[B, T, H, D]`
/// directly, for one query position too: candle's sdpa sends a single query to its vector
/// kernel, which takes no mask, so a padded batch's last row would see its padding. Elsewhere it
/// is plain tensor math: candle's `sdpa` custom op has no CUDA/CPU implementation, so the
/// fallback expands GQA heads and applies the causal mask itself.
pub(crate) fn sdpa_bthd(
    q: &Tensor,
    k: &Tensor,
    v: &Tensor,
    mask: Option<&Tensor>,
    do_causal: bool,
    scale: f32,
) -> Result<Tensor> {
    #[cfg(feature = "metal")]
    if q.device().is_metal() {
        let op = metal::SdpaBthd {
            scale,
            mask: mask.cloned(),
            do_causal,
        };
        return q.apply_op3_no_bwd(k, v, &op);
    }
    sdpa_plain_bthd(q, k, v, mask, do_causal, scale)
}

/// Device-generic attention with the same contract as [`sdpa_bthd`]: q `[B, H, T, D]`,
/// k/v `[B, Hkv, S, D]`, optional additive mask broadcastable to `[B, H, T, S]`, and a
/// causal mask over the last `T` query rows. Used on CUDA and CPU, where candle's
/// Metal-only `sdpa` op cannot run.
fn sdpa_plain_bthd(
    q: &Tensor,
    k: &Tensor,
    v: &Tensor,
    mask: Option<&Tensor>,
    do_causal: bool,
    scale: f32,
) -> Result<Tensor> {
    let (b, h, tq, d) = q.dims4()?;
    let (bk, hkv, s, dk) = k.dims4()?;
    if b != bk || d != dk || d == 0 || tq == 0 || s == 0 {
        candle_core::bail!("attention q is {:?} but k is {:?}", q.dims(), k.dims())
    }
    if h % hkv != 0 {
        candle_core::bail!("attention q heads {h} are not a multiple of kv heads {hkv}")
    }
    let groups = h / hkv;
    let k = repeat_kv(k, groups)?;
    let v = repeat_kv(v, groups)?;
    let dtype = q.dtype();
    let q = q.contiguous()?;
    let kt = k.transpose(2, 3)?.contiguous()?;
    let mut scores = q.matmul(&kt)?;
    if scale != 1.0 {
        scores = scores.affine(scale as f64, 0.0)?;
    }
    if let Some(mask) = mask {
        let mask = mask.to_dtype(dtype)?.contiguous()?;
        scores = scores.broadcast_add(&mask)?;
    }
    if do_causal {
        let additive = causal_additive(tq, s, dtype, q.device())?;
        scores = scores.broadcast_add(&additive)?;
    }
    let probs = candle_nn::ops::softmax_last_dim(&scores)?;
    probs
        .matmul(&v.contiguous()?)?
        .transpose(1, 2)?
        .contiguous()
}

/// `[Tq, S]` additive causal mask aligned like the fused kernel's `qL_off`: the last
/// query row sees every key, its first row sees `S - Tq + 1`.
fn causal_additive(
    tq: usize,
    s: usize,
    dtype: candle_core::DType,
    device: &candle_core::Device,
) -> Result<Tensor> {
    if tq > s {
        candle_core::bail!("causal attention has {tq} queries for {s} keys")
    }
    let all = Tensor::tril2(s, candle_core::DType::F32, device)?;
    let last = all.narrow(0, s - tq, tq)?;
    // 1 at allowed positions, 0 at masked ones; masked becomes ~ -inf in the score dtype.
    let masked = last.affine(-1.0, 1.0)?;
    masked.affine(-1e9, 0.0)?.to_dtype(dtype)
}

/// `[B, Hkv, S, D]` → `[B, Hkv * groups, S, D]` by repeating each kv head contiguously.
fn repeat_kv(x: &Tensor, groups: usize) -> Result<Tensor> {
    if groups == 1 {
        return x.contiguous();
    }
    let (b, hkv, s, d) = x.dims4()?;
    x.unsqueeze(2)?
        .broadcast_as((b, hkv, groups, s, d))?
        .reshape((b, hkv * groups, s, d))?
        .contiguous()
}

#[cfg(feature = "metal")]
mod metal {
    use candle_core::backend::BackendStorage;
    use candle_core::{CpuStorage, DType, Layout, MetalStorage, Result, Shape, Tensor};
    use candle_metal_kernels::SdpaDType;

    pub(super) struct SdpaBthd {
        pub(super) scale: f32,
        pub(super) mask: Option<Tensor>,
        pub(super) do_causal: bool,
    }

    fn sdpa_dtype(dtype: DType) -> Result<SdpaDType> {
        match dtype {
            DType::BF16 => Ok(SdpaDType::BF16),
            DType::F16 => Ok(SdpaDType::F16),
            DType::F32 => Ok(SdpaDType::F32),
            other => candle_core::bail!("sdpa-bthd does not take {other:?}"),
        }
    }

    impl candle_core::CustomOp3 for SdpaBthd {
        fn name(&self) -> &'static str {
            "sdpa-bthd"
        }

        fn cpu_fwd(
            &self,
            _: &CpuStorage,
            _: &Layout,
            _: &CpuStorage,
            _: &Layout,
            _: &CpuStorage,
            _: &Layout,
        ) -> Result<(CpuStorage, Shape)> {
            candle_core::bail!(
                "sdpa-bthd runs on Metal only; sdpa_bthd takes candle's sdpa elsewhere"
            )
        }

        fn metal_fwd(
            &self,
            q: &MetalStorage,
            q_l: &Layout,
            k: &MetalStorage,
            k_l: &Layout,
            v: &MetalStorage,
            v_l: &Layout,
        ) -> Result<(MetalStorage, Shape)> {
            let (b, h, t, d) = q_l.shape().dims4()?;
            let (_, h_kv, s, k_d) = k_l.shape().dims4()?;
            let (_, v_h, v_s, v_d) = v_l.shape().dims4()?;
            if k_d != d || v_d != d || v_h != h_kv || v_s != s || !h.is_multiple_of(h_kv) {
                candle_core::bail!(
                    "sdpa-bthd shapes do not fit: q {:?} k {:?} v {:?}",
                    q_l.dims(),
                    k_l.dims(),
                    v_l.dims()
                )
            }
            if t > s {
                candle_core::bail!("sdpa-bthd takes no more queries than keys: q {t}, k {s}")
            }
            for l in [q_l, k_l, v_l] {
                if l.stride()[3] != 1 {
                    candle_core::bail!("sdpa-bthd needs the head dim contiguous")
                }
            }
            let dtype = q.dtype();
            if k.dtype() != dtype || v.dtype() != dtype {
                candle_core::bail!("sdpa-bthd q, k and v dtypes differ")
            }
            let itype = sdpa_dtype(dtype)?;

            let device = q.device();
            let el = b * t * h * d;
            let output = device
                .new_buffer_builder()
                .with_size_for(el, dtype)
                .with_label("sdpa_bthd_o")
                .build()?;
            // The kernel's (batch, head, sequence) output strides for a `[B, T, H, D]` buffer.
            let o_strides = [t * h * d, d, h * d];

            let mask = self.mask.as_ref().map(|m| m.storage_and_layout());
            let (mask_type, mask_buffer, mask_strides) = match (&self.mask, &mask) {
                (Some(m), Some((storage, layout))) => {
                    let candle_core::Storage::Metal(storage) = &**storage else {
                        candle_core::bail!("sdpa-bthd mask is not on the metal device")
                    };
                    // call_sdpa_full binds the mask buffer at offset 0, so a view that starts
                    // anywhere else (a narrowed row) would be read from the wrong place.
                    if layout.start_offset() != 0 {
                        candle_core::bail!("sdpa-bthd mask has to start at its buffer's start")
                    }
                    if layout.dims() != [b, h, t, s] {
                        candle_core::bail!(
                            "sdpa-bthd mask is {:?}, it needs {:?}",
                            layout.dims(),
                            [b, h, t, s]
                        )
                    }
                    let mask_type = sdpa_dtype(m.dtype())?;
                    if mask_type != itype {
                        candle_core::bail!("sdpa-bthd mask dtype differs from q's")
                    }
                    (
                        Some(mask_type),
                        Some(storage.buffer()),
                        Some(layout.stride().to_vec()),
                    )
                }
                _ => (None, None, None),
            };

            let size = dtype.size_in_bytes();
            let encoder = device.command_encoder()?;
            encoder.set_label("sdpa_bthd");
            candle_metal_kernels::call_sdpa_full(
                device.device(),
                &encoder,
                device.kernels(),
                q_l.start_offset() * size,
                q_l.dims(),
                q_l.stride(),
                q.buffer(),
                k_l.start_offset() * size,
                k_l.dims(),
                k_l.stride(),
                k.buffer(),
                v_l.start_offset() * size,
                v.buffer(),
                v_l.stride(),
                mask_type,
                mask_buffer,
                mask_strides.as_deref(),
                &output,
                &o_strides,
                self.scale,
                self.do_causal,
                itype,
            )
            .map_err(candle_core::Error::wrap)?;
            drop(encoder);
            Ok((
                MetalStorage::new(output, device.clone(), el, dtype),
                Shape::from_dims(&[b, t, h, d]),
            ))
        }
    }
}

#[cfg(all(test, feature = "metal"))]
mod tests {
    use super::sdpa_bthd;
    use candle_core::{DType, Device, Tensor};

    fn max_abs_diff(a: &Tensor, b: &Tensor) -> f32 {
        (a.to_dtype(DType::F32).unwrap() - b.to_dtype(DType::F32).unwrap())
            .unwrap()
            .abs()
            .unwrap()
            .flatten_all()
            .unwrap()
            .max(0)
            .unwrap()
            .to_scalar::<f32>()
            .unwrap()
    }

    /// The `[B, T, H, D]` output is candle's `[B, H, T, D]` output transposed, to the bit,
    /// causal and with a padding mask, with q, k and v as the transposed views the model passes.
    #[test]
    fn metal_output_is_candles_output_transposed() {
        let device = Device::new_metal(0).unwrap();
        let (b, t, h, h_kv, d) = (2usize, 37usize, 4usize, 2usize, 128usize);
        for dtype in [DType::F32, DType::BF16] {
            let view = |heads: usize| {
                Tensor::randn(0f32, 1.0, (b, t, heads, d), &device)
                    .unwrap()
                    .to_dtype(dtype)
                    .unwrap()
                    .transpose(1, 2)
                    .unwrap()
            };
            let (q, k, v) = (view(h), view(h_kv), view(h_kv));
            let scale = (d as f32).powf(-0.5);
            // Left padding on the first row: its first five keys are masked.
            let mut mask = vec![0f32; b * t * t];
            for i in 0..t {
                for j in 0..t {
                    if j > i || j < 5 {
                        mask[i * t + j] = -1e4;
                    }
                }
            }
            let mask = Tensor::from_vec(mask, (b, 1, t, t), &device)
                .unwrap()
                .to_dtype(dtype)
                .unwrap()
                .broadcast_as((b, h, t, t))
                .unwrap();
            for (mask, causal) in [(None, true), (Some(&mask), false)] {
                let expected = candle_nn::ops::sdpa(&q, &k, &v, mask, causal, scale, 1.0)
                    .unwrap()
                    .transpose(1, 2)
                    .unwrap();
                let got = sdpa_bthd(&q, &k, &v, mask, causal, scale).unwrap();
                assert_eq!(got.dims(), &[b, t, h, d]);
                assert!(got.is_contiguous());
                assert_eq!(
                    max_abs_diff(&got, &expected),
                    0.0,
                    "{dtype:?} causal={causal}"
                );
                assert!(max_abs_diff(&got, &got.zeros_like().unwrap()) > 1e-2);

                // The last query alone, against every key, is the full output's last row, to
                // the bit: unmasked where the full run was causal, and through the mask's last
                // row where it was padded. The padding is what candle's vector kernel would drop.
                let last = sdpa_bthd(
                    &q.narrow(2, t - 1, 1).unwrap(),
                    &k,
                    &v,
                    mask.map(|m| {
                        m.narrow(2, t - 1, 1)
                            .unwrap()
                            .contiguous()
                            .unwrap()
                            .broadcast_as((b, h, 1, t))
                            .unwrap()
                    })
                    .as_ref(),
                    false,
                    scale,
                )
                .unwrap();
                assert_eq!(last.dims(), &[b, 1, h, d]);
                assert_eq!(
                    max_abs_diff(&last, &got.narrow(1, t - 1, 1).unwrap()),
                    0.0,
                    "{dtype:?} causal={causal}: the last query alone differs"
                );
            }
        }
    }
}

/// The Metal tests above cover only the fused kernel, which expands grouped heads itself.
/// Off Metal the fallback does it in tensor math, so pin that path with `hkv != groups`.
#[cfg(test)]
mod plain_tests {
    use super::{repeat_kv, sdpa_bthd};
    use candle_core::{Device, Tensor};

    fn max_abs_diff(a: &Tensor, b: &Tensor) -> f32 {
        (a - b)
            .unwrap()
            .abs()
            .unwrap()
            .flatten_all()
            .unwrap()
            .max(0)
            .unwrap()
            .to_scalar::<f32>()
            .unwrap()
    }

    #[test]
    fn repeat_kv_repeats_each_kv_head_contiguously() {
        let device = Device::Cpu;
        // Two kv heads with distinct values, four query heads per kv head.
        let x = Tensor::from_vec(
            vec![1f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0],
            (1, 2, 2, 2),
            &device,
        )
        .unwrap();
        let got = repeat_kv(&x, 4).unwrap();
        assert_eq!(got.dims(), &[1, 8, 2, 2]);
        let mut want = Vec::new();
        for head in [[1.0f32, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0]] {
            for _ in 0..4 {
                want.extend_from_slice(&head);
            }
        }
        let want = Tensor::from_vec(want, (1, 8, 2, 2), &device).unwrap();
        assert_eq!(max_abs_diff(&got, &want), 0.0);
    }

    #[test]
    fn plain_sdpa_expands_grouped_kv_heads() {
        let device = Device::Cpu;
        // `hkv != groups` (and both above one): the case the old axis order got wrong.
        let (b, tq, s, h, hkv, d) = (1usize, 3usize, 4usize, 6usize, 2usize, 3usize);
        let q = Tensor::randn(0f32, 1f32, (b, h, tq, d), &device).unwrap();
        let k = Tensor::randn(0f32, 1f32, (b, hkv, s, d), &device).unwrap();
        let v = Tensor::randn(0f32, 1f32, (b, hkv, s, d), &device).unwrap();
        let groups = h / hkv;
        let expand = |x: &Tensor| {
            let mut heads = Vec::with_capacity(h);
            for head in 0..hkv {
                for _ in 0..groups {
                    heads.push(x.narrow(1, head, 1).unwrap());
                }
            }
            Tensor::cat(&heads, 1).unwrap()
        };
        let (k_exp, v_exp) = (expand(&k), expand(&v));
        let scale = (d as f32).powf(-0.5);
        let scores = q
            .matmul(&k_exp.transpose(2, 3).unwrap().contiguous().unwrap())
            .unwrap();
        let want = candle_nn::ops::softmax_last_dim(&scores.affine(scale as f64, 0.0).unwrap())
            .unwrap()
            .matmul(&v_exp)
            .unwrap()
            .transpose(1, 2)
            .unwrap()
            .contiguous()
            .unwrap();
        let got = sdpa_bthd(&q, &k, &v, None, false, scale).unwrap();
        assert_eq!(got.dims(), &[b, tq, h, d]);
        assert!(
            max_abs_diff(&got, &want) < 1e-5,
            "diff {}",
            max_abs_diff(&got, &want)
        );
    }
}