sam3rs 0.4.0

Real-time Meta SAM 3 in native Rust on NVIDIA GPUs (CUDA) and Apple silicon (Metal): text, box and click segmentation and video tracking, up to 93x faster than PyTorch
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
442
443
444
445
446
447
448
449
450
451
452
453
//! SAM 3 detector: geometry (box) encoder, fusion encoder, DETR decoder with presence
//! token, dot-product scoring and the segmentation head

use eyre::{Result, eyre};

use crate::cuda::gpu::{Buf, Gpu, Tensor, blocks, launch};
use crate::cuda::nvtx::range;
use crate::cuda::ops::{
    Act, Attention, B256, BoxRpb, Conv3x3, LayerNorm, Linear, Mask, Mlp, add, add_assign, bias_act, concat_rows, ew,
    group_norm_stats, upload_i32,
};
use crate::cuda::text::TextFeatures;
use crate::cuda::vision::{Fpn, GRID};
use crate::posenc::{box_encoding, sine_2d};
use crate::precision::Precision;
use crate::prompt::BoxPrompt;
use crate::weights::Weights;

const D: usize = 256;
const HEADS: usize = 8;
pub const QUERIES: usize = 200;
const ROI: usize = 7;

/// Image features the detector reads, computed once per image
pub struct DetectorImage {
    pub fpn: Fpn,
    /// LayerNorm(fpn.coarse) for box ROI pooling
    pub coarse_normed: Tensor,
}

/// Raw detector outputs for one prompt, all on the device
pub struct DetectorOutput {
    /// `[200]` logits before presence
    pub logits: Tensor,
    /// `[1]`
    pub presence: Tensor,
    /// `[200, 4]` normalized cxcywh
    pub boxes: Tensor,
    /// `[200, 288 * 288]`
    pub masks: Tensor,
}

/// Pre-norm encoder layer shared by the geometry and fusion encoders
struct EncoderLayer {
    norm1: LayerNorm,
    self_attn: Attention,
    norm2: LayerNorm,
    cross_attn: Attention,
    norm3: LayerNorm,
    fc1: Linear,
    fc2: Linear,
    /// The FFN runs in BF16 end to end (see [`EncoderLayer::load`])
    ffn16: bool,
}

impl EncoderLayer {
    /// `ffn16` puts the FFN on BF16 cuBLASLt in BF16 mode: the fusion encoder's FFN runs
    /// 5184 tokens through 1M weights per layer, at the TF32 rate otherwise
    fn load(gpu: &Gpu, wts: &Weights, p: &str, ffn16: bool) -> Result<Self> {
        let ffn16 = ffn16 && gpu.precision() == Precision::Bf16;
        let fc = |name: &str| -> Result<Linear> {
            let fc = Linear::load(gpu, wts, &format!("{p}.mlp.{name}"))?;
            if ffn16 { fc.bf16(gpu) } else { Ok(fc) }
        };
        Ok(Self {
            norm1: LayerNorm::load(gpu, wts, &format!("{p}.layer_norm1"), 1e-5)?,
            self_attn: Attention::load(gpu, wts, &format!("{p}.self_attn"), HEADS)?,
            norm2: LayerNorm::load(gpu, wts, &format!("{p}.layer_norm2"), 1e-5)?,
            cross_attn: Attention::load(gpu, wts, &format!("{p}.cross_attn"), HEADS)?,
            norm3: LayerNorm::load(gpu, wts, &format!("{p}.layer_norm3"), 1e-5)?,
            fc1: fc("fc1")?,
            fc2: fc("fc2")?,
            ffn16,
        })
    }

    fn ffn(&self, gpu: &Gpu, x: &Tensor) -> Result<()> {
        if self.ffn16 {
            let h = self.norm3.forward16(gpu, x)?;
            let hidden = self.fc1.forward16_act16(gpu, &h, Act::Relu)?;
            return self.fc2.forward16_residual(gpu, &hidden, x);
        }
        let h = self.norm3.forward(gpu, x)?;
        let hidden = self.fc1.forward_act(gpu, &h, Act::Relu)?;
        self.fc2.forward_residual(gpu, &hidden, x)
    }
}

struct GeometryEncoder {
    direct: Linear,
    pool: Linear,
    pos: Linear,
    label: Tensor,
    cls: Tensor,
    final_proj: Linear,
    prompt_norm: LayerNorm,
    layers: Vec<EncoderLayer>,
    out_norm: LayerNorm,
}

struct DecoderLayer {
    self_attn: Attention,
    self_norm: LayerNorm,
    text_attn: Attention,
    text_norm: LayerNorm,
    image_attn: Attention,
    image_norm: LayerNorm,
    fc1: Linear,
    fc2: Linear,
    mlp_norm: LayerNorm,
}

pub struct Detector {
    vision_norm: LayerNorm,
    geometry: GeometryEncoder,
    encoder: Vec<EncoderLayer>,
    decoder: Vec<DecoderLayer>,
    query_embed: Tensor,
    reference_points: Tensor,
    presence_token: Tensor,
    ref_point_head: Mlp,
    rpb_x: Mlp,
    rpb_y: Mlp,
    box_head: Mlp,
    presence_head: Mlp,
    presence_norm: LayerNorm,
    out_norm: LayerNorm,
    text_mlp: Mlp,
    text_mlp_norm: LayerNorm,
    text_proj: Linear,
    query_proj: Linear,
    seg_attn: Attention,
    seg_attn_norm: LayerNorm,
    pixel_convs: Vec<Conv3x3>,
    pixel_norms: Vec<(Tensor, Tensor)>,
    instance_proj: Linear,
    mask_embed: Mlp,
    /// Sine position encoding of the 72x72 grid `[5184, 256]`
    pos: Tensor,
}

impl Detector {
    pub fn load(gpu: &Gpu, wts: &Weights) -> Result<Self> {
        let p = "detector_model";
        let g = format!("{p}.geometry_encoder");
        let geometry = GeometryEncoder {
            direct: Linear::load(gpu, wts, &format!("{g}.boxes_direct_project"))?,
            pool: Linear::load(gpu, wts, &format!("{g}.boxes_pool_project"))?,
            pos: Linear::load(gpu, wts, &format!("{g}.boxes_pos_enc_project"))?,
            label: wts.get(gpu, &format!("{g}.label_embed.weight"))?,
            cls: wts.get(gpu, &format!("{g}.cls_embed.weight"))?,
            final_proj: Linear::load(gpu, wts, &format!("{g}.final_proj"))?,
            prompt_norm: LayerNorm::load(gpu, wts, &format!("{g}.prompt_layer_norm"), 1e-5)?,
            layers: (0..3)
                .map(|i| EncoderLayer::load(gpu, wts, &format!("{g}.layers.{i}"), false))
                .collect::<Result<_>>()?,
            out_norm: LayerNorm::load(gpu, wts, &format!("{g}.output_layer_norm"), 1e-5)?,
        };
        let encoder = (0..6)
            .map(|i| EncoderLayer::load(gpu, wts, &format!("{p}.detr_encoder.layers.{i}"), true))
            .collect::<Result<_>>()?;
        let dd = format!("{p}.detr_decoder");
        let mut decoder = Vec::new();
        for i in 0..6 {
            let l = format!("{dd}.layers.{i}");
            let ln = |n: &str| LayerNorm::load(gpu, wts, &format!("{l}.{n}"), 1e-5);
            let at = |n: &str| Attention::load(gpu, wts, &format!("{l}.{n}"), HEADS);
            decoder.push(DecoderLayer {
                self_attn: at("self_attn")?,
                self_norm: ln("self_attn_layer_norm")?,
                text_attn: at("text_cross_attn")?,
                text_norm: ln("text_cross_attn_layer_norm")?,
                image_attn: at("vision_cross_attn")?,
                image_norm: ln("vision_cross_attn_layer_norm")?,
                fc1: Linear::load(gpu, wts, &format!("{l}.mlp.fc1"))?,
                fc2: Linear::load(gpu, wts, &format!("{l}.mlp.fc2"))?,
                mlp_norm: ln("mlp_layer_norm")?,
            });
        }
        let s = format!("{p}.dot_product_scoring");
        let m = format!("{p}.mask_decoder");
        Ok(Self {
            vision_norm: LayerNorm::load(gpu, wts, &format!("{g}.vision_layer_norm"), 1e-5)?,
            geometry,
            encoder,
            decoder,
            query_embed: wts.get(gpu, &format!("{dd}.query_embed.weight"))?,
            reference_points: wts.get(gpu, &format!("{dd}.reference_points.weight"))?,
            presence_token: wts.get(gpu, &format!("{dd}.presence_token.weight"))?,
            ref_point_head: Mlp::load_numbered(gpu, wts, &format!("{dd}.ref_point_head"), 2, Act::Relu)?,
            rpb_x: Mlp::load_numbered(gpu, wts, &format!("{dd}.box_rpb_embed_x"), 2, Act::Relu)?,
            rpb_y: Mlp::load_numbered(gpu, wts, &format!("{dd}.box_rpb_embed_y"), 2, Act::Relu)?,
            box_head: Mlp::load_numbered(gpu, wts, &format!("{dd}.box_head"), 3, Act::Relu)?,
            presence_head: Mlp::load_numbered(gpu, wts, &format!("{dd}.presence_head"), 3, Act::Relu)?,
            presence_norm: LayerNorm::load(gpu, wts, &format!("{dd}.presence_layer_norm"), 1e-5)?,
            out_norm: LayerNorm::load(gpu, wts, &format!("{dd}.output_layer_norm"), 1e-5)?,
            text_mlp: Mlp::load_numbered(gpu, wts, &format!("{s}.text_mlp"), 2, Act::Relu)?,
            text_mlp_norm: LayerNorm::load(gpu, wts, &format!("{s}.text_mlp_out_norm"), 1e-5)?,
            text_proj: Linear::load(gpu, wts, &format!("{s}.text_proj"))?,
            query_proj: Linear::load(gpu, wts, &format!("{s}.query_proj"))?,
            seg_attn: Attention::load(gpu, wts, &format!("{m}.prompt_cross_attn"), HEADS)?,
            seg_attn_norm: LayerNorm::load(gpu, wts, &format!("{m}.prompt_cross_attn_norm"), 1e-5)?,
            // the pixel decoder has three convs but only two upsampling stages run
            pixel_convs: (0..2)
                .map(|i| Conv3x3::load(gpu, wts, &format!("{m}.pixel_decoder.conv_layers.{i}")))
                .collect::<Result<_>>()?,
            pixel_norms: (0..2)
                .map(|i| {
                    let n = format!("{m}.pixel_decoder.norms.{i}");
                    Ok((wts.get(gpu, &format!("{n}.weight"))?, wts.get(gpu, &format!("{n}.bias"))?))
                })
                .collect::<Result<_>>()?,
            instance_proj: Linear::load(gpu, wts, &format!("{m}.instance_projection"))?,
            mask_embed: Mlp::load_indexed(gpu, wts, &format!("{m}.mask_embedder"), 3, Act::Relu)?,
            pos: gpu.upload(sine_2d(GRID, 256), &[GRID * GRID, D])?,
        })
    }

    pub fn prepare_image(&self, gpu: &Gpu, fpn: Fpn) -> Result<DetectorImage> {
        let coarse_normed = self.vision_norm.forward(gpu, &fpn.coarse)?;
        Ok(DetectorImage { fpn, coarse_normed })
    }

    /// Geometry tokens: one per box, then the CLS token, all valid
    fn encode_geometry(&self, gpu: &Gpu, img: &DetectorImage, boxes: &[BoxPrompt]) -> Result<Tensor> {
        let g = &self.geometry;
        let n = boxes.len();
        let embeds = if n == 0 {
            gpu.clone_tensor(&g.cls)?
        } else {
            let raw: Vec<f32> = boxes.iter().flat_map(BoxPrompt::cxcywh).collect();
            let raw = gpu.upload(raw, &[n, 4])?;
            let x = g.direct.forward(gpu, &raw)?;

            let side = GRID as f32;
            let xyxy: Vec<f32> = boxes
                .iter()
                .flat_map(|b| {
                    let [cx, cy, w, h] = b.cxcywh();
                    [(cx - 0.5 * w) * side, (cy - 0.5 * h) * side, (cx + 0.5 * w) * side, (cy + 0.5 * h) * side]
                })
                .collect();
            let xyxy = gpu.upload(xyxy, &[n, 4])?;
            let pooled = gpu.empty(&[n, D * ROI * ROI])?;
            launch!(gpu, "roi_align", ew(pooled.len()), B256, 0;
                &pooled, &img.coarse_normed, &xyxy, GRID, GRID, D, ROI)?;
            g.pool.forward_residual(gpu, &pooled, &x)?;

            let enc: Vec<f32> = boxes.iter().flat_map(|b| box_encoding(b.cxcywh())).collect();
            let enc = gpu.upload(enc, &[n, 258])?;
            g.pos.forward_residual(gpu, &enc, &x)?;

            let labels: Vec<i32> = boxes.iter().map(|b| b.positive() as i32).collect();
            let labels = upload_i32(gpu, labels)?;
            let label = gpu.empty(&[n, D])?;
            launch!(gpu, "gather_rows", ew(label.len()), B256, 0; &label, &g.label, labels.slice::<i32>(), D)?;
            add_assign(gpu, &x, &label)?;
            concat_rows(gpu, &x, &g.cls)?
        };

        let x = g.final_proj.forward(gpu, &embeds)?;
        g.prompt_norm.forward_inplace(gpu, &x)?;
        let mem_pos = add(gpu, &img.fpn.coarse, &self.pos)?;
        for l in &g.layers {
            let h = l.norm1.forward(gpu, &x)?;
            l.self_attn.forward_residual(gpu, &h, &h, &h, Mask::default(), &x)?;
            let h = l.norm2.forward(gpu, &x)?;
            l.cross_attn.forward_residual(gpu, &h, &mem_pos, &img.fpn.coarse, Mask::default(), &x)?;
            l.ffn(gpu, &x)?;
        }
        g.out_norm.forward_inplace(gpu, &x)?;
        Ok(x)
    }

    pub fn forward(
        &self,
        gpu: &Gpu,
        img: &DetectorImage,
        text: &TextFeatures,
        boxes: &[BoxPrompt],
    ) -> Result<DetectorOutput> {
        let geo = {
            let _r = range(c"geometry");
            self.encode_geometry(gpu, img, boxes)?
        };
        let prompt = concat_rows(gpu, &text.feats, &geo)?;
        let mut pad = text.pad.to_vec();
        pad.resize(prompt.rows(), 0);
        let pad = gpu.upload_buf(pad)?;
        let prompt_mask = Mask { key_pad: pad.ptr(), ..Mask::default() };

        let memory = {
            let _r = range(c"fusion_encoder");
            self.fusion_encoder(gpu, img, &prompt, prompt_mask)?
        };
        let (hs, boxes, presence) = {
            let _r = range(c"decoder");
            self.decode(gpu, &memory, &prompt, prompt_mask)?
        };
        let logits = self.score(gpu, &hs, &prompt, &pad)?;
        let masks = {
            let _r = range(c"seg_head");
            self.segment(gpu, img, &memory, &hs, &prompt, prompt_mask)?
        };
        Ok(DetectorOutput { logits, presence, boxes, masks })
    }

    fn fusion_encoder(&self, gpu: &Gpu, img: &DetectorImage, prompt: &Tensor, prompt_mask: Mask) -> Result<Tensor> {
        let x = gpu.clone_tensor(&img.fpn.coarse)?;
        for l in &self.encoder {
            let h = l.norm1.forward(gpu, &x)?;
            let qk = add(gpu, &h, &self.pos)?;
            l.self_attn.forward_residual(gpu, &qk, &qk, &h, Mask::default(), &x)?;
            drop((h, qk));
            let h = l.norm2.forward(gpu, &x)?;
            l.cross_attn.forward_residual(gpu, &h, prompt, prompt, prompt_mask, &x)?;
            l.ffn(gpu, &x)?;
        }
        Ok(x)
    }

    /// Returns normed final query states `[200, 256]`, boxes `[200, 4]` and the presence
    /// logit `[1]`
    fn decode(
        &self,
        gpu: &Gpu,
        memory: &Tensor,
        prompt: &Tensor,
        prompt_mask: Mask,
    ) -> Result<(Tensor, Tensor, Tensor)> {
        let n = QUERIES + 1;
        // row 0 is the presence token, which has a zero query position
        let x = concat_rows(gpu, &self.presence_token, &self.query_embed)?;
        let mut boxes = gpu.clone_tensor(&self.reference_points)?;
        bias_act(gpu, &boxes, None, Act::Sigmoid)?;
        let mem_pos = add(gpu, memory, &self.pos)?;
        let qpos = gpu.zeros(&[n, D])?;
        let mut hs = None;

        for (i, l) in self.decoder.iter().enumerate() {
            let sine = gpu.empty(&[QUERIES, 2 * D])?;
            launch!(gpu, "box_sine_embed", ew(sine.len()), B256, 0; &sine, &boxes)?;
            let pos = self.ref_point_head.forward(gpu, &sine)?;
            gpu.copy_dtod(pos.ptr(), qpos.at(D), pos.len() * 4)?;
            let [dx, dy] = self.box_rpb(gpu, &boxes)?;

            let qk = add(gpu, &x, &qpos)?;
            l.self_attn.forward_residual(gpu, &qk, &qk, &x, Mask::default(), &x)?;
            l.self_norm.forward_inplace(gpu, &x)?;

            let q = add(gpu, &x, &qpos)?;
            l.text_attn.forward_residual(gpu, &q, prompt, prompt, prompt_mask, &x)?;
            l.text_norm.forward_inplace(gpu, &x)?;

            let q = add(gpu, &x, &qpos)?;
            let rpb = Mask { rpb: Some(BoxRpb { dx: dx.ptr(), dy: dy.ptr(), side: GRID }), ..Mask::default() };
            l.image_attn.forward_residual(gpu, &q, &mem_pos, memory, rpb, &x)?;
            l.image_norm.forward_inplace(gpu, &x)?;

            let hidden = l.fc1.forward_act(gpu, &x, Act::Relu)?;
            l.fc2.forward_residual(gpu, &hidden, &x)?;
            l.mlp_norm.forward_inplace(gpu, &x)?;

            let queries = gpu.empty(&[QUERIES, D])?;
            gpu.copy_dtod(x.at(D), queries.ptr(), QUERIES * D * 4)?;
            let normed = self.out_norm.forward(gpu, &queries)?;
            let delta = self.box_head.forward(gpu, &normed)?;
            let refined = gpu.empty(&[QUERIES, 4])?;
            launch!(gpu, "box_refine", ew(refined.len()), B256, 0; &refined, &boxes, &delta)?;
            boxes = refined;

            // only the last layer's queries are kept, so earlier ones free before the next layer
            if i + 1 == self.decoder.len() {
                hs = Some(normed);
            }
        }
        let hs = hs.ok_or_else(|| eyre!("the detector has no decoder layers"))?;

        // the presence token is row 0 of the last layer's output
        let p = gpu.empty(&[1, D])?;
        gpu.copy_dtod(x.ptr(), p.ptr(), D * 4)?;
        let p = self.presence_norm.forward(gpu, &p)?;
        let presence = self.presence_head.forward(gpu, &p)?;
        Ok((hs, boxes, presence))
    }

    /// Box relative position bias for the image cross-attention in factored form, `dx`
    /// and `dy` as `[8, 200, 72]` (see [`BoxRpb`])
    fn box_rpb(&self, gpu: &Gpu, boxes: &Tensor) -> Result<[Tensor; 2]> {
        let delta = |axis: usize, mlp: &Mlp| -> Result<Tensor> {
            let d = gpu.empty(&[QUERIES * GRID, 2])?;
            launch!(gpu, "rpb_deltas", ew(d.len()), B256, 0; &d, boxes, GRID, axis)?;
            // the MLP gives [200 * 72, heads]; head-major rows let the attention kernel
            // read a query's biases contiguously instead of one float per 32-byte sector
            let per_pos = mlp.forward(gpu, &d)?;
            let heads = per_pos.cols();
            let out = gpu.empty(&[heads, QUERIES * GRID])?;
            launch!(gpu, "transpose", ew(out.len()), B256, 0; &out, &per_pos, heads)?;
            Ok(out)
        };
        Ok([delta(0, &self.rpb_x)?, delta(1, &self.rpb_y)?])
    }

    fn score(&self, gpu: &Gpu, hs: &Tensor, prompt: &Tensor, pad: &Buf) -> Result<Tensor> {
        let p = self.text_mlp.forward(gpu, prompt)?;
        add_assign(gpu, &p, prompt)?;
        self.text_mlp_norm.forward_inplace(gpu, &p)?;
        let pooled = gpu.empty(&[1, D])?;
        // one thread per output column; the kernel takes the prompt length from p's rows
        launch!(gpu, "masked_mean", (blocks(D, 256), 1, 1), B256, 0; &pooled, &p, pad.slice::<u8>())?;
        let pp = self.text_proj.forward(gpu, &pooled)?;
        let ph = self.query_proj.forward(gpu, hs)?;
        let scores = gpu.empty(&[QUERIES])?;
        let scale = 1.0 / (D as f32).sqrt();
        launch!(gpu, "dot_scores", ((QUERIES as u32).div_ceil(8), 1, 1), B256, 0; &scores, &ph, &pp, scale, 12.0f32)?;
        Ok(scores)
    }

    fn segment(
        &self,
        gpu: &Gpu,
        img: &DetectorImage,
        memory: &Tensor,
        hs: &Tensor,
        prompt: &Tensor,
        prompt_mask: Mask,
    ) -> Result<Tensor> {
        let h = self.seg_attn_norm.forward(gpu, memory)?;
        let enc = gpu.clone_tensor(memory)?;
        self.seg_attn.forward_residual(gpu, &h, prompt, prompt, prompt_mask, &enc)?;
        drop(h);

        // each level's group norm is applied as the next level's conv reads it
        let mut prev = enc;
        let mut norm = None;
        let mut side = GRID;
        for (i, fine) in [&img.fpn.mid, &img.fpn.fine].into_iter().enumerate() {
            side *= 2;
            prev = self.pixel_convs[i].forward_up(gpu, fine, &prev, norm.as_ref(), side, side)?;
            let (w, b) = &self.pixel_norms[i];
            norm = Some(group_norm_stats(gpu, &prev, 8, w, b, 1e-5, Act::Relu)?);
        }
        norm.expect("two pixel decoder levels").apply(gpu, &prev)?;
        let instance = self.instance_proj.forward(gpu, &prev)?;
        drop(prev);
        let embed = self.mask_embed.forward(gpu, hs)?;
        // masks [200, 288^2] = embed [200, 256] @ instance^T
        let masks = gpu.empty(&[QUERIES, side * side])?;
        let lin = Linear::new(instance, None);
        lin.forward_raw(gpu, embed.ptr(), D, QUERIES, masks.ptr(), 0.0)?;
        Ok(masks)
    }
}