Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / engram / ngram_hash_mapping.py: 92%
74 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Deterministic n-gram hash assets and rebuildable metadata."""
16from __future__ import annotations
17from collections.abc import Mapping
18from typing import Any
19import torch
20from torch import nn
21from hyper_parallel.models.materialization import register_rebuildable_buffer
24class NgramHashMapping(nn.Module):
25 """Map token IDs to one Engram layer's disjoint n-gram hash rows."""
27 DEAD_TOKEN = -1
29 def __init__(self, assets: Mapping[str, Any], layer_id: int) -> None:
30 """Create deterministic, non-persistent hash metadata.
32 Args:
33 assets: Prepared tokenizer map and per-layer hash layout.
34 layer_id: Decoder layer owning this Engram table.
35 """
36 super().__init__()
37 target_device = torch.empty(0).device
38 layer_ids = tuple(int(value) for value in assets["layer_ids"])
39 if layer_id not in layer_ids:
40 raise ValueError(f"Engram layer {layer_id} is absent from assets layer_ids={layer_ids}")
41 layer_index = layer_ids.index(layer_id)
42 self.layer_id = layer_id
43 self.max_ngram_size = int(assets["max_ngram_size"])
44 self.num_heads = int(assets["num_heads"])
45 token_map = torch.tensor(assets["token_map"], dtype=torch.long, device="cpu")
46 self.pad_id = int(token_map[int(assets["pad_token_id"])])
47 primes = torch.tensor(assets["primes"][layer_index], dtype=torch.long, device="cpu")
48 if tuple(primes.shape) != (self.max_ngram_size - 1, self.num_heads):
49 raise ValueError(
50 "Engram prime layout must be [max_ngram_size - 1, num_heads], "
51 f"got {tuple(primes.shape)}"
52 )
53 flattened_primes = primes.flatten()
54 if self.max_ngram_size < 2 or self.num_heads <= 0 or bool((primes <= 0).any()):
55 raise ValueError("Engram requires ngram size >=2, positive heads and positive hash moduli")
56 offsets = torch.cat(
57 [torch.zeros(1, dtype=torch.long, device="cpu"), flattened_primes.cumsum(0)[:-1]]
58 ).view_as(primes)
59 multipliers = torch.tensor(assets["multipliers"][layer_index], dtype=torch.long, device="cpu")
60 if multipliers.numel() != self.max_ngram_size:
61 raise ValueError("Engram multiplier count must equal max_ngram_size")
62 self.logical_num_embeddings = int(flattened_primes.sum().item())
63 initial_buffers = {
64 "token_map": token_map,
65 "primes": primes,
66 "offsets": offsets,
67 "multipliers": multipliers,
68 }
69 for name, value in initial_buffers.items():
70 register_rebuildable_buffer(self, name, value=value, persistent=False)
71 if target_device.type != "cpu":
72 self.register_buffer(name, getattr(self, name).to(target_device), persistent=False)
74 def forward(
75 self,
76 input_ids: torch.Tensor,
77 segment_starts: torch.Tensor | None = None,
78 token_mask: torch.Tensor | None = None,
79 ) -> torch.Tensor:
80 """Return global flat-table rows shaped ``[batch, seq, hash_columns]``.
82 Args:
83 input_ids: Token IDs for hash lookup.
84 segment_starts: Optional packed sequence boundaries.
85 token_mask: Optional mask excluding image tokens.
86 """
87 if input_ids.ndim != 2:
88 raise ValueError(f"Engram expects input_ids [B,S], got {tuple(input_ids.shape)}")
89 if input_ids.shape[1] == 0:
90 return input_ids.new_empty((input_ids.shape[0], 0, (self.max_ngram_size - 1) * self.num_heads),
91 dtype=torch.long)
92 compressed = self.token_map[input_ids]
93 if token_mask is not None:
94 if token_mask.shape != input_ids.shape:
95 raise ValueError("Engram token_mask must have the same shape as input_ids")
96 compressed = torch.where(
97 token_mask.to(torch.bool),
98 compressed,
99 compressed.new_full((), self.DEAD_TOKEN),
100 )
101 batch_size, sequence_length = compressed.shape
102 positions = torch.arange(sequence_length, device=input_ids.device).expand(batch_size, -1)
103 segment_ids = None
104 if segment_starts is not None:
105 if segment_starts.shape != input_ids.shape:
106 raise ValueError("Engram segment_starts must have the same shape as input_ids")
107 starts = segment_starts.to(torch.bool).clone()
108 starts[:, 0] = True
109 segment_ids = starts.to(torch.long).cumsum(dim=1)
111 tokens = []
112 blocked = torch.zeros_like(positions, dtype=torch.bool)
113 for shift in range(self.max_ngram_size):
114 source_positions = (positions - shift).clamp_min(0)
115 source = compressed.gather(1, source_positions)
116 blocked = blocked | (positions < shift)
117 if segment_ids is not None:
118 source_segments = segment_ids.gather(1, source_positions)
119 blocked = blocked | (source_segments != segment_ids)
120 blocked = blocked | (source == self.DEAD_TOKEN)
121 tokens.append(torch.where(blocked, self.pad_id, source))
123 products = torch.stack(tokens, dim=-1) * self.multipliers
124 rolling = products[..., 0]
125 hashes = []
126 for ngram_index in range(self.max_ngram_size - 1):
127 rolling = torch.bitwise_xor(rolling, products[..., ngram_index + 1])
128 row = rolling.unsqueeze(-1) % self.primes[ngram_index]
129 hashes.append(row + self.offsets[ngram_index])
130 return torch.cat(hashes, dim=-1)