com.microsoft.NGramHashMapping

com.microsoft · ONNX Runtime contrib operator · contrib since_version 1

Description

Engram n-gram hash IDs from int32 tokenizer IDs. Orders 2..max_ngram_size XOR causal ID/multiplier products with int32 wrapping, then reduce modulo each head vocabulary. past_ids/present_ids carry raw trailing history for chunked execution; keep their buffers distinct for rollback. Optional head_offsets add after modulo. EOS fills unavailable history; reset_on_eos also resets preceding shifts. segment_ids reset at adjacent changes in the current chunk. Int64 products have different wrap semantics and are unsupported.

See the ONNX Runtime NGramHashMapping contrib-operator spec for the reference semantics.

Differences from the ONNX Runtime spec

  • Output presentIdsT (ONNX present_ids): The package always produces the raw carry state.

Inputs

Name Upstream name Logical dtype Rank Shape Description Presence
inputIdsT input_ids M 2 — Compressed tokenizer ids with shape (batch_size, sequence_length). A zero-length sequence is accepted: it emits no hash ids and passes the carry state through unchanged. required
multipliersT multipliers M 1 — Per-shift hash multipliers with a rank-1 length at least max_ngram_size. Only the leading max_ngram_size values are consumed. Any value is accepted; products wrap in two's complement rather than saturating. required
vocabSizesT vocab_sizes M 1 — Per-output-head vocabulary sizes with shape ((max_ngram_size - 1) * n_head_per_ngram), conventionally prime and strictly positive. A non-positive entry has no meaningful modulo; this kernel emits a hash id of 0 for that head, which is what every GPU implementation of the operator does, while the reference CPU implementation rejects it instead. required
pastIdsT past_ids M 2 — Optional raw IDs for the max_ngram_size - 1 positions preceding this call, with exact shape (batch_size, max_ngram_size - 1), right-aligned. Short available history must use padded contents in this full-sized tensor. When absent, missing history is eos_token_id if supplied, otherwise pad_id. Segment boundaries are not inferred from past_ids. Keep the buffer distinct from present_ids, including during speculative calls or prefix rollback. optional
headOffsetsT head_offsets M 1 — Optional per-head offsets with exact shape ((max_ngram_size - 1) * n_head_per_ngram). Added after positive modulo with int32 wrapping. A non-positive vocabulary entry still emits zero, ignoring its offset. For portability with ONNX Runtime's CPU provider, offsets must be non-negative and offset plus vocabulary size must fit int32; the GPU path uses wrapping int32 addition, as ONNX Runtime's CUDA provider does, and reads no tensor values on the host. optional
eosTokenIdT eos_token_id M 0 — Optional rank-0 device tensor holding the EOS ID. Replaces unavailable history even when reset_on_eos is zero; with reset enabled, shifted IDs at or before the nearest EOS strictly before the current token are replaced with this value. The current token always participates unchanged. optional
segmentIdsT segment_ids int32 2 — Optional int32 per-token segment IDs with exactly input_ids shape. Adjacent changes within the current chunk reset preceding shifts to eos_token_id if supplied, otherwise pad_id. No segment comparison is inferred across past_ids. optional

Outputs

Name Upstream name Logical dtype Rank Shape Description Presence
hashIdsT hash_ids M 3 derived Hash ids with shape (batch_size, sequence_length, (max_ngram_size - 1) * n_head_per_ngram). The heads of order n = 2 come first, then n = 3, and so on. required
presentIdsT present_ids M 2 derived Raw trailing max_ngram_size - 1 IDs of past_ids followed by input_ids, with exact shape (batch_size, max_ngram_size - 1). Boundary substitutions affect only hashes. Missing history uses eos_token_id if supplied, otherwise pad_id. Always written to a buffer distinct from past_ids; retain original history for speculative calls or prefix rollback. required

Attributes

Attributes and default values (overridable per request):

Attribute Default Description
max_ngram_size — Highest n-gram order, at least 2. It is compiled into the shader as a constant, so the shift walk and the head arithmetic are resolved at compile time; this package renders orders up to 16.
n_head_per_ngram — Number of hash heads emitted for each n-gram order, at least 1. Like max_ngram_size, it is compiled into the shader as a constant, and their product with max_ngram_size - 1 is capped at 64 heads.
pad_id — Compressed tokenizer id used for causal-shift positions before the beginning of the whole sequence. It must be representable as int32.
reset_on_eos 0 When nonzero and eos_token_id is supplied, reset causal shifts at or before the nearest EOS strictly preceding the current token, including EOS in past_ids. The current EOS token does not reset its own history. Without eos_token_id this attribute has no effect.

Type constraints

Variable Allowed dtypes
M int32

Implementation variants

One implementation is selected per call from the device capabilities, the request shapes and the dtypes; these notes say what each one covers.

  • hash — Hash token spans and emit raw carry in the same dispatch, except when past_ids and all three optional control tensors need a separate carry pass to stay within eight storage bindings.
  • shared_prefix — Stage each causal prefix once per token in workgroup memory, then distribute contiguous head outputs across lanes. The tile obeys device storage and invocation limits.

Files

Use with @huggingface/kernels

npm install --save-exact @huggingface/kernels@0.0.1-preview.4

Paste the example into a browser app that resolves npm imports. Serve the app over HTTPS or localhost with WebGPU available.

Required output shapes and logical data types are inferred from the supplied inputs and attributes; result tensors are allocated automatically.

The version: 1 option selects the published kernel contract; it is independent of any operator opset, contrib since_version, or model version. It follows the v1 branch as fixes land. To pin exact artifact bytes, pass a 40-character commit revision instead of version.

import { getKernel } from "@huggingface/kernels";

const kernel = await getKernel("webgpu-kernels/com.microsoft.NGramHashMapping", { version: 1 });

const inputIdsTData = Int32Array.of(5);
const multipliersTData = Int32Array.of(11, 13, 17);
const vocabSizesTData = Int32Array.of(101, 103, 107, 109);

const { hashIdsT, presentIdsT } = await kernel({
  inputIdsT: { data: inputIdsTData, shape: [1, 1] },
  multipliersT: { data: multipliersTData, shape: [3] },
  vocabSizesT: { data: vocabSizesTData, shape: [4] },
}, {
  attrs: { max_ngram_size: 3, n_head_per_ngram: 2, pad_id: 9 },
});
console.log({ hashIdsT, presentIdsT });
Downloads last month
-
kernel
webgpu
wgsl
apache-2.0
WebGPU

Requires WebGPU support. See the compatibility table.