|
| 1 | +from typing import Any, Dict |
| 2 | + |
| 3 | +import mlx.core as mx |
| 4 | + |
| 5 | + |
| 6 | +def mean_pooling(token_embeddings: mx.array, attention_mask: mx.array): |
| 7 | + input_mask_expanded = mx.expand_dims(attention_mask, -1) |
| 8 | + input_mask_expanded = mx.broadcast_to( |
| 9 | + input_mask_expanded, token_embeddings.shape |
| 10 | + ).astype(mx.float32) |
| 11 | + sum_embeddings = mx.sum(token_embeddings * input_mask_expanded, axis=1) |
| 12 | + sum_mask = mx.maximum(mx.sum(input_mask_expanded, axis=1), 1e-9) |
| 13 | + return sum_embeddings / sum_mask |
| 14 | + |
| 15 | + |
| 16 | +def cls_pooling(token_embeddings: mx.array, attention_mask: mx.array) -> mx.array: |
| 17 | + first_indices = mx.argmax(attention_mask, axis=1) |
| 18 | + batch_size = token_embeddings.shape[0] |
| 19 | + hidden_dim = token_embeddings.shape[-1] |
| 20 | + gather_idx = mx.broadcast_to( |
| 21 | + first_indices[:, None, None], (batch_size, 1, hidden_dim) |
| 22 | + ) |
| 23 | + return mx.squeeze(mx.take_along_axis(token_embeddings, gather_idx, axis=1), axis=1) |
| 24 | + |
| 25 | + |
| 26 | +def max_pooling(token_embeddings: mx.array, attention_mask: mx.array) -> mx.array: |
| 27 | + mask = mx.expand_dims(attention_mask, -1) |
| 28 | + mask = mx.broadcast_to(mask, token_embeddings.shape).astype(token_embeddings.dtype) |
| 29 | + masked = mx.where(mask == 0, -float("inf"), token_embeddings) |
| 30 | + return mx.max(masked, axis=1) |
| 31 | + |
| 32 | + |
| 33 | +def lasttoken_pooling(token_embeddings: mx.array, attention_mask: mx.array) -> mx.array: |
| 34 | + batch_size, seq_len, hidden_dim = token_embeddings.shape |
| 35 | + flipped = attention_mask[:, ::-1] |
| 36 | + flip_indices = mx.argmax(flipped, axis=1) |
| 37 | + has_any_real = mx.max(flipped, axis=1) |
| 38 | + flip_indices = mx.where(has_any_real == 0, seq_len - 1, flip_indices) |
| 39 | + last_indices = seq_len - flip_indices - 1 |
| 40 | + gather_idx = mx.broadcast_to( |
| 41 | + last_indices[:, None, None], (batch_size, 1, hidden_dim) |
| 42 | + ) |
| 43 | + mask = mx.broadcast_to(attention_mask[:, :, None], token_embeddings.shape).astype( |
| 44 | + token_embeddings.dtype |
| 45 | + ) |
| 46 | + return mx.squeeze( |
| 47 | + mx.take_along_axis(token_embeddings * mask, gather_idx, axis=1), axis=1 |
| 48 | + ) |
| 49 | + |
| 50 | + |
| 51 | +_LEGACY_POOLING_MODE_KWARGS = { |
| 52 | + "pooling_mode_cls_token": "cls", |
| 53 | + "pooling_mode_max_tokens": "max", |
| 54 | + "pooling_mode_mean_tokens": "mean", |
| 55 | + "pooling_mode_mean_sqrt_len_tokens": "mean_sqrt_len_tokens", |
| 56 | + "pooling_mode_weightedmean_tokens": "weightedmean", |
| 57 | + "pooling_mode_lasttoken": "lasttoken", |
| 58 | +} |
| 59 | + |
| 60 | +_SUPPORTED_POOL_MODES = {"cls", "mean", "max", "lasttoken"} |
| 61 | +_KNOWN_UNSUPPORTED_POOL_MODES = {"weightedmean", "mean_sqrt_len_tokens"} |
| 62 | + |
| 63 | + |
| 64 | +def _normalize_pooling_config( |
| 65 | + pooling_config: Dict[str, Any], |
| 66 | +) -> Dict[str, Any]: |
| 67 | + cfg = dict(pooling_config) |
| 68 | + found = [k for k in _LEGACY_POOLING_MODE_KWARGS if k in cfg] |
| 69 | + if not found: |
| 70 | + return cfg |
| 71 | + if "pooling_mode" not in cfg: |
| 72 | + active = tuple( |
| 73 | + name |
| 74 | + for key, name in _LEGACY_POOLING_MODE_KWARGS.items() |
| 75 | + if cfg.get(key, False) |
| 76 | + ) |
| 77 | + if not active: |
| 78 | + active = ("mean",) |
| 79 | + cfg["pooling_mode"] = active[0] if len(active) == 1 else active |
| 80 | + for k in found: |
| 81 | + del cfg[k] |
| 82 | + return cfg |
| 83 | + |
| 84 | + |
| 85 | +def pool_by_config( |
| 86 | + token_embeddings: mx.array, |
| 87 | + attention_mask: mx.array, |
| 88 | + pooling_config: Dict[str, Any], |
| 89 | +) -> mx.array: |
| 90 | + cfg = _normalize_pooling_config(pooling_config) |
| 91 | + mode = cfg["pooling_mode"] |
| 92 | + if not cfg.get("include_prompt", True): |
| 93 | + raise NotImplementedError( |
| 94 | + "Prompt-aware pooling (include_prompt=False) is not supported. " |
| 95 | + "This affects INSTRUCTOR-style models." |
| 96 | + ) |
| 97 | + if isinstance(mode, (tuple, list)): |
| 98 | + raise NotImplementedError( |
| 99 | + f"Concatenated pooling mode {mode!r} is not supported; " |
| 100 | + "only a single pooling mode is allowed." |
| 101 | + ) |
| 102 | + if mode in _KNOWN_UNSUPPORTED_POOL_MODES: |
| 103 | + raise NotImplementedError( |
| 104 | + f"Pooling mode {mode!r} is not supported. " |
| 105 | + f"Supported modes: {sorted(_SUPPORTED_POOL_MODES)}." |
| 106 | + ) |
| 107 | + |
| 108 | + if mode == "cls": |
| 109 | + return cls_pooling(token_embeddings, attention_mask) |
| 110 | + if mode == "max": |
| 111 | + return max_pooling(token_embeddings, attention_mask) |
| 112 | + if mode == "lasttoken": |
| 113 | + return lasttoken_pooling(token_embeddings, attention_mask) |
| 114 | + if mode == "mean": |
| 115 | + return mean_pooling(token_embeddings, attention_mask) |
| 116 | + raise ValueError( |
| 117 | + f"Unknown pooling mode {mode!r}. " |
| 118 | + f"Supported modes: {sorted(_SUPPORTED_POOL_MODES)}." |
| 119 | + ) |
0 commit comments