File size: 24,461 Bytes
88b959f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any

import torch
import torch.nn.functional as F
from torch import nn
from transformers import AutoConfig, AutoModel, AutoTokenizer, PretrainedConfig, PreTrainedModel

RELEASE_FILES = ("config.json", "pooler.safetensors", "backbone/config.json")
CHUNK_WINDOW, CHUNK_STRIDE, CHUNK_WEIGHT = 512, 256, 0.75


def chunk_mix_scores(queries: torch.Tensor, documents: torch.Tensor, windows: torch.Tensor, owner: torch.Tensor,
                     weight: float = CHUNK_WEIGHT, block: int = 256) -> torch.Tensor:
    q = torch.as_tensor(queries).float()
    full = q @ torch.as_tensor(documents).float().to(q.device).T
    if len(windows) == 0:
        return full
    w = torch.as_tensor(windows).float().to(q.device)
    owner = torch.as_tensor(owner, dtype=torch.long, device=q.device)
    best = torch.full_like(full, -torch.inf)
    for start in range(0, len(q), block):
        part = q[start : start + block] @ w.T
        best[start : start + block] = best[start : start + block].scatter_reduce(1, owner.expand(len(part), -1), part, "amax")
    return torch.where(torch.isfinite(best), weight * best + (1 - weight) * full, full)


FUSE_DENSE_WEIGHT, FUSE_DENSE_WINDOW_WEIGHT, FUSE_MAXSIM_WINDOW_WEIGHT = 0.25, 0.5, 0.5
FUSE_DENSE_ONLY_MAX_TOKENS: int | None = None
FUSE_QUERY_MAX_LENGTH = 1024


def best_per_document(scores: torch.Tensor, owner: torch.Tensor, documents: int) -> torch.Tensor:
    best = torch.full((scores.shape[0], documents), -torch.inf, device=scores.device)
    return best.scatter_reduce(1, owner.to(scores.device).expand(scores.shape[0], -1), scores, "amax")


def maxsim_scores(queries: list[torch.Tensor], documents: list[torch.Tensor], query_block: int = 256,
                  budget: int | None = None) -> torch.Tensor:
    device = queries[0].device
    budget = budget or (2**28 if device.type == "cuda" else 2**24)

    def pad(rows):
        length = max(len(r) for r in rows)
        out = torch.zeros(len(rows), length, rows[0].shape[1], device=device)
        mask = torch.zeros(len(rows), length, dtype=torch.bool, device=device)
        for i, r in enumerate(rows):
            out[i, : len(r)], mask[i, : len(r)] = r.to(device).float(), True
        return out, mask

    q_order = sorted(range(len(queries)), key=lambda i: len(queries[i]))
    d_order = sorted(range(len(documents)), key=lambda i: len(documents[i]))
    result = torch.empty(len(queries), len(documents), device=device)
    for qs in range(0, len(q_order), query_block):
        q_index = q_order[qs : qs + query_block]
        q, qm = pad([queries[i] for i in q_index])
        rows = torch.tensor(q_index, device=device)
        ds = 0
        while ds < len(d_order):
            longest = len(documents[d_order[min(ds + 255, len(d_order) - 1)]])
            step = max(1, min(256, budget // (q.shape[0] * q.shape[1] * max(1, longest))))
            d_index = d_order[ds : ds + step]
            d, dm = pad([documents[i] for i in d_index])
            sim = torch.einsum("qld,cmd->qclm", q, d).masked_fill_(~dm[None, :, None, :], -torch.inf).amax(-1)
            sim = sim.masked_fill(~qm[:, None, :], 0).sum(-1) / qm.sum(-1, keepdim=True)
            result[rows[:, None], torch.tensor(d_index, device=device)[None, :]] = sim
            ds += step
    return result


def fuse_scores(dense_full: torch.Tensor, dense_window: torch.Tensor, maxsim_full: torch.Tensor | None,
                maxsim_window: torch.Tensor, document_tokens: torch.Tensor | None = None,
                dense_weight: float = FUSE_DENSE_WEIGHT, dense_window_weight: float = FUSE_DENSE_WINDOW_WEIGHT,
                maxsim_window_weight: float = FUSE_MAXSIM_WINDOW_WEIGHT,
                dense_only_max_tokens: int | None = FUSE_DENSE_ONLY_MAX_TOKENS) -> torch.Tensor:
    dense = dense_window_weight * dense_window + (1 - dense_window_weight) * dense_full
    maxsim = maxsim_window if maxsim_window_weight == 1 else maxsim_window_weight * maxsim_window + (1 - maxsim_window_weight) * maxsim_full
    fused = dense_weight * dense + (1 - dense_weight) * maxsim
    if dense_only_max_tokens is None:
        return fused
    if document_tokens is None:
        raise ValueError("dense_only_max_tokens needs document_tokens")
    short = torch.as_tensor(document_tokens, device=fused.device) <= dense_only_max_tokens
    return torch.where(short[None, :], dense, fused)


class Hyper3EmbedConfig(PretrainedConfig):

    model_type = "hyper3_embed"

    def __init__(self, backbone_subfolder: str = "backbone", embedding_dim: int = 1536, max_length: int = 4096,
                 embedding_config: dict[str, Any] | None = None, prompt_config: dict[str, Any] | None = None,
                 **kwargs: Any) -> None:
        self.backbone_subfolder = backbone_subfolder
        self.embedding_dim = embedding_dim
        self.max_length = max_length
        self.embedding_config = embedding_config if embedding_config is not None else {}
        self.prompt_config = prompt_config if prompt_config is not None else {}
        super().__init__(**kwargs)


class _GEGLU(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        values, gates = x.chunk(2, dim=-1)
        return values * F.gelu(gates)


class Hyper3EmbedLatentPooler(nn.Module):

    def __init__(self, hidden_size: int, latent_count: int, num_heads: int, head_dim: int, ffn_mult: int, output_normalize: bool) -> None:
        super().__init__()
        self.num_heads, self.head_dim, self.latent_count = num_heads, head_dim, latent_count
        self.inner_dim = num_heads * head_dim
        self.output_normalize = output_normalize
        self.latents = nn.Parameter(torch.zeros(latent_count, hidden_size))
        self.token_norm = nn.LayerNorm(hidden_size)
        self.latent_norm = nn.LayerNorm(hidden_size)
        self.to_q = nn.Linear(hidden_size, self.inner_dim, bias=False)
        self.to_kv = nn.Linear(hidden_size, self.inner_dim * 2, bias=False)
        self.to_out = nn.Linear(self.inner_dim, hidden_size, bias=False)
        self.ffn_norm = nn.LayerNorm(hidden_size)
        self.ffn = nn.Sequential(nn.Linear(hidden_size, hidden_size * ffn_mult * 2), _GEGLU(), nn.Linear(hidden_size * ffn_mult, hidden_size))

    def forward(self, hidden_states: torch.Tensor, pooling_mask: torch.Tensor) -> torch.Tensor:
        hidden_states = self.refine(hidden_states)
        mask = pooling_mask.unsqueeze(-1).to(hidden_states.dtype)
        pooled = (hidden_states * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
        return F.normalize(pooled, p=2, dim=-1) if self.output_normalize else pooled

    def refine(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = hidden_states.float()
        batch, length, _ = hidden_states.shape
        latents = self.latents.unsqueeze(0).expand(batch, -1, -1).float()
        query = self.to_q(self.token_norm(hidden_states))
        key, value = self.to_kv(self.latent_norm(latents)).chunk(2, dim=-1)
        query = query.view(batch, length, self.num_heads, self.head_dim).transpose(1, 2)
        key = key.view(batch, self.latent_count, self.num_heads, self.head_dim).transpose(1, 2)
        value = value.view(batch, self.latent_count, self.num_heads, self.head_dim).transpose(1, 2)
        attended = F.scaled_dot_product_attention(query, key, value).transpose(1, 2).reshape(batch, length, self.inner_dim)
        hidden_states = hidden_states + self.to_out(attended)
        return hidden_states + self.ffn(self.ffn_norm(hidden_states))


def named_prompts(prompt_config: dict[str, Any]) -> dict[str, str]:
    types = prompt_config["type_prompts"]
    template = prompt_config["instruction_template"]
    named = {"query": types["retrieval"]["query"], "document": types["retrieval"]["positive"]}
    named.update({family: sides["query"] for family, sides in types.items() if family != "retrieval"})
    named.update({task: template.format(instruction=instruction) for task, instruction in prompt_config["task_instructions"].items()})
    return named


def _resolve(path_or_id: str | os.PathLike, revision: str | None = None, token: bool | str | None = None,
             cache_dir: str | None = None, local_files_only: bool = False) -> Path:
    root = Path(path_or_id)
    if root.is_dir():
        return root
    from huggingface_hub import snapshot_download

    return Path(snapshot_download(str(path_or_id), revision=revision, token=token, cache_dir=cache_dir, local_files_only=local_files_only))


class Hyper3EmbedModel(PreTrainedModel):

    config_class = Hyper3EmbedConfig
    base_model_prefix = "hyper3_embed"
    chunk_mix_scores = staticmethod(chunk_mix_scores)
    maxsim_scores = staticmethod(maxsim_scores)
    best_per_document = staticmethod(best_per_document)
    fuse_scores = staticmethod(fuse_scores)

    def __init__(self, config: Hyper3EmbedConfig) -> None:
        super().__init__(config)
        self.backbone: nn.Module | None = None
        self.pooler: Hyper3EmbedLatentPooler | None = None

    @classmethod
    def from_pretrained(cls, pretrained_model_name_or_path: str | os.PathLike, *model_args: Any, config: Hyper3EmbedConfig | None = None,
                        revision: str | None = None, token: bool | str | None = None, cache_dir: str | None = None,
                        local_files_only: bool = False, dtype: torch.dtype | str | None = None, device: str | torch.device | None = None,
                        **kwargs: Any) -> Hyper3EmbedModel:
        from safetensors.torch import load_file

        unsupported = sorted(set(kwargs) & {"device_map", "quantization_config", "load_in_4bit", "load_in_8bit"})
        if unsupported:
            raise ValueError(
                "This loader does not support " + ", ".join(unsupported)
                + ". Load on one device with .to(device) or the explicit device argument."
            )
        dtype = kwargs.pop("torch_dtype", None) if dtype is None else dtype
        if isinstance(dtype, str) and dtype != "auto":
            dtype = getattr(torch, dtype)
        if dtype in (None, "auto"):
            dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
        root = _resolve(pretrained_model_name_or_path, revision, token, cache_dir, local_files_only)
        missing = [name for name in RELEASE_FILES if not (root / name).is_file()]
        if missing:
            raise FileNotFoundError(f"{root} is not a Hyper3 Embed release directory (missing {missing})")
        if config is None:
            config = Hyper3EmbedConfig.from_pretrained(root)
        if not isinstance(config.embedding_config, dict) or not config.embedding_config:
            raise ValueError("config.json must contain embedding_config")
        if not isinstance(config.prompt_config, dict) or not config.prompt_config:
            raise ValueError("config.json must contain prompt_config")
        model = cls(config)
        settings = config.embedding_config
        if settings["pooling"] != "latent_cross_attention_mean" or settings["attention_mode"] != "bidirectional":
            raise ValueError(f"Unsupported Hyper3 Embed configuration in {root}")
        if settings.get("projection_enabled", True) or settings.get("text_transform", "none") != "none":
            raise ValueError("Unsupported Hyper3 Embed configuration: projection head or text transform")

        backbone_dir = root / config.backbone_subfolder
        backbone_config = AutoConfig.from_pretrained(backbone_dir)
        model.tokenizer = AutoTokenizer.from_pretrained(root, config=backbone_config)
        if model.tokenizer.pad_token is None:
            model.tokenizer.pad_token = model.tokenizer.eos_token
        model.tokenizer.padding_side = "right"
        model.tokenizer.truncation_side = "right"
        model.append_eos = bool(settings.get("append_eos", True))

        text_config = backbone_config.get_text_config() if hasattr(backbone_config, "get_text_config") else backbone_config
        saved = json.loads((backbone_dir / "config.json").read_text(encoding="utf-8"))
        saved = saved.get("text_config", saved)
        if saved.get("use_bidirectional_attention") == "all" and isinstance(saved.get("sliding_window"), int):
            text_config.sliding_window = saved["sliding_window"]
        text_config.is_causal = False
        load_kwargs: dict[str, Any] = {"dtype": dtype}
        if (torch.device(device).type == "cuda") if device is not None else torch.cuda.is_available():
            load_kwargs["attn_implementation"] = "sdpa"
        model.backbone = AutoModel.from_pretrained(backbone_dir, config=backbone_config, **load_kwargs)
        for module in model.backbone.modules():
            if hasattr(module, "is_causal"):
                module.is_causal = False
        if hasattr(model.backbone.config, "use_cache"):
            model.backbone.config.use_cache = False

        model.pooler = Hyper3EmbedLatentPooler(
            int(settings["hidden_size"]),
            latent_count=int(settings["latent_count"]),
            num_heads=int(settings["latent_num_heads"]),
            head_dim=int(settings["latent_head_dim"]),
            ffn_mult=int(settings["latent_ffn_mult"]),
            output_normalize=bool(settings["latent_output_normalize"]),
        )
        model.pooler.load_state_dict(load_file(str(root / "pooler.safetensors")))
        model.pooler.float()
        model.multivec = None
        if int(settings.get("multivec_dim", 0)) > 0:
            model.multivec = nn.Linear(int(settings["hidden_size"]), int(settings["multivec_dim"]), bias=False)
            model.multivec.load_state_dict(load_file(str(root / "multivec_projection.safetensors")))
            model.multivec.float()
        model.eval()
        if device is not None:
            model.to(device)
        return model

    @property
    def embedding_dim(self) -> int:
        return self.pooler.to_out.out_features

    def prompts(self) -> dict[str, str]:
        return named_prompts(self.config.prompt_config)

    def tokenize(self, texts: list[str], prompt: str = "", max_length: int | None = None) -> dict[str, torch.Tensor]:
        prompt = prompt or ""
        eos = self.tokenizer.eos_token
        prepared = []
        for text in texts:
            value = prompt + text.strip()
            if self.append_eos and eos and not value.endswith(eos):
                value += eos
            prepared.append(value)
        batch = self.tokenizer(prepared, padding=True, truncation=True, max_length=max_length or self.config.max_length,
                               return_tensors="pt", return_offsets_mapping=True)
        offsets = batch.pop("offset_mapping")
        pooling_mask = batch["attention_mask"].clone()
        if prompt:
            pooling_mask[(offsets[..., 1] > offsets[..., 0]) & (offsets[..., 1] <= len(prompt))] = 0
        return {"input_ids": batch["input_ids"], "attention_mask": batch["attention_mask"], "pooling_mask": pooling_mask}

    def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, pooling_mask: torch.Tensor | None = None, **kwargs: Any) -> torch.Tensor:
        hidden = self.backbone(input_ids=input_ids, attention_mask=attention_mask, return_dict=True).last_hidden_state
        pooled = self.pooler(hidden, attention_mask if pooling_mask is None else pooling_mask)
        return F.normalize(pooled.float(), p=2, dim=-1)

    @torch.no_grad()
    def encode(self, texts: str | list[str], prompt: str | None = None, prompt_name: str | None = None,
               batch_size: int = 8, max_length: int | None = None) -> torch.Tensor:
        if prompt is not None and prompt_name is not None:
            raise ValueError("Pass prompt or prompt_name, not both")
        if prompt_name is not None:
            prompt = self.prompts()[prompt_name]
        texts = [texts] if isinstance(texts, str) else list(texts)
        device = next(self.backbone.parameters()).device
        order = sorted(range(len(texts)), key=lambda index: len(texts[index]), reverse=True)
        out = torch.empty((len(texts), self.embedding_dim), dtype=torch.float32)
        for start in range(0, len(order), batch_size):
            chunk = order[start : start + batch_size]
            batch = {key: value.to(device) for key, value in self.tokenize([texts[index] for index in chunk], prompt or "", max_length).items()}
            out[chunk] = self(**batch).cpu()
        return out

    def document_windows(self, texts: list[str], window: int = CHUNK_WINDOW, stride: int = CHUNK_STRIDE) -> tuple[list[str], list[int]]:
        windows, owner, _ = self._windows(texts, window, stride)
        return windows, owner

    def _windows(self, texts: list[str], window: int, stride: int) -> tuple[list[str], list[int], list[int]]:
        windows, owner, lengths = [], [], []
        for index, text in enumerate(texts):
            ids = self.tokenizer(text, add_special_tokens=False)["input_ids"]
            starts = range(0, max(1, len(ids) - stride), stride)
            windows += [self.tokenizer.decode(ids[start : start + window]) for start in starts]
            owner += [index] * len(starts)
            lengths.append(len(ids))
        return windows, owner, lengths

    def encode_windows(self, texts: str | list[str], prompt: str = "", batch_size: int = 8, window: int = CHUNK_WINDOW,
                       stride: int = CHUNK_STRIDE) -> tuple[torch.Tensor, torch.Tensor]:
        texts = [texts] if isinstance(texts, str) else list(texts)
        windows, owner = self.document_windows(texts, window, stride)
        embeddings = self.encode(windows, prompt=prompt, batch_size=batch_size, max_length=window + 64)
        return embeddings, torch.tensor(owner, dtype=torch.long)

    @torch.no_grad()
    def encode_with_tokens(self, texts: str | list[str], prompt: str | None = None, prompt_name: str | None = None,
                           batch_size: int = 8, max_length: int | None = None) -> tuple[torch.Tensor, list[torch.Tensor]]:
        if self.multivec is None:
            raise ValueError("this checkpoint has no MaxSim head")
        if prompt is not None and prompt_name is not None:
            raise ValueError("Pass prompt or prompt_name, not both")
        if prompt_name is not None:
            prompt = self.prompts()[prompt_name]
        texts = [texts] if isinstance(texts, str) else list(texts)
        device = next(self.backbone.parameters()).device
        order = sorted(range(len(texts)), key=lambda index: len(texts[index]), reverse=True)
        dense = torch.empty((len(texts), self.embedding_dim), dtype=torch.float32)
        tokens: list[torch.Tensor] = [None] * len(texts)
        for start in range(0, len(order), batch_size):
            chunk = order[start : start + batch_size]
            batch = {key: value.to(device) for key, value in self.tokenize([texts[index] for index in chunk], prompt or "", max_length).items()}
            hidden = self.backbone(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], return_dict=True).last_hidden_state
            refined = self.pooler.refine(hidden)
            mask = batch["pooling_mask"].unsqueeze(-1).to(refined.dtype)
            pooled = (refined * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0)
            if self.pooler.output_normalize:
                pooled = F.normalize(pooled, p=2, dim=-1)
            dense[chunk] = F.normalize(pooled.float(), p=2, dim=-1).cpu()
            vectors = F.normalize(self.multivec(refined.float()), p=2, dim=-1)
            for row, index in enumerate(chunk):
                tokens[index] = vectors[row][batch["pooling_mask"][row].bool()].half().cpu()
        return dense, tokens

    @torch.no_grad()
    def multivector_parts(self, queries: list[str], documents: list[str], query_prompt: str | None = None,
                          document_prompt: str = "", batch_size: int = 8, window_block: int = 4096,
                          full_maxsim: bool | None = None) -> dict[str, torch.Tensor]:
        query_prompt = self.prompts()["query"] if query_prompt is None else query_prompt
        qd, qt = self.encode_with_tokens(queries, prompt=query_prompt, batch_size=batch_size, max_length=FUSE_QUERY_MAX_LENGTH)
        return self.document_parts(qd, qt, documents, document_prompt=document_prompt, batch_size=batch_size,
                                   window_block=window_block, full_maxsim=full_maxsim)

    @torch.no_grad()
    def document_parts(self, query_dense: torch.Tensor, query_tokens: list[torch.Tensor], documents: list[str],
                       document_prompt: str = "", batch_size: int = 8, window_block: int = 4096,
                       full_maxsim: bool | None = None) -> dict[str, torch.Tensor]:
        device = next(self.backbone.parameters()).device
        full_maxsim = FUSE_MAXSIM_WINDOW_WEIGHT != 1 if full_maxsim is None else full_maxsim
        qd, qt = query_dense.to(device), [t.to(device) for t in query_tokens]
        parts = {"dense_full": torch.empty(len(qt), len(documents), device=device),
                 "maxsim_full": torch.empty(len(qt), len(documents), device=device) if full_maxsim else None}
        for start in range(0, len(documents), window_block // 8):
            block = documents[start : start + window_block // 8]
            dd, dt = (self.encode_with_tokens(block, prompt=document_prompt, batch_size=batch_size) if full_maxsim
                      else (self.encode(block, prompt=document_prompt, batch_size=batch_size), None))
            parts["dense_full"][:, start : start + len(block)] = qd @ dd.to(device).T
            if full_maxsim:
                parts["maxsim_full"][:, start : start + len(block)] = maxsim_scores(qt, dt)
        windows, owner, lengths = self._windows(documents, CHUNK_WINDOW, CHUNK_STRIDE)
        parts["document_tokens"] = torch.tensor(lengths, dtype=torch.long, device=device)
        owner = torch.tensor(owner, dtype=torch.long, device=device)
        dense_best = torch.full((len(qt), len(documents)), -torch.inf, device=device)
        maxsim_best = torch.full((len(qt), len(documents)), -torch.inf, device=device)
        for start in range(0, len(windows), window_block):
            wd, wt = self.encode_with_tokens(windows[start : start + window_block], prompt=document_prompt,
                                             batch_size=batch_size, max_length=CHUNK_WINDOW + 64)
            own = owner[start : start + window_block].expand(len(qt), -1)
            dense_best = dense_best.scatter_reduce(1, own, qd @ wd.to(device).T, "amax")
            maxsim_best = maxsim_best.scatter_reduce(1, own, maxsim_scores(qt, wt), "amax")
        parts["dense_window"], parts["maxsim_window"] = dense_best, maxsim_best
        return parts

    def score_multivector(self, queries: list[str], documents: list[str], rerank_top_k: int | None = None,
                          fusion: dict[str, Any] | None = None, **kwargs: Any) -> torch.Tensor:
        fusion = fusion or {}
        if rerank_top_k is None:
            return fuse_scores(**self.multivector_parts(queries, documents, **kwargs), **fusion)
        kwargs = dict(kwargs)
        query_prompt = kwargs.pop("query_prompt", None)
        document_prompt, batch_size = kwargs.get("document_prompt", ""), kwargs.get("batch_size", 8)
        q = self.encode(queries, prompt=self.prompts()["query"] if query_prompt is None else query_prompt, batch_size=batch_size,
                        max_length=FUSE_QUERY_MAX_LENGTH)
        d = self.encode(documents, prompt=document_prompt, batch_size=batch_size)
        w, owner = self.encode_windows(documents, prompt=document_prompt, batch_size=batch_size)
        first = chunk_mix_scores(q, d, w, owner, weight=fusion.get("dense_window_weight", FUSE_DENSE_WINDOW_WEIGHT))
        top = first.topk(min(rerank_top_k, len(documents)), dim=1).indices
        candidates = sorted(set(top.flatten().tolist()))
        sub = fuse_scores(**self.multivector_parts(queries, [documents[i] for i in candidates], query_prompt=query_prompt, **kwargs),
                          **fusion)
        scores = torch.full_like(first, -torch.inf)
        column = {doc: j for j, doc in enumerate(candidates)}
        for row in range(len(queries)):
            keep = top[row].tolist()
            scores[row, keep] = sub[row, [column[i] for i in keep]].to(scores.device)
        return scores