Feature Extraction
Transformers
Safetensors
multilingual
pplx_contextual_qwen3_5
sentence-similarity
contextual-embeddings
custom_code
Instructions to use perplexity-ai/pplx-embed-v2-context-0.6b with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use perplexity-ai/pplx-embed-v2-context-0.6b with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("feature-extraction", model="perplexity-ai/pplx-embed-v2-context-0.6b", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("perplexity-ai/pplx-embed-v2-context-0.6b", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download modeling_pplx_contextual.py from perplexity-ai/pplx-embed-v2-context-0.6b: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/perplexity-ai/pplx-embed-v2-context-0.6b/resolve/main/modeling_pplx_contextual.py
- Command line
-
hf download hf://perplexity-ai/pplx-embed-v2-context-0.6b/modeling_pplx_contextual.py
-
curl -L -o modeling_pplx_contextual.py https://huggingface.co/perplexity-ai/pplx-embed-v2-context-0.6b/resolve/main/modeling_pplx_contextual.py
12.7 kB
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import Any, Literal | |
| import numpy as np | |
| import torch | |
| import torch.nn.functional as F | |
| from torch import nn | |
| from tqdm.auto import tqdm | |
| from PIL import Image | |
| from transformers import AutoTokenizer, PreTrainedTokenizerBase, Qwen3_5Model, Qwen3VLProcessor | |
| from .configuration_pplx_contextual import PplxContextualConfig | |
| from .image_processing import ImageEncodingConfig, ImageInputMapper | |
| class PplxContextualModel(Qwen3_5Model): | |
| """Encode a document's supplied chunks together, then pool each chunk.""" | |
| config_class = PplxContextualConfig | |
| config: PplxContextualConfig | |
| _keep_in_fp32_modules = ["contextual_projection"] | |
| def __init__(self, config: PplxContextualConfig) -> None: | |
| super().__init__(config) | |
| self.contextual_projection = nn.Linear( | |
| config.text_config.hidden_size, config.embedding_dim, bias=False | |
| ) | |
| self._tokenizer: PreTrainedTokenizerBase | None = None | |
| self._image_processor: Qwen3VLProcessor | None = None | |
| self.post_init() | |
| def tokenizer(self) -> PreTrainedTokenizerBase: | |
| if self._tokenizer is None: | |
| self._tokenizer = AutoTokenizer.from_pretrained( | |
| self.config._name_or_path, | |
| config=self.config, | |
| revision=self.config._commit_hash, | |
| padding_side="right", | |
| ) | |
| return self._tokenizer | |
| def tokenizer(self, value: PreTrainedTokenizerBase) -> None: | |
| self._tokenizer = value | |
| def prepare_inputs( | |
| self, documents: list[list[str]], task: str = "document" | |
| ) -> dict[str, torch.Tensor]: | |
| tokenizer = self.tokenizer | |
| if task == "query": | |
| if any(len(row) != 1 for row in documents): | |
| raise ValueError("Each query must contain exactly one string") | |
| batch = tokenizer( | |
| [row[0] for row in documents], | |
| padding=True, | |
| truncation=False, | |
| split_special_tokens=True, | |
| return_tensors="pt", | |
| return_token_type_ids=False, | |
| ) | |
| prefix_id = tokenizer.convert_tokens_to_ids( | |
| self.config.query_prefix | |
| ) | |
| prefix = torch.full( | |
| (len(documents), 1), prefix_id, dtype=torch.long | |
| ) | |
| batch["input_ids"] = torch.cat((prefix, batch["input_ids"]), dim=1) | |
| batch["attention_mask"] = torch.cat( | |
| (torch.ones_like(prefix), batch["attention_mask"]), dim=1 | |
| ) | |
| batch["chunk_mask"] = torch.ones( | |
| (len(documents), 1), dtype=torch.bool | |
| ) | |
| elif task == "document": | |
| texts, char_spans = [], [] | |
| for chunks in documents: | |
| parts = [self.config.document_prefix] | |
| cursor = len(self.config.document_prefix) | |
| spans = [] | |
| for index, chunk in enumerate(chunks): | |
| if index: | |
| parts.append(self.config.boundary_marker) | |
| cursor += len(self.config.boundary_marker) | |
| spans.append((cursor, cursor + len(chunk))) | |
| parts.append(chunk) | |
| cursor += len(chunk) | |
| texts.append("".join(parts)) | |
| char_spans.append(spans) | |
| batch = tokenizer( | |
| texts, | |
| padding=True, | |
| truncation=False, | |
| split_special_tokens=True, | |
| return_tensors="pt", | |
| return_token_type_ids=False, | |
| return_offsets_mapping=True, | |
| ) | |
| offsets = batch.pop("offset_mapping") | |
| count = max(1, *map(len, documents)) | |
| token_spans = torch.zeros( | |
| (len(documents), count, 2), dtype=torch.long | |
| ) | |
| chunk_mask = torch.zeros((len(documents), count), dtype=torch.bool) | |
| for row, spans in enumerate(char_spans): | |
| starts, ends = offsets[row].unbind(dim=-1) | |
| valid = batch["attention_mask"][row].bool() & (ends > starts) | |
| for column, (start, end) in enumerate(spans): | |
| indices = ( | |
| (valid & (starts < end) & (ends > start)) | |
| .nonzero() | |
| .flatten() | |
| ) | |
| if indices.numel(): | |
| token_spans[row, column, 0] = indices[0] | |
| token_spans[row, column, 1] = indices[-1] + 1 | |
| elif documents[row][column]: | |
| raise ValueError( | |
| f"Chunk {column} in document {row} produced no tokens" | |
| ) | |
| chunk_mask[row, column] = True | |
| batch["chunk_token_spans"] = token_spans | |
| batch["chunk_mask"] = chunk_mask | |
| else: | |
| raise ValueError(f"Unsupported task: {task}") | |
| limit = ( | |
| self.config.query_length | |
| if task == "query" | |
| else self.config.document_length | |
| ) | |
| if batch["input_ids"].shape[1] > limit: | |
| raise ValueError( | |
| f"Input exceeds the {limit}-token limit; split the document into context windows" | |
| ) | |
| return dict(batch) | |
| def _pool( | |
| self, features: dict[str, torch.Tensor], task: str | |
| ) -> torch.Tensor: | |
| visual = {key: features[key] for key in ( | |
| "pixel_values", "image_grid_thw", "mm_token_type_ids", "position_ids" | |
| ) if key in features} | |
| hidden = self( | |
| input_ids=features["input_ids"], | |
| attention_mask=features["attention_mask"], | |
| use_cache=False, | |
| return_dict=True, | |
| **visual, | |
| ).last_hidden_state | |
| with torch.autocast(device_type=hidden.device.type, enabled=False): | |
| hidden = hidden.float() | |
| if "pixel_values" in features: | |
| hidden = F.linear(hidden, self.contextual_projection.weight.float()) | |
| if task == "query": | |
| mask = features["attention_mask"].unsqueeze(-1).float() | |
| pooled = ( | |
| (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp_min(1.0) | |
| ).unsqueeze(1) | |
| else: | |
| prefix = torch.cat( | |
| ( | |
| hidden.new_zeros(hidden.shape[0], 1, hidden.shape[-1]), | |
| hidden.cumsum(dim=1), | |
| ), | |
| dim=1, | |
| ) | |
| starts, ends = features["chunk_token_spans"].unbind(dim=-1) | |
| rows = torch.arange( | |
| hidden.shape[0], device=hidden.device | |
| ).unsqueeze(1) | |
| pooled = (prefix[rows, ends] - prefix[rows, starts]) / ( | |
| ends - starts | |
| ).clamp_min(1).unsqueeze(-1) | |
| if "pixel_values" in features: | |
| return pooled | |
| return F.linear(pooled, self.contextual_projection.weight.float()) | |
| def prepare_images( | |
| self, | |
| images: list[Image.Image], | |
| *, | |
| chunks: int = 8, | |
| min_pixels: int = 16384, | |
| max_pixels: int = 1800000, | |
| ) -> dict[str, torch.Tensor]: | |
| """Wrap whole pages and split their visual tokens into native-MRoPE row bands.""" | |
| if not images or any(not isinstance(image, Image.Image) for image in images): | |
| raise ValueError("Expected a nonempty list of PIL images") | |
| if self._image_processor is None: | |
| self._image_processor = Qwen3VLProcessor.from_pretrained( | |
| self.config._name_or_path, revision=self.config._commit_hash, trust_remote_code=True, | |
| ) | |
| self._image_processor.tokenizer = self.tokenizer | |
| mapper = ImageInputMapper( | |
| self._image_processor, self.tokenizer, | |
| self.config.document_prefix, self.config.boundary_marker, | |
| ) | |
| features = ImageEncodingConfig(chunks, min_pixels, max_pixels).prepare(mapper, images) | |
| if features["input_ids"].shape[1] > self.config.document_length: | |
| raise ValueError("Image input exceeds document_length; reduce max_pixels") | |
| return dict(features) | |
| def encode_images( | |
| self, | |
| images: list[Image.Image], | |
| batch_size: int = 1, | |
| show_progress_bar: bool = False, | |
| device: str | torch.device | None = None, | |
| normalize_embeddings: bool = False, | |
| convert_to_numpy: bool = True, | |
| quantization: Literal["int8"] = "int8", | |
| *, | |
| chunks: int = 8, | |
| min_pixels: int = 16384, | |
| max_pixels: int = 1800000, | |
| ) -> list[np.ndarray] | list[torch.Tensor]: | |
| """Return one quantized vector per nonempty row band of each page.""" | |
| if batch_size < 1 or quantization != "int8": | |
| raise ValueError("Expected positive batch_size and int8 quantization") | |
| self.eval() | |
| if device is not None: | |
| self.to(device) | |
| rows = [] | |
| for start in tqdm(range(0, len(images), batch_size), disable=not show_progress_bar): | |
| features = { | |
| key: value.to(self.device) | |
| for key, value in self.prepare_images( | |
| images[start:start + batch_size], chunks=chunks, | |
| min_pixels=min_pixels, max_pixels=max_pixels, | |
| ).items() | |
| } | |
| projected = self._pool(features, "document") | |
| vectors = torch.round(torch.tanh(projected) * 127).clamp(-128, 127) | |
| if normalize_embeddings: | |
| vectors = F.normalize(vectors, p=2, dim=-1) | |
| rows.extend(vector[mask].cpu() for vector, mask in zip(vectors, features["chunk_mask"], strict=True)) | |
| return [row.numpy() for row in rows] if convert_to_numpy else rows | |
| def encode( | |
| self, | |
| documents: list[list[str]], | |
| batch_size: int = 32, | |
| show_progress_bar: bool = False, | |
| device: str | torch.device | None = None, | |
| normalize_embeddings: bool = False, | |
| convert_to_numpy: bool = True, | |
| quantization: Literal["int8"] = "int8", | |
| *, | |
| task: Literal["query", "document"] = "document", | |
| ) -> list[np.ndarray] | list[torch.Tensor]: | |
| """Return one (chunk_count, embedding_dim) array per document. | |
| Int8 quantization returns float32 integer values, matching the V1 API. | |
| No automatic chunk splitting or input truncation is performed. | |
| """ | |
| if not isinstance(documents, list) or any( | |
| not isinstance(row, list) | |
| or any(not isinstance(text, str) for text in row) | |
| for row in documents | |
| ): | |
| raise TypeError( | |
| "Expected a list of documents, each a list of text chunks" | |
| ) | |
| if batch_size < 1: | |
| raise ValueError("batch_size must be positive") | |
| if task not in ("query", "document"): | |
| raise ValueError(f"Unsupported task: {task}") | |
| if quantization != "int8": | |
| raise ValueError(f"Unsupported quantization: {quantization}") | |
| self.eval() | |
| if device is not None: | |
| self.to(device) | |
| rows = [] | |
| for start in tqdm( | |
| range(0, len(documents), batch_size), disable=not show_progress_bar | |
| ): | |
| batch = documents[start : start + batch_size] | |
| features = { | |
| key: value.to(self.device) | |
| for key, value in self.prepare_inputs(batch, task).items() | |
| } | |
| projected = self._pool(features, task) | |
| vectors = torch.round(torch.tanh(projected) * 127).clamp(-128, 127) | |
| if normalize_embeddings: | |
| vectors = F.normalize(vectors, p=2, dim=-1) | |
| rows.extend( | |
| vectors[index, : len(chunks)].cpu() | |
| for index, chunks in enumerate(batch) | |
| ) | |
| return [row.numpy() for row in rows] if convert_to_numpy else rows | |
| def encode_queries( | |
| self, queries: list[list[str]], **kwargs: Any | |
| ) -> list[np.ndarray] | list[torch.Tensor]: | |
| """Encode singleton query rows with the checkpoint's query prefix.""" | |
| return self.encode(queries, task="query", **kwargs) | |
| def save_pretrained( | |
| self, save_directory: str | Path, **kwargs: Any | |
| ) -> None: | |
| tokenizer = self.tokenizer | |
| super().save_pretrained(save_directory, **kwargs) | |
| tokenizer.save_pretrained(save_directory) | |