rlx-vjepa2 0.2.4

V-JEPA 2 video encoder for RLX
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
// RLX — versatile ML compiler + runtime.
// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Weight extraction for V-JEPA2 checkpoints (HF + Meta key layouts).

use super::config::Vjepa2Config;
use super::preprocess::{Vjepa2PatchEmbedWeights, extract_patch_embed_weights};
use anyhow::{Result, ensure};
use rlx_core::weight_map::WeightMap;

#[derive(Clone)]
pub struct Vjepa2BlockWeights {
    pub norm1_w: Vec<f32>,
    pub norm1_b: Vec<f32>,
    pub q_w_t: Vec<f32>,
    pub q_b: Vec<f32>,
    pub k_w_t: Vec<f32>,
    pub k_b: Vec<f32>,
    pub v_w_t: Vec<f32>,
    pub v_b: Vec<f32>,
    pub proj_w_t: Vec<f32>,
    pub proj_b: Vec<f32>,
    pub norm2_w: Vec<f32>,
    pub norm2_b: Vec<f32>,
    pub mlp_fc1_w_t: Vec<f32>,
    pub mlp_fc1_b: Vec<f32>,
    pub mlp_fc2_w_t: Vec<f32>,
    pub mlp_fc2_b: Vec<f32>,
}

#[derive(Clone)]
pub struct Vjepa2EncoderWeights {
    pub patch: Vjepa2PatchEmbedWeights,
    pub blocks: Vec<Vjepa2BlockWeights>,
    pub norm_w: Vec<f32>,
    pub norm_b: Vec<f32>,
}

#[derive(Clone)]
pub struct Vjepa2PredictorWeights {
    pub embed_w_t: Vec<f32>,
    pub embed_b: Vec<f32>,
    pub mask_tokens: Vec<f32>,
    pub blocks: Vec<Vjepa2BlockWeights>,
    pub norm_w: Vec<f32>,
    pub norm_b: Vec<f32>,
    pub proj_w_t: Vec<f32>,
    pub proj_b: Vec<f32>,
}

#[derive(Clone)]
pub struct Vjepa2PoolerSelfBlockWeights {
    pub norm1_w: Vec<f32>,
    pub norm1_b: Vec<f32>,
    pub q_w_t: Vec<f32>,
    pub q_b: Vec<f32>,
    pub k_w_t: Vec<f32>,
    pub k_b: Vec<f32>,
    pub v_w_t: Vec<f32>,
    pub v_b: Vec<f32>,
    pub out_w_t: Vec<f32>,
    pub out_b: Vec<f32>,
    pub norm2_w: Vec<f32>,
    pub norm2_b: Vec<f32>,
    pub mlp_fc1_w_t: Vec<f32>,
    pub mlp_fc1_b: Vec<f32>,
    pub mlp_fc2_w_t: Vec<f32>,
    pub mlp_fc2_b: Vec<f32>,
}

#[derive(Clone)]
pub struct Vjepa2PoolerCrossWeights {
    pub norm1_w: Vec<f32>,
    pub norm1_b: Vec<f32>,
    pub q_w_t: Vec<f32>,
    pub q_b: Vec<f32>,
    pub k_w_t: Vec<f32>,
    pub k_b: Vec<f32>,
    pub v_w_t: Vec<f32>,
    pub v_b: Vec<f32>,
    pub norm2_w: Vec<f32>,
    pub norm2_b: Vec<f32>,
    pub mlp_fc1_w_t: Vec<f32>,
    pub mlp_fc1_b: Vec<f32>,
    pub mlp_fc2_w_t: Vec<f32>,
    pub mlp_fc2_b: Vec<f32>,
}

#[derive(Clone)]
pub struct Vjepa2PoolerWeights {
    pub query_tokens: Vec<f32>,
    pub self_blocks: Vec<Vjepa2PoolerSelfBlockWeights>,
    pub cross: Vjepa2PoolerCrossWeights,
    pub classifier_w_t: Option<Vec<f32>>,
    pub classifier_b: Option<Vec<f32>>,
}

#[derive(Clone)]
pub struct Vjepa2ModelWeights {
    pub encoder: Vjepa2EncoderWeights,
    pub predictor: Option<Vjepa2PredictorWeights>,
    pub pooler: Option<Vjepa2PoolerWeights>,
}

pub fn extract_encoder_weights(
    weights: &mut WeightMap,
    cfg: &Vjepa2Config,
) -> Result<Vjepa2EncoderWeights> {
    let patch = extract_patch_embed_weights(weights, cfg)?;
    let e = cfg.hidden_size;
    let hidden = cfg.intermediate_size();
    let mut blocks = Vec::with_capacity(cfg.num_hidden_layers);

    for i in 0..cfg.num_hidden_layers {
        let hf = format!("encoder.layer.{i}");
        let meta = format!("blocks.{i}");
        blocks.push(extract_transformer_block(
            weights,
            &[hf, meta],
            e,
            hidden,
            "attention",
            "attn",
        )?);
    }

    let norm_w = take_first_vec(
        weights,
        &["encoder.layernorm.weight", "norm.weight"],
        vec![e],
    )?;
    let norm_b = take_first_vec(weights, &["encoder.layernorm.bias", "norm.bias"], vec![e])?;

    Ok(Vjepa2EncoderWeights {
        patch,
        blocks,
        norm_w,
        norm_b,
    })
}

pub fn extract_predictor_weights(
    weights: &mut WeightMap,
    cfg: &Vjepa2Config,
) -> Result<Vjepa2PredictorWeights> {
    let enc = cfg.hidden_size;
    let pred = cfg.pred_hidden_size;
    let hidden = cfg.pred_intermediate_size();

    let embed_key = pick_key(
        weights,
        &[
            "predictor.embeddings.predictor_embeddings.weight",
            "predictor_embed.weight",
        ],
    )?;
    let embed_w_t = take_linear_w_key(weights, &embed_key, enc, pred)?;
    let embed_b = take_first_vec(
        weights,
        &[
            "predictor.embeddings.predictor_embeddings.bias",
            "predictor_embed.bias",
        ],
        vec![pred],
    )?;

    let n_masks = cfg.pred_num_mask_tokens;
    let mask_tokens = take_first_vec(
        weights,
        &["predictor.embeddings.mask_tokens", "mask_tokens"],
        vec![n_masks, 1, 1, pred],
    )?;

    let mut blocks = Vec::with_capacity(cfg.pred_num_hidden_layers);
    for i in 0..cfg.pred_num_hidden_layers {
        let hf = format!("predictor.layer.{i}");
        let meta = format!("predictor_blocks.{i}");
        blocks.push(extract_transformer_block(
            weights,
            &[hf, meta],
            pred,
            hidden,
            "attention",
            "attn",
        )?);
    }

    let norm_w = take_first_vec(
        weights,
        &["predictor.layernorm.weight", "predictor_norm.weight"],
        vec![pred],
    )?;
    let norm_b = take_first_vec(
        weights,
        &["predictor.layernorm.bias", "predictor_norm.bias"],
        vec![pred],
    )?;
    let proj_key = pick_key(weights, &["predictor.proj.weight", "predictor_proj.weight"])?;
    let proj_w_t = take_linear_w_key(weights, &proj_key, pred, enc)?;
    let proj_b = take_first_vec(
        weights,
        &["predictor.proj.bias", "predictor_proj.bias"],
        vec![enc],
    )?;

    Ok(Vjepa2PredictorWeights {
        embed_w_t,
        embed_b,
        mask_tokens,
        blocks,
        norm_w,
        norm_b,
        proj_w_t,
        proj_b,
    })
}

pub fn extract_pooler_weights(
    weights: &mut WeightMap,
    cfg: &Vjepa2Config,
) -> Result<Vjepa2PoolerWeights> {
    let e = cfg.hidden_size;
    let hidden = cfg.pooler_intermediate_size();

    let query_tokens = take_first_vec(weights, &["pooler.query_tokens"], vec![1, 1, e])?;

    let mut self_blocks = Vec::with_capacity(cfg.num_pooler_layers);
    for i in 0..cfg.num_pooler_layers {
        let p = format!("pooler.self_attention_layers.{i}");
        self_blocks.push(Vjepa2PoolerSelfBlockWeights {
            norm1_w: take_ln_w(weights, &[&p], "layer_norm1", e)?,
            norm1_b: take_ln_b(weights, &[&p], "layer_norm1", e)?,
            q_w_t: take_linear_w_key(weights, &format!("{p}.self_attn.q_proj.weight"), e, e)?,
            q_b: take_first_vec(weights, &[&format!("{p}.self_attn.q_proj.bias")], vec![e])?,
            k_w_t: take_linear_w_key(weights, &format!("{p}.self_attn.k_proj.weight"), e, e)?,
            k_b: take_first_vec(weights, &[&format!("{p}.self_attn.k_proj.bias")], vec![e])?,
            v_w_t: take_linear_w_key(weights, &format!("{p}.self_attn.v_proj.weight"), e, e)?,
            v_b: take_first_vec(weights, &[&format!("{p}.self_attn.v_proj.bias")], vec![e])?,
            out_w_t: take_linear_w_key(weights, &format!("{p}.self_attn.out_proj.weight"), e, e)?,
            out_b: take_first_vec(weights, &[&format!("{p}.self_attn.out_proj.bias")], vec![e])?,
            norm2_w: take_ln_w(weights, &[&p], "layer_norm2", e)?,
            norm2_b: take_ln_b(weights, &[&p], "layer_norm2", e)?,
            mlp_fc1_w_t: take_linear_w_key(weights, &format!("{p}.mlp.fc1.weight"), e, hidden)?,
            mlp_fc1_b: take_first_vec(weights, &[&format!("{p}.mlp.fc1.bias")], vec![hidden])?,
            mlp_fc2_w_t: take_linear_w_key(weights, &format!("{p}.mlp.fc2.weight"), hidden, e)?,
            mlp_fc2_b: take_first_vec(weights, &[&format!("{p}.mlp.fc2.bias")], vec![e])?,
        });
    }

    let cp = "pooler.cross_attention_layer";
    let cross = Vjepa2PoolerCrossWeights {
        norm1_w: take_ln_w(weights, &[cp], "layer_norm1", e)?,
        norm1_b: take_ln_b(weights, &[cp], "layer_norm1", e)?,
        q_w_t: take_linear_w_key(weights, &format!("{cp}.cross_attn.q_proj.weight"), e, e)?,
        q_b: take_first_vec(weights, &[&format!("{cp}.cross_attn.q_proj.bias")], vec![e])?,
        k_w_t: take_linear_w_key(weights, &format!("{cp}.cross_attn.k_proj.weight"), e, e)?,
        k_b: take_first_vec(weights, &[&format!("{cp}.cross_attn.k_proj.bias")], vec![e])?,
        v_w_t: take_linear_w_key(weights, &format!("{cp}.cross_attn.v_proj.weight"), e, e)?,
        v_b: take_first_vec(weights, &[&format!("{cp}.cross_attn.v_proj.bias")], vec![e])?,
        norm2_w: take_ln_w(weights, &[cp], "layer_norm2", e)?,
        norm2_b: take_ln_b(weights, &[cp], "layer_norm2", e)?,
        mlp_fc1_w_t: take_linear_w_key(weights, &format!("{cp}.mlp.fc1.weight"), e, hidden)?,
        mlp_fc1_b: take_first_vec(weights, &[&format!("{cp}.mlp.fc1.bias")], vec![hidden])?,
        mlp_fc2_w_t: take_linear_w_key(weights, &format!("{cp}.mlp.fc2.weight"), hidden, e)?,
        mlp_fc2_b: take_first_vec(weights, &[&format!("{cp}.mlp.fc2.bias")], vec![e])?,
    };

    let classifier_w_t = if weights.has("classifier.weight") {
        let (data, shape) = weights.take_transposed("classifier.weight")?;
        ensure!(shape[1] == e, "classifier weight second dim must be {e}");
        Some(data)
    } else {
        None
    };
    let classifier_b = if weights.has("classifier.bias") {
        let (data, shape) = weights.take("classifier.bias")?;
        ensure!(shape.len() == 1, "classifier bias must be 1d");
        Some(data)
    } else {
        None
    };

    Ok(Vjepa2PoolerWeights {
        query_tokens,
        self_blocks,
        cross,
        classifier_w_t,
        classifier_b,
    })
}

pub fn extract_model_weights(
    weights: &mut WeightMap,
    cfg: &Vjepa2Config,
) -> Result<Vjepa2ModelWeights> {
    let encoder = extract_encoder_weights(weights, cfg)?;
    let predictor = if weights.has("predictor.layer.0.attention.query.weight")
        || weights.has("predictor_blocks.0.attn.qkv.weight")
    {
        Some(extract_predictor_weights(weights, cfg)?)
    } else {
        None
    };
    let pooler = if weights.has("pooler.query_tokens") {
        Some(extract_pooler_weights(weights, cfg)?)
    } else {
        None
    };
    Ok(Vjepa2ModelWeights {
        encoder,
        predictor,
        pooler,
    })
}

pub(crate) fn extract_transformer_block(
    weights: &mut WeightMap,
    prefixes: &[String],
    embed: usize,
    hidden: usize,
    attn_hf: &str,
    attn_meta: &str,
) -> Result<Vjepa2BlockWeights> {
    let pref_refs: Vec<&str> = prefixes.iter().map(String::as_str).collect();
    Ok(Vjepa2BlockWeights {
        norm1_w: take_ln_w(weights, &pref_refs, "norm1", embed)?,
        norm1_b: take_ln_b(weights, &pref_refs, "norm1", embed)?,
        q_w_t: take_linear_w(
            weights, &pref_refs, "query", embed, embed, attn_hf, attn_meta,
        )?,
        q_b: take_linear_b(weights, &pref_refs, "query", embed, attn_hf, attn_meta)?,
        k_w_t: take_linear_w(weights, &pref_refs, "key", embed, embed, attn_hf, attn_meta)?,
        k_b: take_linear_b(weights, &pref_refs, "key", embed, attn_hf, attn_meta)?,
        v_w_t: take_linear_w(
            weights, &pref_refs, "value", embed, embed, attn_hf, attn_meta,
        )?,
        v_b: take_linear_b(weights, &pref_refs, "value", embed, attn_hf, attn_meta)?,
        proj_w_t: take_attn_proj_w(weights, &pref_refs, embed, attn_hf, attn_meta)?,
        proj_b: take_attn_proj_b(weights, &pref_refs, embed, attn_hf, attn_meta)?,
        norm2_w: take_ln_w(weights, &pref_refs, "norm2", embed)?,
        norm2_b: take_ln_b(weights, &pref_refs, "norm2", embed)?,
        mlp_fc1_w_t: take_mlp_w(weights, &pref_refs, "fc1", embed, hidden)?,
        mlp_fc1_b: take_mlp_b(weights, &pref_refs, "fc1", hidden)?,
        mlp_fc2_w_t: take_mlp_w(weights, &pref_refs, "fc2", hidden, embed)?,
        mlp_fc2_b: take_mlp_b(weights, &pref_refs, "fc2", embed)?,
    })
}

fn pick_key(weights: &WeightMap, keys: &[&str]) -> Result<String> {
    for k in keys {
        if weights.has(k) {
            return Ok((*k).to_string());
        }
    }
    anyhow::bail!("none of keys found: {keys:?}")
}

fn take_attn_proj_w(
    weights: &mut WeightMap,
    prefixes: &[&str],
    e: usize,
    attn_hf: &str,
    attn_meta: &str,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let hf = format!("{p}.{attn_hf}.proj.weight");
        if weights.has(&hf) {
            return take_linear_w_key(weights, &hf, e, e);
        }
        let meta = format!("{p}.{attn_meta}.proj.weight");
        if weights.has(&meta) {
            return take_linear_w_key(weights, &meta, e, e);
        }
    }
    anyhow::bail!("attention proj weight not found for {prefixes:?}")
}

fn take_attn_proj_b(
    weights: &mut WeightMap,
    prefixes: &[&str],
    e: usize,
    attn_hf: &str,
    attn_meta: &str,
) -> Result<Vec<f32>> {
    for p in prefixes {
        for suffix in [
            format!("{attn_hf}.proj.bias"),
            format!("{attn_meta}.proj.bias"),
        ] {
            let key = format!("{p}.{suffix}");
            if weights.has(&key) {
                let (data, shape) = weights.take(&key)?;
                ensure!(shape == vec![e]);
                return Ok(data);
            }
        }
    }
    anyhow::bail!("attention proj bias not found")
}

fn take_linear_w(
    weights: &mut WeightMap,
    prefixes: &[&str],
    name: &str,
    in_dim: usize,
    out_dim: usize,
    attn_hf: &str,
    attn_meta: &str,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let hf = format!("{p}.{attn_hf}.{name}.weight");
        if weights.has(&hf) {
            return take_linear_w_key(weights, &hf, in_dim, out_dim);
        }
    }
    for p in prefixes {
        if !p.starts_with("blocks.") && !p.starts_with("predictor_blocks.") {
            continue;
        }
        let key = format!("{p}.{attn_meta}.qkv.weight");
        if weights.has(&key) {
            let (data, shape) = weights.take_transposed(&key)?;
            ensure!(shape == vec![in_dim, 3 * out_dim]);
            return Ok(split_qkv_w(&data, in_dim, out_dim, name));
        }
    }
    anyhow::bail!("linear weight {name} not found for {prefixes:?}")
}

fn take_linear_b(
    weights: &mut WeightMap,
    prefixes: &[&str],
    name: &str,
    dim: usize,
    attn_hf: &str,
    attn_meta: &str,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let hf = format!("{p}.{attn_hf}.{name}.bias");
        if weights.has(&hf) {
            let (data, shape) = weights.take(&hf)?;
            ensure!(shape == vec![dim]);
            return Ok(data);
        }
    }
    for p in prefixes {
        if !p.starts_with("blocks.") && !p.starts_with("predictor_blocks.") {
            continue;
        }
        let key = format!("{p}.{attn_meta}.qkv.bias");
        if weights.has(&key) {
            let (data, shape) = weights.take(&key)?;
            ensure!(shape == vec![3 * dim]);
            return Ok(split_qkv_b(&data, dim, name));
        }
    }
    anyhow::bail!("linear bias {name} not found")
}

fn split_qkv_w(data: &[f32], in_dim: usize, out_dim: usize, which: &str) -> Vec<f32> {
    let off = match which {
        "query" => 0,
        "key" => out_dim,
        "value" => 2 * out_dim,
        _ => panic!("bad qkv split {which}"),
    };
    let mut out = vec![0f32; in_dim * out_dim];
    for i in 0..in_dim {
        for j in 0..out_dim {
            out[i * out_dim + j] = data[i * 3 * out_dim + off + j];
        }
    }
    out
}

fn split_qkv_b(data: &[f32], dim: usize, which: &str) -> Vec<f32> {
    let off = match which {
        "query" => 0,
        "key" => dim,
        "value" => 2 * dim,
        _ => panic!("bad qkv split {which}"),
    };
    data[off..off + dim].to_vec()
}

fn take_mlp_w(
    weights: &mut WeightMap,
    prefixes: &[&str],
    fc: &str,
    in_dim: usize,
    out_dim: usize,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let key = format!("{p}.mlp.{fc}.weight");
        if weights.has(&key) {
            return take_linear_w_key(weights, &key, in_dim, out_dim);
        }
    }
    anyhow::bail!("mlp {fc} weight not found")
}

fn take_mlp_b(
    weights: &mut WeightMap,
    prefixes: &[&str],
    fc: &str,
    dim: usize,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let key = format!("{p}.mlp.{fc}.bias");
        if weights.has(&key) {
            let (data, shape) = weights.take(&key)?;
            ensure!(shape == vec![dim]);
            return Ok(data);
        }
    }
    anyhow::bail!("mlp {fc} bias not found")
}

fn take_ln_w(
    weights: &mut WeightMap,
    prefixes: &[&str],
    norm: &str,
    dim: usize,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let key = format!("{p}.{norm}.weight");
        if weights.has(&key) {
            let (data, shape) = weights.take(&key)?;
            ensure!(shape == vec![dim]);
            return Ok(data);
        }
    }
    anyhow::bail!("{norm} weight not found")
}

fn take_ln_b(
    weights: &mut WeightMap,
    prefixes: &[&str],
    norm: &str,
    dim: usize,
) -> Result<Vec<f32>> {
    for p in prefixes {
        let key = format!("{p}.{norm}.bias");
        if weights.has(&key) {
            let (data, shape) = weights.take(&key)?;
            ensure!(shape == vec![dim]);
            return Ok(data);
        }
    }
    anyhow::bail!("{norm} bias not found")
}

fn take_linear_w_key(
    weights: &mut WeightMap,
    key: &str,
    in_dim: usize,
    out_dim: usize,
) -> Result<Vec<f32>> {
    let (data, shape) = weights.take_transposed(key)?;
    ensure!(
        shape == vec![in_dim, out_dim],
        "{key} expected [{in_dim}, {out_dim}], got {shape:?}"
    );
    Ok(data)
}

fn take_first_vec(
    weights: &mut WeightMap,
    keys: &[&str],
    expected: Vec<usize>,
) -> Result<Vec<f32>> {
    for key in keys {
        if weights.has(key) {
            let (data, shape) = weights.take(key)?;
            ensure!(
                shape == expected,
                "{key} shape mismatch: {shape:?} vs {expected:?}"
            );
            return Ok(data);
        }
    }
    anyhow::bail!("keys not found: {keys:?}")
}